"""Tests for milco.toml LLM config loading."""

import pytest
from milco.llm.config import load_llm_config, resolve_provider


def test_load_config_missing_file(tmp_path):
    cfg = load_llm_config(tmp_path)
    assert cfg is None


def test_load_config_no_llm_section(tmp_path):
    (tmp_path / "milco.toml").write_text("[tool]\nfoo = 1\n", encoding="utf-8")
    cfg = load_llm_config(tmp_path)
    assert cfg is None


def test_load_config_ollama(tmp_path):
    toml_text = '[llm]\nprovider = "ollama"\nmodel = "llama3"\n'
    (tmp_path / "milco.toml").write_text(toml_text, encoding="utf-8")
    cfg = load_llm_config(tmp_path)
    assert cfg["provider"] == "ollama"
    assert cfg["model"] == "llama3"


def test_load_config_openai_with_base_url(tmp_path):
    toml_text = (
        '[llm]\nprovider = "openai"\nmodel = "gpt-4o"\n'
        'base_url = "http://localhost:1234/v1"\n\n'
        '[llm.openai]\napi_key_env = "MY_KEY"\n'
    )
    (tmp_path / "milco.toml").write_text(toml_text, encoding="utf-8")
    cfg = load_llm_config(tmp_path)
    assert cfg["provider"] == "openai"
    assert cfg["base_url"] == "http://localhost:1234/v1"
    assert cfg["openai"]["api_key_env"] == "MY_KEY"


def test_resolve_provider_ollama(tmp_path):
    toml_text = '[llm]\nprovider = "ollama"\nmodel = "llama3"\n'
    (tmp_path / "milco.toml").write_text(toml_text, encoding="utf-8")
    provider = resolve_provider(tmp_path)
    assert provider is not None
    assert provider.name == "ollama"
    assert provider.model == "llama3"


def test_resolve_provider_openai(tmp_path, monkeypatch):
    toml_text = (
        '[llm]\nprovider = "openai"\nmodel = "gpt-4o"\n\n'
        '[llm.openai]\napi_key_env = "TEST_OPENAI_KEY"\n'
    )
    (tmp_path / "milco.toml").write_text(toml_text, encoding="utf-8")
    monkeypatch.setenv("TEST_OPENAI_KEY", "sk-fake-key")
    provider = resolve_provider(tmp_path)
    assert provider is not None
    assert provider.name == "openai"
    assert provider.api_key == "sk-fake-key"


def test_resolve_provider_openai_missing_key(tmp_path):
    toml_text = (
        '[llm]\nprovider = "openai"\nmodel = "gpt-4o"\n\n'
        '[llm.openai]\napi_key_env = "NONEXISTENT_KEY_12345"\n'
    )
    (tmp_path / "milco.toml").write_text(toml_text, encoding="utf-8")
    with pytest.raises(ValueError, match="not set"):
        resolve_provider(tmp_path)


def test_resolve_provider_none_when_no_config(tmp_path):
    provider = resolve_provider(tmp_path)
    assert provider is None


def test_resolve_provider_unknown_provider(tmp_path):
    toml_text = '[llm]\nprovider = "banana"\nmodel = "x"\n'
    (tmp_path / "milco.toml").write_text(toml_text, encoding="utf-8")
    with pytest.raises(ValueError, match="Unknown"):
        resolve_provider(tmp_path)
