from __future__ import annotations

import asyncio
from pathlib import Path

import pytest

from reddit_mcp import cli as cli_module
from reddit_mcp import uninstall as uninstall_module


@pytest.mark.anyio
async def test_setup_uses_shared_registration_and_skill_install(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    class FakeTokenManager:
        def __init__(self, *_args: object, **_kwargs: object) -> None:
            pass

        async def get_valid_token(self) -> str:
            return "pat_ready"

    cookie_calls: dict[str, bool] = {}
    register_calls: dict[str, object] = {}
    install_calls: dict[str, bool] = {}

    async def fake_setup_cookies(*_args: object, **_kwargs: object) -> dict[str, str]:
        cookie_calls["called"] = True
        return {"reddit_session": "ok"}

    def fake_register_all(*, server_name: str, runtime: str, launcher_path: Path | str) -> None:
        register_calls["server_name"] = server_name
        register_calls["runtime"] = runtime
        register_calls["launcher_path"] = str(launcher_path)

    def fake_install_skills() -> None:
        install_calls["called"] = True

    monkeypatch.setattr(cli_module, "TokenManager", FakeTokenManager)
    monkeypatch.setattr("reddit_mcp.cookie_manager.setup_cookies", fake_setup_cookies)
    monkeypatch.setattr(
        cli_module,
        "write_uvx_launcher",
        lambda **_kwargs: tmp_path / "launcher.py",
    )
    monkeypatch.setattr(cli_module, "register_all", fake_register_all, raising=False)
    monkeypatch.setattr(
        cli_module,
        "_register_mcp_clients",
        lambda *_args, **_kwargs: (_ for _ in ()).throw(
            AssertionError("legacy _register_mcp_clients path should not be used")
        ),
        raising=False,
    )
    monkeypatch.setattr(
        cli_module,
        "_install_bundled_skills",
        fake_install_skills,
        raising=False,
    )

    await cli_module._async_setup()

    assert cookie_calls.get("called") is True
    assert register_calls.get("server_name") == "reddit-mcp"
    assert register_calls.get("runtime") == "python3"
    assert register_calls.get("launcher_path") == str(tmp_path / "launcher.py")
    assert install_calls.get("called") is True


def test_help_contains_install_skills_command(capsys: pytest.CaptureFixture[str]) -> None:
    cli_module._print_help()
    out = capsys.readouterr().out
    assert "reddit-mcp install-skills" in out


def test_uninstall_uses_shared_unregister(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    cfg_dir = tmp_path / ".reddit-mcp"
    cfg_dir.mkdir(parents=True, exist_ok=True)

    calls: dict[str, object] = {}

    def fake_unregister_all(*, server_name: str) -> None:
        calls["server_name"] = server_name

    monkeypatch.setattr(uninstall_module, "CONFIG_DIR", cfg_dir)
    monkeypatch.setattr(uninstall_module, "unregister_all", fake_unregister_all, raising=False)
    monkeypatch.setattr(uninstall_module.shutil, "rmtree", lambda path: calls.setdefault("removed", path))

    uninstall_module.run_uninstall()

    assert calls.get("server_name") == "reddit-mcp"
    assert calls.get("removed") == cfg_dir


def test_bundled_skill_is_packaged_in_source_tree() -> None:
    skill_path = (
        Path(__file__).resolve().parents[1]
        / "src"
        / "reddit_mcp"
        / "skills"
        / "use-reddit-mcp"
        / "SKILL.md"
    )
    assert skill_path.exists()
