import importlib
import json
from pathlib import Path

import pytest


mcp_cmd = importlib.import_module("gjalla_precommit.commands.mcp")


def test_mcp_detects_claude_code(home_dir: Path):
    mcp_path = home_dir / ".claude" / "mcp.json"
    mcp_path.parent.mkdir(parents=True, exist_ok=True)
    mcp_path.write_text(json.dumps({"servers": []}), encoding="utf-8")
    assert mcp_cmd.find_mcp_config() == mcp_path


def test_mcp_no_claude_code(home_dir: Path):
    assert mcp_cmd.find_mcp_config() is None


def test_mcp_preserves_existing(home_dir: Path):
    mcp_path = home_dir / ".claude" / "mcp.json"
    mcp_path.parent.mkdir(parents=True, exist_ok=True)
    mcp_path.write_text(json.dumps({"servers": [{"name": "existing"}]}), encoding="utf-8")
    mcp_cmd.install_gjalla_entry(mcp_path)
    data = json.loads(mcp_path.read_text(encoding="utf-8"))
    assert any(server["name"] == "existing" for server in data["servers"])


def test_mcp_already_installed(home_dir: Path):
    mcp_path = home_dir / ".claude" / "mcp.json"
    mcp_path.parent.mkdir(parents=True, exist_ok=True)
    mcp_path.write_text(json.dumps({"servers": [{"name": "gjalla"}]}), encoding="utf-8")
    assert mcp_cmd.install_gjalla_entry(mcp_path) is False
