"""Factory for creating LLM clients based on configuration."""

import logging

from openai import AsyncOpenAI, AsyncAzureOpenAI

from .models import AgentConfig

logger = logging.getLogger(__name__)


def create_llm_client(config: AgentConfig) -> tuple[AsyncOpenAI | AsyncAzureOpenAI, str]:
    """Create appropriate LLM client based on config.

    Args:
        config: Agent configuration with model client settings

    Returns:
        Tuple of (client, model_name)

    Raises:
        ValueError: If required config fields are missing for the selected model type
    """
    if config.model_client_type == "azure":
        if not config.azure_openai_endpoint:
            raise ValueError("Azure config requires azure_openai_endpoint")
        if not config.token_provider:
            raise ValueError("Azure config requires token_provider")
        if not config.azure_openai_deployment:
            raise ValueError("Azure config requires azure_openai_deployment")

        client = AsyncAzureOpenAI(
            azure_endpoint=config.azure_openai_endpoint,
            azure_ad_token_provider=config.token_provider,
            api_version="2024-08-01-preview",
        )
        logger.info(f"[BTQL] Using Azure OpenAI: endpoint={config.azure_openai_endpoint}, deployment={config.azure_openai_deployment}")
        return client, config.azure_openai_deployment

    elif config.model_client_type == "papyrus":
        if not config.papyrus_endpoint:
            raise ValueError("Papyrus config requires papyrus_endpoint")
        if not config.token_provider:
            raise ValueError("Papyrus config requires token_provider")
        if not config.papyrus_deployment:
            raise ValueError("Papyrus config requires papyrus_deployment")

        # Papyrus uses Azure AD auth like Azure OpenAI
        client = AsyncAzureOpenAI(
            azure_endpoint=config.papyrus_endpoint,
            azure_ad_token_provider=config.token_provider,
            api_version="2024-08-01-preview",
        )
        logger.info(f"[BTQL] Using Papyrus: endpoint={config.papyrus_endpoint}, deployment={config.papyrus_deployment}")
        return client, config.papyrus_deployment

    elif config.model_client_type == "copilot":
        if not config.copilot_model:
            raise ValueError("Copilot config requires copilot_model (--model-name or COPILOT_MODEL)")

        # Connect to backend's Copilot proxy (OpenAI-compatible endpoint)
        base_url = f"{config.copilot_endpoint}/api/copilot/v1"
        client = AsyncOpenAI(
            base_url=base_url,
            api_key="not-needed",  # Auth handled by backend/extension
        )
        logger.info(f"[BTQL] Using Copilot proxy: base_url={base_url}, model={config.copilot_model}")
        return client, config.copilot_model

    elif config.model_client_type == "local":
        if not config.local_model:
            raise ValueError("Local config requires local_model (--model-name or LOCAL_MODEL)")

        # Connect to local OpenAI-compatible endpoint (vLLM, Ollama, Agent Maestro, etc.)
        base_url = config.local_endpoint.rstrip("/")
        suffix = "/chat/completions"
        if base_url.endswith(suffix):
            base_url = base_url[: -len(suffix)]
        client = AsyncOpenAI(
            base_url=base_url,
            api_key="not-needed",  # Local models typically don't need auth
        )
        logger.info(f"[BTQL] Using Local model: base_url={base_url}, model={config.local_model}")
        return client, config.local_model

    else:
        raise ValueError(f"Unknown model_client_type: {config.model_client_type}")
