from __future__ import annotations

from pathlib import Path

from worai.config import CONFIG_FILENAMES, load_config, resolve_config_path


def test_load_config_profile(tmp_path: Path, monkeypatch) -> None:
    config_path = tmp_path / "worai.toml"
    config_path.write_text(
        """
        [defaults]
        timeout = 10

        [profile.dev]
        timeout = 20
        """
    )

    cfg = load_config(str(config_path), "dev", env={})
    assert cfg.get("defaults.timeout") == 10
    assert cfg.get("timeout") == 20


def test_env_config_override(tmp_path: Path, monkeypatch) -> None:
    config_path = tmp_path / "worai.toml"
    config_path.write_text("[defaults]\nlog_level = 'info'\n")

    env = {"WORAI_CONFIG": str(config_path)}
    cfg = load_config(None, None, env=env)
    assert cfg.get("defaults.log_level") == "info"


def test_resolve_config_path_prefers_cli_option(tmp_path: Path) -> None:
    config_path = tmp_path / "myconfig.toml"
    resolved = resolve_config_path(str(config_path), env={})
    assert resolved == config_path.resolve()


def test_resolve_config_path_uses_env(tmp_path: Path) -> None:
    config_path = tmp_path / "envconfig.toml"
    env = {"WORAI_CONFIG": str(config_path)}
    resolved = resolve_config_path(None, env=env)
    assert resolved == config_path.resolve()


def test_resolve_config_path_defaults_when_no_files(monkeypatch) -> None:
    monkeypatch.setattr(Path, "exists", lambda _self: False)
    resolved = resolve_config_path(None, env={})
    assert resolved == Path(CONFIG_FILENAMES[0]).expanduser().resolve()


def test_resolve_config_path_uses_nearest_parent_worai_toml(tmp_path: Path, monkeypatch) -> None:
    project = tmp_path / "project"
    nested = project / "a" / "b"
    nested.mkdir(parents=True)
    config_path = project / "worai.toml"
    config_path.write_text("[profiles.default]\napi_key='wl'\n", encoding="utf-8")

    monkeypatch.chdir(nested)
    resolved = resolve_config_path(None, env={})
    assert resolved == config_path.resolve()
