import json

from ccma.config import AppConfig, load_config


def test_paths_and_automation_settings_round_trip(tmp_path, monkeypatch) -> None:
    monkeypatch.setenv("CCMA_CONFIG_DIR", str(tmp_path / "config"))
    expected = AppConfig(
        store_path=str(tmp_path / "members"),
        gnucash_path=str(tmp_path / "club.gnucash"),
        theme_mode="light",
        run_housekeeper_on_startup=False,
        splash_minimum_seconds=0,
        birthday_days_before=10,
        birthday_days_after=3,
        anniversary_days_before=21,
        anniversary_days_after=5,
        anniversary_intervals="30D;2M;1Y;10Y",
        retroactive_claims=True,
        optional_member_fields=("nickname", "email", "phone"),
        window_geometry="1200x800-1800+40",
        window_state="maximized",
        monitor_bounds=(-1920, 0, 1920, 1080),
    )
    expected.save()

    loaded = load_config()
    assert loaded == expected
    raw = json.loads(expected.path.read_text(encoding="utf-8"))
    assert raw["schema_version"] == 1
    assert raw["monitor_bounds"] == [-1920, 0, 1920, 1080]
    assert raw["splash_minimum_seconds"] == 0
    assert raw["retroactive_claims"] is True
    assert raw["optional_member_fields"] == ["nickname", "email", "phone"]


def test_splash_minimum_defaults_to_five_and_is_clamped(tmp_path, monkeypatch) -> None:
    monkeypatch.setenv("CCMA_CONFIG_DIR", str(tmp_path / "config"))
    assert load_config().splash_minimum_seconds == 5.0

    config = AppConfig(splash_minimum_seconds=-10)
    config.save()
    assert load_config().splash_minimum_seconds == 0.0


def test_store_path_can_be_overridden_from_ccma_environment(tmp_path, monkeypatch) -> None:
    monkeypatch.setenv("CCMA_CONFIG_DIR", str(tmp_path / "config"))
    monkeypatch.setenv("CCMA_STORE", str(tmp_path / "store"))

    assert load_config().store_path == str(tmp_path / "store")


def test_gnucash_last_account_per_file_round_trips(tmp_path, monkeypatch) -> None:
    monkeypatch.setenv("CCMA_CONFIG_DIR", str(tmp_path / "config"))
    first_file = str(tmp_path / "verein.gnucash")
    second_file = str(tmp_path / "spenden.gnucash")
    config = AppConfig(
        gnucash_last_accounts={first_file: "bank-guid", second_file: "cash-guid"}
    )
    config.save()

    loaded = load_config()
    assert loaded.gnucash_last_accounts == {first_file: "bank-guid", second_file: "cash-guid"}


def test_gnucash_last_accounts_defaults_to_empty_dict_for_malformed_value(tmp_path, monkeypatch) -> None:
    monkeypatch.setenv("CCMA_CONFIG_DIR", str(tmp_path / "config"))
    config_path = tmp_path / "config" / "config.json"
    config_path.parent.mkdir(parents=True, exist_ok=True)
    config_path.write_text(
        json.dumps({"schema_version": 1, "gnucash_last_accounts": "not-a-dict"}), encoding="utf-8"
    )

    assert load_config().gnucash_last_accounts == {}
