"""Native Google Gemini connector using the modern ``google-genai`` SDK.

Replaces the deprecated ``google-generativeai`` package. The system instruction
and generation options go through ``GenerateContentConfig``; conversation roles
are mapped to Gemini's ``user`` / ``model`` convention. Safety filters are
relaxed because security tooling output routinely trips default blocks.
"""

from __future__ import annotations

from typing import Any

from pentestgpt_legacy.llm.base import BaseProvider, Message
from pentestgpt_legacy.llm.registry import ModelSpec


class GeminiProvider(BaseProvider):
    """Async Google Gemini provider (google-genai)."""

    async def acomplete(
        self,
        messages: list[Message],
        system: str | None,
        spec: ModelSpec,
        *,
        max_output_tokens: int | None = None,
        temperature: float | None = None,
    ) -> str:
        try:
            from google import genai
            from google.genai import types
        except ImportError as exc:  # pragma: no cover - install-time guard
            raise RuntimeError(
                "The 'google-genai' package is required. Install with: uv add google-genai"
            ) from exc

        contents: list[Any] = []
        for message in messages:
            role = "user" if message["role"] == "user" else "model"
            contents.append(
                types.Content(role=role, parts=[types.Part.from_text(text=message["content"])])
            )

        # Relax safety filters — security tooling output routinely trips defaults.
        safety_categories = (
            types.HarmCategory.HARM_CATEGORY_HARASSMENT,
            types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
            types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
            types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
        )
        safety = [
            types.SafetySetting(category=category, threshold=types.HarmBlockThreshold.BLOCK_NONE)
            for category in safety_categories
        ]
        config = types.GenerateContentConfig(
            system_instruction=system or None,
            temperature=temperature,
            max_output_tokens=max_output_tokens,
            safety_settings=safety,
        )

        client = genai.Client(api_key=self.api_key or "")
        response = await client.aio.models.generate_content(
            model=spec.api_id, contents=contents, config=config
        )
        return response.text or ""
