"""
xAI Client - Grok AI Models

Provides LLM completion via xAI API (Elon Musk's AI company).
xAI develops Grok, trained on X (Twitter) data for real-time information.
"""

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 XAIClient(BaseLM):
    """
    xAI Language Model Client (Grok)

    xAI provides the Grok family of models:
    - Grok 2 (latest, multimodal)
    - Grok 1.5 (function calling)
    - Grok Beta (experimental features)

    Features:
    - Real-time information from X (Twitter)
    - Chat completion
    - Streaming responses
    - Function calling support
    - Image understanding (Grok 2)
    - Token usage tracking
    - OpenAI-compatible API

    Example:
        >>> from groknroll.clients.xai import XAIClient
        >>> client = XAIClient(model_name="grok-2-latest")
        >>> response = await client.acompletion("What's trending on X today?")
        >>> print(response)
    """

    # xAI models (Grok family)
    MODELS = [
        "grok-2-latest",  # Latest Grok 2
        "grok-2-1212",  # Grok 2 December release
        "grok-beta",  # Beta version
        "grok-vision-beta",  # Multimodal beta
    ]

    def __init__(
        self,
        api_key: Optional[str] = None,
        model_name: str = "grok-2-latest",
        base_url: Optional[str] = None,
        **kwargs,
    ):
        """
        Initialize xAI client

        Args:
            api_key: xAI API key (reads from XAI_API_KEY env if not provided)
            model_name: Model to use (default: grok-2-latest)
            base_url: Optional base URL override (default: https://api.x.ai/v1)
            **kwargs: Additional xAI-specific options
        """
        super().__init__(model_name=model_name, **kwargs)

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

        self.model_name = model_name
        self.base_url = base_url or "https://api.x.ai/v1"

        # xAI uses OpenAI-compatible API
        try:
            from openai import OpenAI, AsyncOpenAI
        except ImportError:
            raise ImportError(
                "openai package not found. Install with: pip install openai"
            )

        self.client = OpenAI(
            api_key=self.api_key,
            base_url=self.base_url,
        )
        self.async_client = AsyncOpenAI(
            api_key=self.api_key,
            base_url=self.base_url,
        )

        # 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 xAI client.")

        response = self.client.chat.completions.create(
            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 xAI client.")

        response = await self.async_client.chat.completions.create(
            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,
        )
