"""Shared model-client builders for preset entities."""

from __future__ import annotations

import os
from typing import Any

from agentbyte.llm import (
    AzureOpenAIChatCompletionClient,
    BaseChatCompletionClient,
    OpenAIChatCompletionClient,
)

DEFAULT_OPENAI_MODEL = "gpt-4.1-mini"
DEFAULT_CLIENT_CONFIG = {"temperature": 0.2}


def _resolve_provider(provider: str | None = None) -> str:
    """Resolve a supported provider from explicit input or environment."""
    if provider:
        normalized = provider.strip().lower().replace("_", "-")
        if normalized in {"openai", "azure-openai"}:
            return normalized
        raise ValueError(
            "Unsupported provider. Expected 'openai' or 'azure-openai'."
        )

    if os.getenv("OPENAI_API_KEY"):
        return "openai"
    if os.getenv("AZURE_OPENAI_ENDPOINT"):
        return "azure-openai"

    raise ValueError(
        "Could not infer chat provider. Set OPENAI_API_KEY for OpenAI or "
        "AZURE_OPENAI_ENDPOINT for Azure OpenAI, or pass provider= explicitly."
    )


def build_chat_client(
    provider: str | None = None,
    model: str | None = None,
    *,
    config: dict[str, Any] | None = None,
) -> BaseChatCompletionClient:
    """Build one chat client using OpenAI or Azure OpenAI."""
    resolved_provider = _resolve_provider(provider)
    resolved_config = config or DEFAULT_CLIENT_CONFIG.copy()
    resolved_model = (
        model
        or os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME")
        or os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME")
        or DEFAULT_OPENAI_MODEL
    )

    if resolved_provider == "openai":
        return OpenAIChatCompletionClient.from_api_key(
            model=model or DEFAULT_OPENAI_MODEL,
            config=resolved_config,
        )

    if os.getenv("AZURE_TENANT_ID"):
        return AzureOpenAIChatCompletionClient.from_certificate(
            model=resolved_model,
            config=resolved_config,
        )

    if os.getenv("AZURE_OPENAI_API_KEY"):
        return AzureOpenAIChatCompletionClient.from_api_key(
            model=resolved_model,
            config=resolved_config,
        )

    return AzureOpenAIChatCompletionClient.from_default_credential(
        model=resolved_model,
        config=resolved_config,
    )


__all__ = ["build_chat_client"]
