"""Tests for ievo.core.global_config — plaintext config management."""

from __future__ import annotations

import json
from pathlib import Path

from ievo.core.global_config import (
    get_config,
    load_global_config,
    save_global_config,
    set_config,
)


def test_load_creates_default(tmp_path: Path) -> None:
    config = load_global_config(tmp_path)
    assert config["default_model"] == "sonnet"
    assert config["marketplace_url"] == "https://github.com/ievo-ai/marketplace"
    assert config["auto_update_registry"] is True
    # File should now exist
    assert (tmp_path / "config.json").exists()


def test_load_preserves_existing(tmp_path: Path) -> None:
    (tmp_path / "config.json").write_text(json.dumps({"default_model": "opus"}))
    config = load_global_config(tmp_path)
    assert config["default_model"] == "opus"
    # Should merge missing keys from defaults
    assert config["marketplace_url"] == "https://github.com/ievo-ai/marketplace"


def test_save_and_load_roundtrip(tmp_path: Path) -> None:
    data = {"custom_key": "custom_value", "number": 42}
    save_global_config(tmp_path, data)
    loaded = json.loads((tmp_path / "config.json").read_text())
    assert loaded == data


def test_get_config(tmp_path: Path) -> None:
    load_global_config(tmp_path)  # create defaults
    assert get_config(tmp_path, "default_model") == "sonnet"
    assert get_config(tmp_path, "nonexistent") is None


def test_set_config(tmp_path: Path) -> None:
    load_global_config(tmp_path)  # create defaults
    set_config(tmp_path, "default_model", "opus")
    assert get_config(tmp_path, "default_model") == "opus"


def test_set_config_new_key(tmp_path: Path) -> None:
    load_global_config(tmp_path)
    set_config(tmp_path, "custom", "value")
    assert get_config(tmp_path, "custom") == "value"
