"""Tests for MCP configuration file."""

import json
from pathlib import Path
import pytest


def _find_project_root() -> Path:
    """Find project root by walking up to find .git directory."""
    current = Path(__file__).resolve()
    for parent in current.parents:
        if (parent / ".git").exists():
            return parent
    raise RuntimeError("Could not find project root (.git)")


PROJECT_ROOT = _find_project_root()


class TestMcpConfig:
    """Verify .mcp.json is properly configured for the SPOQ server."""

    def test_mcp_json_exists(self):
        mcp_json = PROJECT_ROOT / ".mcp.json"
        assert mcp_json.exists(), ".mcp.json not found at project root"

    def test_mcp_json_valid(self):
        mcp_json = PROJECT_ROOT / ".mcp.json"
        data = json.loads(mcp_json.read_text())
        assert "mcpServers" in data

    def test_spoq_server_entry(self):
        mcp_json = PROJECT_ROOT / ".mcp.json"
        data = json.loads(mcp_json.read_text())
        servers = data["mcpServers"]
        assert "spoq" in servers, "Missing 'spoq' entry in mcpServers"

    def test_spoq_server_command(self):
        mcp_json = PROJECT_ROOT / ".mcp.json"
        data = json.loads(mcp_json.read_text())
        spoq = data["mcpServers"]["spoq"]
        assert spoq["command"] == "uv"

    def test_spoq_server_args(self):
        mcp_json = PROJECT_ROOT / ".mcp.json"
        data = json.loads(mcp_json.read_text())
        spoq = data["mcpServers"]["spoq"]
        args = spoq["args"]
        assert "--directory" in args
        assert "code/mcp/spoq-server" in args
        assert "run" in args

    def test_spoq_server_directory_exists(self):
        mcp_json = PROJECT_ROOT / ".mcp.json"
        data = json.loads(mcp_json.read_text())
        spoq = data["mcpServers"]["spoq"]
        args = spoq["args"]
        dir_idx = args.index("--directory")
        dir_path = args[dir_idx + 1]
        resolved = PROJECT_ROOT / dir_path
        assert resolved.is_dir(), f"Server directory not found: {resolved}"
