import os
from pathlib import Path

import yaml
import pytest
from click.testing import CliRunner

from project_hub.cli import main


def _read_exclude(hub: Path) -> list[str]:
    raw = yaml.safe_load((hub / ".project-hub" / "config.yaml").read_text()) or {}
    return raw.get("exclude") or []


@pytest.fixture(autouse=False)
def in_hub(tmp_hub: Path, monkeypatch: pytest.MonkeyPatch):
    """Change cwd to tmp_hub so CLI resolves .project-hub correctly."""
    monkeypatch.chdir(tmp_hub)
    return tmp_hub


def test_exclude_adds_to_config(in_hub: Path):
    result = CliRunner().invoke(main, ["exclude", "repo-alpha"], catch_exceptions=False)
    assert result.exit_code == 0
    assert "repo-alpha" in _read_exclude(in_hub)


def test_exclude_idempotent(in_hub: Path):
    runner = CliRunner()
    runner.invoke(main, ["exclude", "repo-alpha"], catch_exceptions=False)
    runner.invoke(main, ["exclude", "repo-alpha"], catch_exceptions=False)
    assert _read_exclude(in_hub).count("repo-alpha") == 1


def test_include_removes_from_config(in_hub: Path):
    runner = CliRunner()
    runner.invoke(main, ["exclude", "repo-beta"], catch_exceptions=False)
    assert "repo-beta" in _read_exclude(in_hub)

    result = runner.invoke(main, ["include", "repo-beta"], catch_exceptions=False)
    assert result.exit_code == 0
    assert "repo-beta" not in _read_exclude(in_hub)


def test_include_not_present(in_hub: Path):
    result = CliRunner().invoke(main, ["include", "repo-gamma"], catch_exceptions=False)
    assert result.exit_code == 0
    assert "repo-gamma" not in _read_exclude(in_hub)
