"""Build an LLM client from configuration.

Phase 2 ships OpenRouter (cloud default) and Ollama (local). Other providers in
the config enum are wired in later phases.
"""

from __future__ import annotations

from legate.config import Settings, get_settings
from legate.llm.base import LLMClient, LLMError
from legate.llm.ollama import OllamaClient
from legate.llm.openrouter import OpenRouterClient


def build_llm_client(provider: str | None = None, settings: Settings | None = None) -> LLMClient:
    settings = settings or get_settings()
    provider = (provider or settings.llm_provider or "openrouter").lower()

    if provider == "openrouter":
        if not settings.llm_api_key:
            raise LLMError("LLM_API_KEY is required for the openrouter provider")
        return OpenRouterClient(api_key=settings.llm_api_key, base_url=settings.openrouter_base_url)
    if provider == "ollama":
        return OllamaClient(base_url=settings.ollama_base_url)

    raise LLMError(
        f"unsupported LLM provider '{provider}'; available in this build: openrouter, ollama"
    )
