"""Config precedence: env > file > default, and a typo in the file is an error."""

import pytest
from conftest import write_toml

from askcli import DEFAULTS, Config, load_config


def test_defaults_apply_when_nothing_else_sets_a_key(tmp_path):
    for path in (None, tmp_path / "missing.toml"):
        cfg = load_config(DEFAULTS, path, env={})
        assert isinstance(cfg, Config), (
            f"load_config(DEFAULTS, {path!r}, env={{}}) returned {cfg!r}, want a Config"
        )
        want = Config(model_name="tiny-local", timeout_s=30.0, log_level="INFO")
        assert cfg == want, f"no file, no env (path={path!r}): got {cfg!r}, want {want!r}"


def test_file_beats_default(tmp_path):
    path = write_toml(tmp_path, 'model_name = "gpt-large"\ntimeout_s = 12.5\n')
    cfg = load_config(DEFAULTS, path, env={})
    assert isinstance(cfg, Config), f"load_config returned {cfg!r}, want a Config"
    assert cfg.model_name == "gpt-large", (
        f"file says gpt-large, default says tiny-local; got model_name={cfg.model_name!r}"
    )
    assert cfg.timeout_s == 12.5, f"file says timeout_s = 12.5; got {cfg.timeout_s!r}"
    assert cfg.log_level == "INFO", (
        f"the file does not set log_level, so the default INFO stands; got {cfg.log_level!r}"
    )


def test_env_beats_file(tmp_path):
    path = write_toml(tmp_path, 'model_name = "gpt-large"\ntimeout_s = 12.5\n')
    env = {
        "ASKCLI_MODEL_NAME": "gpt-mini",
        "ASKCLI_TIMEOUT_S": "5",
        "MODEL_NAME": "not-mine",  # no ASKCLI_ prefix: somebody else's variable
        "HOME": "/home/someone",
    }
    cfg = load_config(DEFAULTS, path, env=env)
    assert isinstance(cfg, Config), f"load_config returned {cfg!r}, want a Config"
    assert cfg.model_name == "gpt-mini", (
        "env ASKCLI_MODEL_NAME=gpt-mini, file gpt-large, default tiny-local; "
        f"got {cfg.model_name!r} "
        "— the environment is the top layer"
    )
    assert cfg.timeout_s == 5.0 and isinstance(cfg.timeout_s, float), (
        f"env ASKCLI_TIMEOUT_S='5' must beat the file's 12.5 AND arrive as the float 5.0; "
        f"got {cfg.timeout_s!r} ({type(cfg.timeout_s).__name__})"
    )
    assert cfg.log_level == "INFO", (
        f"nobody overrides log_level, so the default INFO stands; got {cfg.log_level!r}"
    )


def test_unknown_key_in_file_raises(tmp_path):
    path = write_toml(tmp_path, 'modle_name = "gpt-large"\n')
    try:
        got = load_config(DEFAULTS, path, env={})
    except ValueError as exc:
        assert "modle_name" in str(exc), (
            f"the error should name the bad key 'modle_name'; it says {exc!s}"
        )
        return
    pytest.fail(
        f"a file with the typo 'modle_name' loaded without complaint: {got!r} "
        "— it must raise ValueError"
    )
