"""Groq model provider for fast inference."""

import ssl
import time
from typing import Any, Optional

import httpx
from groq import AsyncGroq

from genesis.models.base import ModelProvider, ModelResponse


class GroqProvider(ModelProvider):
    """Groq model provider - ultra-fast inference."""

    def __init__(self, api_key: Optional[str] = None, **kwargs: Any):
        super().__init__(api_key, **kwargs)
        if api_key:
            # Create HTTP client with SSL context that uses system certificates
            http_client = httpx.AsyncClient(
                verify=ssl.create_default_context(),
                timeout=30.0
            )
            self.client = AsyncGroq(api_key=api_key, http_client=http_client)
        else:
            self.client = None

    def _clean_messages(self, messages: list[dict]) -> list[dict]:
        """Clean messages to only include fields supported by Groq API."""
        return [
            {"role": msg["role"], "content": msg["content"]}
            for msg in messages
        ]

    def is_available(self) -> bool:
        """Check if Groq is available."""
        return self.client is not None

    async def generate(
        self,
        messages: list[dict[str, str]],
        model: str = "openai/gpt-oss-120b",
        temperature: float = 0.7,
        max_tokens: int = 1000,
        **kwargs: Any,
    ) -> ModelResponse:
        """Generate response from Groq."""
        if not self.is_available():
            raise ValueError("Groq API key not configured")

        start_time = time.time()

        # Clean messages - remove Genesis-specific fields
        clean_messages = self._clean_messages(messages)

        # Convert 'functions' to 'tools' format if present (Groq uses new OpenAI tools format)
        if 'functions' in kwargs:
            functions = kwargs.pop('functions')
            # Convert to tools format
            kwargs['tools'] = [
                {
                    'type': 'function',
                    'function': func
                }
                for func in functions
            ]

        response = await self.client.chat.completions.create(
            model=model,
            messages=clean_messages,
            temperature=temperature,
            max_tokens=max_tokens,
            **kwargs,
        )

        latency_ms = (time.time() - start_time) * 1000

        # Check if response has tool calls (function calls)
        message = response.choices[0].message
        model_response = ModelResponse(
            content=message.content or "",
            model=model,
            provider="groq",
            tokens_used=response.usage.total_tokens if response.usage else None,
            latency_ms=latency_ms,
            metadata={"finish_reason": response.choices[0].finish_reason},
        )
        
        # Add function_call if present (convert from tool_calls)
        if hasattr(message, 'tool_calls') and message.tool_calls:
            tool_call = message.tool_calls[0]
            model_response.function_call = {
                'name': tool_call.function.name,
                'arguments': tool_call.function.arguments
            }
        
        return model_response

    async def stream_generate(
        self,
        messages: list[dict[str, str]],
        model: str = "openai/gpt-oss-120b",
        temperature: float = 0.7,
        max_tokens: int = 1000,
        **kwargs: Any,
    ):
        """Stream generate from Groq."""
        if not self.is_available():
            raise ValueError("Groq API key not configured")

        # Clean messages - remove Genesis-specific fields
        clean_messages = self._clean_messages(messages)

        stream = await self.client.chat.completions.create(
            model=model,
            messages=clean_messages,
            temperature=temperature,
            max_tokens=max_tokens,
            stream=True,
            **kwargs,
        )

        async for chunk in stream:
            if chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content
