import pytest
from pathlib import Path
from project_hub.core.config import Config, load_config


def test_load_default_config(tmp_hub: Path):
    """Minimal config file: non-specified fields use defaults."""
    config_path = tmp_hub / ".project-hub" / "config.yaml"
    # tmp_hub already has a minimal config (just forges); verify defaults kick in
    cfg = load_config(config_path)
    assert cfg.pull_strategy == "merge"
    assert cfg.cache_ttl == 300
    assert cfg.http_port == 8400
    assert cfg.watch_mrs_mode == "mine"


def test_load_custom_config(tmp_hub: Path):
    """Custom values override defaults."""
    config_path = tmp_hub / ".project-hub" / "config.yaml"
    config_path.write_text(
        "pull:\n  strategy: rebase\ncache_ttl: 60\n"
    )
    cfg = load_config(config_path)
    assert cfg.pull_strategy == "rebase"
    assert cfg.cache_ttl == 60
    # non-specified fields stay at defaults
    assert cfg.http_port == 8400
    assert cfg.watch_mrs_mode == "mine"


def test_load_with_include_exclude(tmp_hub: Path):
    """include string and exclude list are parsed correctly."""
    config_path = tmp_hub / ".project-hub" / "config.yaml"
    config_path.write_text(
        "include: 'repo-*'\nexclude:\n  - repo-gamma\n"
    )
    cfg = load_config(config_path)
    assert cfg.include == "repo-*"
    assert cfg.exclude == ["repo-gamma"]


def test_missing_config_uses_defaults(tmp_path: Path):
    """Non-existent config file returns a Config with all defaults."""
    cfg = load_config(tmp_path / "does-not-exist.yaml")
    assert cfg.pull_strategy == "merge"
    assert cfg.cache_ttl == 300
    assert cfg.http_port == 8400
    assert cfg.watch_mrs_mode == "mine"
    assert cfg.include is None
    assert cfg.exclude == []
    assert cfg.forges == {}


def test_unknown_keys_ignored(tmp_hub: Path):
    """Config with unknown keys loads without error."""
    config_path = tmp_hub / ".project-hub" / "config.yaml"
    config_path.write_text("unknown_key: whatever\nanother_unknown: 42\n")
    cfg = load_config(config_path)
    assert cfg.pull_strategy == "merge"  # default preserved


def test_malformed_yaml_exits(tmp_hub: Path):
    """Invalid YAML raises SystemExit."""
    config_path = tmp_hub / ".project-hub" / "config.yaml"
    config_path.write_text("key: [unclosed\n")
    with pytest.raises(SystemExit):
        load_config(config_path)
