"""LLM client factory — supports Azure OpenAI, OpenAI, and Ollama."""

from __future__ import annotations

import os

from logging_config import get_logger
from openai import AzureOpenAI, OpenAI

log = get_logger(__name__)


def create_llm_client() -> tuple[OpenAI | AzureOpenAI, str]:
    """Create an LLM client based on ``LLM_PROVIDER`` env var.

    Supported providers:
        * ``azure`` (default) — Azure OpenAI
        * ``openai`` — OpenAI direct
        * ``ollama`` — Local Ollama instance

    Returns:
        (client, model/deployment) tuple.
    """
    provider = os.getenv("LLM_PROVIDER", "azure").lower()

    if provider == "azure":
        return _create_azure()
    elif provider == "openai":
        return _create_openai()
    elif provider == "ollama":
        return _create_ollama()
    else:
        raise ValueError(f"Unknown LLM_PROVIDER: {provider!r}. Use 'azure', 'openai', or 'ollama'.")


def _require_env(name: str) -> str:
    value = os.getenv(name)
    if not value:
        raise ValueError(f"Missing required environment variable: {name}")
    return value


def _create_azure() -> tuple[AzureOpenAI, str]:
    endpoint = _require_env("AZURE_OPENAI_ENDPOINT")
    api_key = _require_env("AZURE_OPENAI_API_KEY")
    api_version = os.getenv("AZURE_OPENAI_API_VERSION", "2024-06-01")
    deployment = _require_env("AZURE_OPENAI_DEPLOYMENT")

    log.info("llm_client_created", provider="azure", deployment=deployment)

    client = AzureOpenAI(
        api_key=api_key,
        api_version=api_version,
        azure_endpoint=endpoint,
    )
    return client, deployment


def _create_openai() -> tuple[OpenAI, str]:
    api_key = _require_env("OPENAI_API_KEY")
    model = os.getenv("OPENAI_MODEL", "gpt-4o")

    log.info("llm_client_created", provider="openai", model=model)

    client = OpenAI(api_key=api_key)
    return client, model


def _create_ollama() -> tuple[OpenAI, str]:
    base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
    model = os.getenv("OLLAMA_MODEL", "qwen3.5:4b")

    log.info("llm_client_created", provider="ollama", model=model, base_url=base_url)

    client = OpenAI(base_url=base_url, api_key="ollama")
    return client, model
