"""Tests for config.py loading and resolution."""

import os
from pathlib import Path

from corpo.config import DEFAULTS, load_config, resolve


def test_load_config_missing_file(tmp_path):
    """Loading a nonexistent config returns empty dict."""
    result = load_config(tmp_path / "nope.toml")
    assert result == {}


def test_load_config_valid(tmp_path):
    cfg = tmp_path / "config.toml"
    cfg.write_text("""
[identity]
keypair = "/tmp/test.json"

[network]
api_url = "http://localhost:9999"
rpc_url = "https://rpc.example.com"
""")
    result = load_config(cfg)
    assert result["keypair"] == "/tmp/test.json"
    assert result["api_url"] == "http://localhost:9999"


def test_load_config_flattens_sections(tmp_path):
    cfg = tmp_path / "config.toml"
    cfg.write_text("""
[defaults]
realm = "abc123"
governance = "def456"
""")
    result = load_config(cfg)
    assert result["realm"] == "abc123"
    assert result["governance"] == "def456"


def test_resolve_cli_wins():
    """CLI value takes precedence over everything."""
    assert resolve("from-cli", "NOPE", {"key": "from-config"}, "key", "default") == "from-cli"


def test_resolve_env_over_config(monkeypatch):
    """Env var beats config."""
    monkeypatch.setenv("TEST_VAR", "from-env")
    assert resolve(None, "TEST_VAR", {"key": "from-config"}, "key", "default") == "from-env"


def test_resolve_config_over_default():
    """Config beats default."""
    assert resolve(None, "NONEXISTENT_VAR_XYZ", {"key": "from-config"}, "key", "default") == "from-config"


def test_resolve_default():
    """Falls through to default."""
    assert resolve(None, "NONEXISTENT_VAR_XYZ", {}, "key", "the-default") == "the-default"


def test_resolve_empty_cli_skips():
    """Empty CLI string is treated as not set."""
    assert resolve("", "NONEXISTENT_VAR_XYZ", {"key": "cfg"}, "key", "def") == "cfg"
