import importlib
import json
from pathlib import Path

import pytest


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


def test_mcp_finds_existing_config(tmp_path: Path):
    mcp_path = tmp_path / ".mcp.json"
    mcp_path.write_text(json.dumps({"mcpServers": {}}), encoding="utf-8")
    assert mcp_cmd.find_mcp_config(tmp_path) == mcp_path


def test_mcp_no_config(tmp_path: Path):
    assert mcp_cmd.find_mcp_config(tmp_path) is None


def test_mcp_install_creates_correct_format(tmp_path: Path):
    result = mcp_cmd.install_gjalla_entry(tmp_path, project_id=116, api_key="gja_test123")
    mcp_path = tmp_path / ".mcp.json"
    assert mcp_path.exists()
    data = json.loads(mcp_path.read_text(encoding="utf-8"))

    assert "mcpServers" in data
    assert "gjalla" in data["mcpServers"]

    entry = data["mcpServers"]["gjalla"]
    assert entry["command"] == "npx"
    assert entry["args"] == ["-y", "@gjalla/mcp-server"]
    assert entry["env"]["GJALLA_API_KEY"] == "gja_test123"
    assert entry["env"]["GJALLA_PROJECT_ID"] == "116"
    assert result is True


def test_mcp_install_no_project_id(tmp_path: Path):
    mcp_cmd.install_gjalla_entry(tmp_path)
    data = json.loads((tmp_path / ".mcp.json").read_text(encoding="utf-8"))
    entry = data["mcpServers"]["gjalla"]
    assert "GJALLA_PROJECT_ID" not in entry["env"]


def test_mcp_install_custom_api_url(tmp_path: Path):
    mcp_cmd.install_gjalla_entry(tmp_path, project_id=46, api_url="https://dev.gjalla.io")
    data = json.loads((tmp_path / ".mcp.json").read_text(encoding="utf-8"))
    entry = data["mcpServers"]["gjalla"]
    assert entry["env"]["GJALLA_BASE_URL"] == "https://dev.gjalla.io"


def test_mcp_install_default_url_not_included(tmp_path: Path):
    mcp_cmd.install_gjalla_entry(tmp_path, project_id=46, api_url="https://gjalla.io")
    data = json.loads((tmp_path / ".mcp.json").read_text(encoding="utf-8"))
    entry = data["mcpServers"]["gjalla"]
    assert "GJALLA_BASE_URL" not in entry["env"]


def test_mcp_preserves_existing_servers(tmp_path: Path):
    mcp_path = tmp_path / ".mcp.json"
    existing = {"mcpServers": {"other-server": {"command": "node", "args": ["server.js"]}}}
    mcp_path.write_text(json.dumps(existing), encoding="utf-8")

    mcp_cmd.install_gjalla_entry(tmp_path, project_id=116)
    data = json.loads(mcp_path.read_text(encoding="utf-8"))

    assert "other-server" in data["mcpServers"]
    assert "gjalla" in data["mcpServers"]


def test_mcp_already_installed(tmp_path: Path):
    mcp_path = tmp_path / ".mcp.json"
    existing = {"mcpServers": {"gjalla": {"command": "npx", "args": ["-y", "@gjalla/mcp-server"]}}}
    mcp_path.write_text(json.dumps(existing), encoding="utf-8")
    assert mcp_cmd.install_gjalla_entry(tmp_path, project_id=116) is False
