from __future__ import annotations

import pytest

import oh_my_linear.server as server


class _FakeRouter:
    def __init__(self) -> None:
        self.read_calls: list[tuple[str, dict[str, object]]] = []
        self.official_calls: list[tuple[str, dict[str, object]]] = []

    def call_read(self, name: str, args: dict[str, object]) -> dict[str, object]:
        self.read_calls.append((name, args))
        return {"path": "read", "name": name, "args": args}

    def call_official(self, name: str, args: dict[str, object]) -> dict[str, object]:
        self.official_calls.append((name, args))
        return {"path": "official", "name": name, "args": args}


def test_server_exports_main_and_mcp() -> None:
    assert callable(server.main)
    assert server.mcp is not None


def test_module_does_not_export_removed_ops_tools() -> None:
    assert not hasattr(server, "list_official_tools")
    assert not hasattr(server, "reconnect_official")
    assert not hasattr(server, "refresh_cache")
    assert not hasattr(server, "get_cache_health")
    assert not hasattr(server, "reauth")


def test_tool_surface_excludes_removed_ops_tools() -> None:
    tool_names = set(server.mcp._tool_manager._tools.keys())

    assert "official_call_tool" in tool_names
    assert "list_official_tools" not in tool_names
    assert "reconnect_official" not in tool_names
    assert "refresh_cache" not in tool_names
    assert "get_cache_health" not in tool_names
    assert "reauth" not in tool_names
    assert "create_issue" not in tool_names
    assert "update_issue" not in tool_names


def test_read_helper_raises_runtime_error_when_router_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(server, "_router", None)
    with pytest.raises(RuntimeError, match="server not initialized"):
        server._read("list_users")


def test_official_call_tool_raises_runtime_error_when_router_missing(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(server, "_router", None)
    with pytest.raises(RuntimeError, match="server not initialized"):
        server.official_call_tool("create_issue", {})


def test_read_helper_forwards_to_router(monkeypatch: pytest.MonkeyPatch) -> None:
    fake_router = _FakeRouter()
    monkeypatch.setattr(server, "_router", fake_router)

    result = server._read("list_users", limit=5)

    assert result["path"] == "read"
    assert fake_router.read_calls == [("list_users", {"limit": 5})]


def test_official_call_tool_forwards_to_router(monkeypatch: pytest.MonkeyPatch) -> None:
    fake_router = _FakeRouter()
    monkeypatch.setattr(server, "_router", fake_router)

    result = server.official_call_tool("create_issue", {"title": "Test"})

    assert result["path"] == "official"
    assert fake_router.official_calls == [("create_issue", {"title": "Test"})]
