"""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, info
from ._shared import get_repo_root, load_local_config


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


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

    # Read project config to get project_id and api_url
    gjalla_config = load_local_config(repo_root)
    project_id = gjalla_config.get("project_id")
    api_url = gjalla_config.get("api_url", "https://gjalla.io")

    installed = install_gjalla_entry(repo_root, project_id=project_id, api_url=api_url)
    if installed:
        success("gjalla MCP server installed in .mcp.json")
    else:
        warning("gjalla MCP server already configured in .mcp.json")


def find_mcp_config(repo_root: Path | None = None) -> Path | None:
    """Find the .mcp.json config file in the project root.

    Returns:
        Path to .mcp.json if found, None otherwise.
    """
    if repo_root is None:
        repo_root = Path.cwd()

    mcp_path = repo_root / ".mcp.json"
    if mcp_path.exists():
        return mcp_path

    return None


def install_gjalla_entry(
    repo_root: Path,
    project_id: int | str | None = None,
    api_url: str = "https://gjalla.io",
    api_key: str | None = None,
) -> bool:
    """Install the Gjalla MCP server entry in .mcp.json.

    Writes to {repo_root}/.mcp.json using the Claude Code project-scope format:
    {"mcpServers": {"gjalla": {"command": "npx", "args": [...], "env": {...}}}}

    Args:
        repo_root: Path to the repository root.
        project_id: Gjalla project ID to configure.
        api_url: Gjalla API base URL.
        api_key: Gjalla API key. If not provided, falls back to GJALLA_API_KEY
                 env var or global config.

    Returns:
        True if installed, False if already present.
    """
    mcp_path = repo_root / ".mcp.json"

    # Read existing config if present
    config: dict = {}
    if mcp_path.exists():
        try:
            config = json.loads(mcp_path.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            config = {}

    mcp_servers = config.get("mcpServers", {})

    # Check if gjalla is already installed
    if "gjalla" in mcp_servers:
        return False

    # Resolve API key: explicit arg > env var > global config
    resolved_key = api_key or os.environ.get("GJALLA_API_KEY")
    if not resolved_key:
        try:
            from .init import load_global_config
            global_config = load_global_config()
            resolved_key = global_config.get("api_key")
        except Exception:
            pass

    # Build env vars
    env: dict[str, str] = {}
    if resolved_key:
        env["GJALLA_API_KEY"] = resolved_key
    if project_id is not None:
        env["GJALLA_PROJECT_ID"] = str(project_id)
    if api_url and api_url != "https://gjalla.io":
        env["GJALLA_BASE_URL"] = api_url

    # Add gjalla server entry
    mcp_servers["gjalla"] = {
        "command": "npx",
        "args": ["-y", "@gjalla/mcp-server"],
        "env": env,
    }
    config["mcpServers"] = mcp_servers

    # Write config
    mcp_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")

    return True
