"""Tests for gwtm.config — config loading and management."""

from pathlib import Path

import yaml
import pytest

from gwtm.config import GwtConfig, load_config, ensure_global_config, get_all_managed_repos


class TestGwtConfig:
    def test_defaults(self) -> None:
        config = GwtConfig()
        assert config.branch_prefix == "wt/"
        assert config.default_base_branch == "main"
        assert config.sync_strategy == "rebase"
        assert config.auto_fetch is True
        assert config.clone_base is None

    def test_repo_worktrees_dir(self) -> None:
        config = GwtConfig(worktrees_base=Path("/tmp/wt"))
        assert config.repo_worktrees_dir("my-repo") == Path("/tmp/wt/my-repo")


class TestLoadConfig:
    def test_loads_defaults_when_no_files(self, gwt_config: Path) -> None:
        config = load_config()
        assert config.branch_prefix == "wt/"
        assert config.default_base_branch == "main"

    def test_global_config_overrides_defaults(self, gwt_config: Path) -> None:
        config_file = gwt_config / "config.yaml"
        config_file.write_text(yaml.dump({
            "branch_prefix": "feature/",
            "default_base_branch": "develop",
        }))

        config = load_config()
        assert config.branch_prefix == "feature/"
        assert config.default_base_branch == "develop"
        # Non-overridden values stay default
        assert config.sync_strategy == "rebase"

    def test_repo_config_overrides_global(self, gwt_config: Path, tmp_path: Path) -> None:
        # Write global config
        config_file = gwt_config / "config.yaml"
        config_file.write_text(yaml.dump({
            "default_base_branch": "main",
        }))

        # Write per-repo config
        repo_root = tmp_path / "repo"
        repo_root.mkdir()
        (repo_root / ".gwtconfig.yaml").write_text(yaml.dump({
            "default_base_branch": "develop",
        }))

        config = load_config(repo_root)
        assert config.default_base_branch == "develop"

    def test_ignores_unknown_keys(self, gwt_config: Path) -> None:
        config_file = gwt_config / "config.yaml"
        config_file.write_text(yaml.dump({
            "unknown_key": "value",
            "branch_prefix": "custom/",
        }))

        config = load_config()
        assert config.branch_prefix == "custom/"
        assert not hasattr(config, "unknown_key")

    def test_expands_paths(self, gwt_config: Path) -> None:
        config_file = gwt_config / "config.yaml"
        config_file.write_text(yaml.dump({
            "worktrees_base": "~/my-worktrees",
        }))

        config = load_config()
        assert "~" not in str(config.worktrees_base)


class TestEnsureGlobalConfig:
    def test_creates_config_when_missing(self, gwt_config: Path) -> None:
        config_file = gwt_config / "config.yaml"
        # Remove the pre-created config so ensure_global_config will create it
        config_file.unlink(missing_ok=True)

        ensure_global_config()
        assert config_file.exists()

        data = yaml.safe_load(config_file.read_text())
        assert data["worktrees_base"] == "~/.worktrees"
        assert data["branch_prefix"] == "wt/"

    def test_does_not_overwrite_existing(self, gwt_config: Path) -> None:
        config_file = gwt_config / "config.yaml"
        config_file.write_text("custom: true\n")

        ensure_global_config()
        assert config_file.read_text() == "custom: true\n"


class TestGetAllManagedRepos:
    def test_returns_empty_when_no_worktrees(self, gwt_config: Path, tmp_path: Path) -> None:
        repos = get_all_managed_repos()
        assert repos == []

    def test_finds_repos(self, gwt_config: Path, tmp_path: Path) -> None:
        import gwtm.config as config_mod
        wt_base = config_mod.WORKTREES_BASE
        (wt_base / "repo-a").mkdir(parents=True)
        (wt_base / "repo-b").mkdir(parents=True)

        repos = get_all_managed_repos()
        assert repos == ["repo-a", "repo-b"]
