from __future__ import annotations

from cli.config import CONFIG_DIR_ENV, CLIConfig, ConfigStore


def test_config_store_roundtrip(tmp_path, monkeypatch):
    monkeypatch.setenv(CONFIG_DIR_ENV, str(tmp_path))
    store = ConfigStore()

    saved = CLIConfig(
        api_base_url="https://api.example.com", default_project="core", use_mock_client=False
    )
    store.save(saved)

    loaded = store.load()
    assert loaded == saved


def test_env_overrides_take_precedence(tmp_path, monkeypatch):
    monkeypatch.setenv(CONFIG_DIR_ENV, str(tmp_path))
    monkeypatch.setenv("CLI__DEFAULT_PROJECT", "env-project")
    monkeypatch.setenv("CLI__API_BASE_URL", "https://env.example.com")

    store = ConfigStore()
    store.save(
        CLIConfig(
            api_base_url="https://file.example.com",
            default_project="file-project",
        )
    )

    loaded = store.load()
    assert loaded.default_project == "env-project"
    assert loaded.api_base_url == "https://env.example.com"

    monkeypatch.delenv("CLI__DEFAULT_PROJECT")
    monkeypatch.delenv("CLI__API_BASE_URL")


def test_empty_env_values_do_not_override_saved_config(tmp_path, monkeypatch):
    monkeypatch.setenv(CONFIG_DIR_ENV, str(tmp_path))
    monkeypatch.setenv("CLI__DEFAULT_PROJECT", "")
    monkeypatch.setenv("CLI__API_BASE_URL", "")

    store = ConfigStore()
    store.save(
        CLIConfig(
            api_base_url="https://file.example.com",
            default_project="file-project",
        )
    )

    loaded = store.load()
    assert loaded.default_project == "file-project"
    assert loaded.api_base_url == "https://file.example.com"

    monkeypatch.delenv("CLI__DEFAULT_PROJECT")
    monkeypatch.delenv("CLI__API_BASE_URL")
