"""
Mistral AI Client - European AI Excellence

Provides LLM completion via Mistral AI API.
Mistral AI is a European AI company known for high-quality open-source models.
"""

import os
from collections import defaultdict
from typing import Any, Optional

from groknroll.clients.base_lm import BaseLM
from groknroll.core.types import ModelUsageSummary, UsageSummary


class MistralClient(BaseLM):
    """
    Mistral AI Language Model Client

    Mistral AI provides powerful open-source and commercial models:
    - Mistral Large 2 (128k context)
    - Mistral Small
    - Codestral (code generation)
    - Mistral-Embed (embeddings)

    Features:
    - Chat completion
    - Streaming responses
    - Function calling support
    - 128k context window (Large model)
    - Token usage tracking

    Example:
        >>> from groknroll.clients.mistral import MistralClient
        >>> client = MistralClient(model_name="mistral-large-latest")
        >>> response = await client.acompletion("Explain AI safety")
        >>> print(response)
    """

    # Mistral AI models
    MODELS = [
        "mistral-large-latest",  # Latest Mistral Large (128k context)
        "mistral-small-latest",  # Mistral Small
        "codestral-latest",  # Code generation specialist
        "mistral-embed",  # Embeddings model
        "open-mistral-7b",  # Open source 7B
        "open-mixtral-8x7b",  # Open source Mixtral
        "open-mixtral-8x22b",  # Open source Mixtral 8x22B
    ]

    def __init__(
        self,
        api_key: Optional[str] = None,
        model_name: str = "mistral-large-latest",
        base_url: Optional[str] = None,
        **kwargs,
    ):
        """
        Initialize Mistral AI client

        Args:
            api_key: Mistral API key (reads from MISTRAL_API_KEY env if not provided)
            model_name: Model to use (default: mistral-large-latest)
            base_url: Optional base URL override
            **kwargs: Additional Mistral-specific options
        """
        super().__init__(model_name=model_name, **kwargs)

        self.api_key = api_key or os.getenv("MISTRAL_API_KEY")
        if not self.api_key:
            raise ValueError(
                "Mistral API key not found. Set MISTRAL_API_KEY environment variable or pass api_key parameter."
            )

        self.model_name = model_name
        self.base_url = base_url

        # Initialize Mistral SDK
        try:
            from mistralai import Mistral
        except ImportError:
            raise ImportError(
                "mistralai package not found. Install with: pip install mistralai"
            )

        self.client = Mistral(api_key=self.api_key)

        # Per-model usage tracking
        self.model_call_counts: dict[str, int] = defaultdict(int)
        self.model_input_tokens: dict[str, int] = defaultdict(int)
        self.model_output_tokens: dict[str, int] = defaultdict(int)
        self.model_total_tokens: dict[str, int] = defaultdict(int)

        # Last call tracking
        self.last_prompt_tokens = 0
        self.last_completion_tokens = 0

    def completion(
        self,
        prompt: str | list[dict[str, Any]],
        model: Optional[str] = None,
    ) -> str:
        """
        Synchronous completion

        Args:
            prompt: User prompt (string or messages list)
            model: Model to use (defaults to self.model_name)

        Returns:
            Generated text string
        """
        if isinstance(prompt, str):
            messages = [{"role": "user", "content": prompt}]
        elif isinstance(prompt, list) and all(isinstance(item, dict) for item in prompt):
            messages = prompt
        else:
            raise ValueError(f"Invalid prompt type: {type(prompt)}")

        model = model or self.model_name
        if not model:
            raise ValueError("Model name is required for Mistral client.")

        response = self.client.chat.complete(
            model=model,
            messages=messages,
        )

        self._track_cost(response, model)
        return response.choices[0].message.content

    async def acompletion(
        self,
        prompt: str | list[dict[str, Any]],
        model: Optional[str] = None,
    ) -> str:
        """
        Asynchronous completion

        Args:
            prompt: User prompt (string or messages list)
            model: Model to use (defaults to self.model_name)

        Returns:
            Generated text string
        """
        if isinstance(prompt, str):
            messages = [{"role": "user", "content": prompt}]
        elif isinstance(prompt, list) and all(isinstance(item, dict) for item in prompt):
            messages = prompt
        else:
            raise ValueError(f"Invalid prompt type: {type(prompt)}")

        model = model or self.model_name
        if not model:
            raise ValueError("Model name is required for Mistral client.")

        response = await self.client.chat.complete_async(
            model=model,
            messages=messages,
        )

        self._track_cost(response, model)
        return response.choices[0].message.content

    def _track_cost(self, response, model: str):
        """Track token usage from API response"""
        self.model_call_counts[model] += 1

        usage = getattr(response, "usage", None)
        if usage is None:
            raise ValueError("No usage data received. Tracking tokens not possible.")

        self.model_input_tokens[model] += usage.prompt_tokens
        self.model_output_tokens[model] += usage.completion_tokens
        self.model_total_tokens[model] += usage.total_tokens

        # Track last call for handler to read
        self.last_prompt_tokens = usage.prompt_tokens
        self.last_completion_tokens = usage.completion_tokens

    def get_usage_summary(self) -> UsageSummary:
        """Get usage statistics across all models"""
        model_summaries = {}
        for model in self.model_call_counts:
            model_summaries[model] = ModelUsageSummary(
                total_calls=self.model_call_counts[model],
                total_input_tokens=self.model_input_tokens[model],
                total_output_tokens=self.model_output_tokens[model],
            )
        return UsageSummary(model_usage_summaries=model_summaries)

    def get_last_usage(self) -> ModelUsageSummary:
        """Get usage statistics from last completion"""
        return ModelUsageSummary(
            total_calls=1,
            total_input_tokens=self.last_prompt_tokens,
            total_output_tokens=self.last_completion_tokens,
        )
