"""MCP (Model Context Protocol) integration for gjalla-precommit."""

from __future__ import annotations

import json
import os
from pathlib import Path

import click

from ..display.output import console, success, error, warning


@click.group()
def mcp() -> None:
    """MCP (Model Context Protocol) commands."""
    pass


@mcp.command()
def install() -> None:
    """Install Gjalla MCP server entry in Claude config."""
    mcp_path = find_mcp_config()

    if mcp_path is None:
        # Create the config directory and file
        home = Path(os.environ.get("HOME", Path.home()))
        mcp_path = home / ".claude" / "mcp.json"
        mcp_path.parent.mkdir(parents=True, exist_ok=True)
        mcp_path.write_text('{"servers": []}', encoding="utf-8")
        console.print(f"Created MCP config at {mcp_path}")

    installed = install_gjalla_entry(mcp_path)
    if installed:
        success("Gjalla MCP server installed successfully")
    else:
        warning("Gjalla MCP server already installed")


def find_mcp_config() -> Path | None:
    """Find the MCP configuration file for Claude Code.

    Looks for the mcp.json file in the user's home directory
    at ~/.claude/mcp.json.

    Returns:
        Path to mcp.json if found, None otherwise.
    """
    home = Path(os.environ.get("HOME", Path.home()))
    mcp_path = home / ".claude" / "mcp.json"

    if mcp_path.exists():
        return mcp_path

    return None


def install_gjalla_entry(mcp_path: Path) -> bool:
    """Install the Gjalla MCP server entry.

    Adds the gjalla server configuration to the MCP config file,
    preserving any existing servers.

    Args:
        mcp_path: Path to the mcp.json file.

    Returns:
        True if installed, False if already present.
    """
    # Read existing config
    with open(mcp_path, encoding="utf-8") as f:
        config = json.load(f)

    servers = config.get("servers", [])

    # Check if gjalla is already installed
    for server in servers:
        if server.get("name") == "gjalla":
            return False

    # Add gjalla server
    gjalla_server = {
        "name": "gjalla",
        "command": "gjalla-mcp",
        "args": [],
    }
    servers.append(gjalla_server)
    config["servers"] = servers

    # Write updated config
    with open(mcp_path, "w", encoding="utf-8") as f:
        json.dump(config, f, indent=2)

    return True
