"""LLM resource for Agent Berlin SDK."""

from typing import Dict, List, Optional

from .._http import HTTPClient
from ..models.llm import LLMCompleteResponse, LLMSearchResponse


class LLMResource:
    """Resource for LLM operations.

    Provides AI-powered web search using Perplexity, ChatGPT, or Gemini,
    and text completion using Claude, GPT, or Gemini.

    Example:
        # Search with Perplexity
        result = client.llm.search(
            model="sonar",
            user_query="What are the best SEO practices for 2024?",
        )
        print(result.content)
        for citation in result.citations:
            print(f"  Source: {citation.url}")

        # Text completion with Claude
        result = client.llm.complete(
            model="claude-sonnet-4-6",
            messages=[{"role": "user", "content": "Hello!"}],
            max_tokens=1024,
        )
        print(result.content)
    """

    def __init__(self, http: HTTPClient) -> None:
        self._http = http

    def search(
        self,
        model: str,
        user_query: str,
        *,
        system_prompt: Optional[str] = None,
        max_tokens: Optional[int] = None,
    ) -> LLMSearchResponse:
        """Perform an LLM-powered web search with citations.

        Supports multiple AI providers (Perplexity, OpenAI, Gemini) with
        automatic routing based on the model name.

        Args:
            model: Model to use for the search. Supported models:
                   - Perplexity: sonar, sonar-pro
                   - OpenAI: gpt-5-mini, gpt-5.4
                   - Gemini: gemini-3-flash, gemini-3-pro-preview
            user_query: The search query or question to answer.
            system_prompt: Optional system prompt to guide the AI's behavior.
            max_tokens: Maximum tokens in the response.

        Returns:
            LLMSearchResponse with generated content, citations, and usage stats.
        """
        payload: dict[str, object] = {
            "model": model,
            "user_query": user_query,
        }
        if system_prompt is not None:
            payload["system_prompt"] = system_prompt
        if max_tokens is not None:
            payload["max_tokens"] = max_tokens

        data = self._http.post("/llm/search", json=payload)
        return LLMSearchResponse.model_validate(data)

    def complete(
        self,
        model: str,
        messages: List[Dict[str, str]],
        *,
        system_prompt: Optional[str] = None,
        max_tokens: Optional[int] = None,
    ) -> LLMCompleteResponse:
        """Complete a conversation using Claude, GPT, or Gemini models.

        This method calls the LLM API directly (not through a proxy) for
        text completion tasks like chat, code generation, and analysis.

        Args:
            model: Model to use. Supported models:
                   - Claude: claude-sonnet-4-6, claude-opus-4-6, claude-haiku-4-5
                   - GPT: gpt-5-mini, gpt-5-nano, gpt-5.4, gpt-5.4-pro
                   - Gemini: gemini-3-flash, gemini-3-pro-preview
            messages: List of conversation messages, each with 'role' and 'content'.
                     Roles: 'user', 'assistant'.
            system_prompt: Optional system prompt to guide the AI's behavior.
            max_tokens: Maximum tokens in the response. Required for Claude models.

        Returns:
            LLMCompleteResponse with generated content and usage stats.

        Example:
            result = client.llm.complete(
                model="claude-sonnet-4-6",
                messages=[
                    {"role": "user", "content": "What is Python?"}
                ],
                system_prompt="Be concise.",
                max_tokens=500,
            )
            print(result.content)
        """
        payload: dict[str, object] = {
            "model": model,
            "messages": messages,
        }
        if system_prompt is not None:
            payload["system_prompt"] = system_prompt
        if max_tokens is not None:
            payload["max_tokens"] = max_tokens

        data = self._http.post("/llm/complete", json=payload)
        return LLMCompleteResponse.model_validate(data)
