"""Google Gemini API provider."""

from __future__ import annotations

from typing import Any

import google.generativeai as genai

from ..utils.logger import Logger
from .base_provider import BaseProvider


class GeminiProvider(BaseProvider):
    """Provider using Google Gemini API."""

    name = "Gemini"
    type = "api"

    def __init__(self, api_key: str, model: str = "gemini-pro") -> None:
        self.api_key = api_key
        self.model = model
        genai.configure(api_key=api_key)

    def test_connection(self) -> bool:
        """Test API connection."""
        try:
            model = genai.GenerativeModel(self.model)
            # Simple test - just check if we can create the model
            _ = model.generate_content("Hello", generation_config={"max_output_tokens": 5})
            return True
        except Exception as e:
            Logger.error("Gemini connection test failed", e)
            return False

    def execute(self, skill_content: str, user_input: str, context: dict[str, Any]) -> str:
        """Execute task using Gemini API."""
        system_prompt = self._build_system_prompt(skill_content, context)

        Logger.info("Executing with Gemini", {"model": self.model, "input": user_input[:100]})

        try:
            model = genai.GenerativeModel(self.model)

            # Combine system prompt with user input
            full_prompt = f"{system_prompt}\n\nUser request: {user_input}"

            response = model.generate_content(
                full_prompt, generation_config={"temperature": 0.7, "max_output_tokens": 4000}
            )

            return response.text if response.text else ""

        except Exception as e:
            Logger.error("Gemini execution failed", e)
            raise RuntimeError(f"Gemini API error: {e}")

    def _build_system_prompt(self, skill_content: str, context: dict[str, Any]) -> str:
        """Build system prompt."""
        prompt = (
            "You are a marketing assistant for Reply Cash, "
            "a stablecoin-to-mobile-money payment platform."
        )

        if skill_content:
            prompt += f"\n\n{skill_content}"

        skill = context.get("skill")
        if skill:
            prompt += f"\n\nCurrent task: Use the {skill} skill to help the user."

        prompt += """

Guidelines:
- Be concise and actionable
- Focus on Reply Cash's value proposition
- Always suggest next steps
- If creating content, mention you'll submit it for approval"""

        return prompt

    def get_model(self) -> str:
        """Get model name."""
        return self.model
