"""Load LLM configuration from milco.toml."""

from __future__ import annotations

import os
import pathlib
import sys
from typing import Any

if sys.version_info >= (3, 11):
    import tomllib
else:
    try:
        import tomllib
    except ModuleNotFoundError:
        import tomli as tomllib  # type: ignore[no-redef]

from milco.llm.base import LLMProvider
from milco.llm.ollama import OllamaProvider
from milco.llm.openai import OpenAIProvider


def load_llm_config(repo_root: pathlib.Path) -> dict[str, Any] | None:
    toml_path = repo_root / "milco.toml"
    if not toml_path.exists():
        return None
    with open(toml_path, "rb") as f:
        data = tomllib.load(f)
    return data.get("llm")


def resolve_provider(repo_root: pathlib.Path) -> LLMProvider | None:
    cfg = load_llm_config(repo_root)
    if cfg is None:
        return None

    provider_name = cfg.get("provider", "")
    model = cfg.get("model", "")
    base_url = cfg.get("base_url")

    if provider_name == "ollama":
        return OllamaProvider(model=model, base_url=base_url)

    if provider_name == "openai":
        openai_cfg = cfg.get("openai", {})
        key_env = openai_cfg.get("api_key_env", "OPENAI_API_KEY")
        api_key = os.environ.get(key_env)
        if not api_key:
            raise ValueError(
                f"Environment variable '{key_env}' not set. "
                f"Set it or update milco.toml [llm.openai].api_key_env."
            )
        return OpenAIProvider(model=model, api_key=api_key, base_url=base_url)

    raise ValueError(
        f"Unknown LLM provider: '{provider_name}'. Use 'ollama' or 'openai'."
    )
