from typing import List, Dict
from .base import BaseProvider


class GeminiProvider(BaseProvider):
    """Google Gemini provider — free tier available."""

    def __init__(self, api_key: str, model: str = "gemini-1.5-flash"):
        super().__init__(api_key, model)

    def complete(self, messages: List[Dict], system_prompt: str = "") -> str:
        try:
            import google.generativeai as genai
        except ImportError:
            raise ImportError("Run: pip install google-generativeai")

        genai.configure(api_key=self.api_key)
        model = genai.GenerativeModel(
            model_name=self.model,
            system_instruction=system_prompt or "You are a helpful AI assistant."
        )

        # Convert messages to Gemini format
        history = []
        last_user_msg = ""
        for msg in messages:
            if msg["role"] == "user":
                last_user_msg = msg["content"]
                history.append({"role": "user", "parts": [msg["content"]]})
            elif msg["role"] == "assistant":
                history.append({"role": "model", "parts": [msg["content"]]})

        chat = model.start_chat(history=history[:-1] if history else [])
        response = chat.send_message(last_user_msg)
        return response.text
