"""MCP server CLI commands for Komodo."""

import json
from pathlib import Path

import pyperclip
import typer
from rich.console import Console
from rich.panel import Panel
from rich.text import Text

console = Console()

mcp_app = typer.Typer(
    name="mcp",
    help="Manage the Komodo MCP server for AI assistants",
    add_completion=False,
    no_args_is_help=True,
)


def _get_connector_root() -> str:
    """Get the root directory of the connector package (where pyproject.toml is)."""
    current_file = Path(__file__).resolve()
    return str(current_file.parent.parent.parent)


def _get_mcp_server_config(name: str) -> dict:
    """Generate standard MCP server configuration."""
    return {
        name: {
            "command": "uv",
            "args": ["run", "komodo", "mcp", "run"],
            "cwd": _get_connector_root(),
        }
    }


@mcp_app.command()
def run():
    """Run the Komodo MCP server (STDIO transport).

    This starts the MCP server which AI assistants like Cursor, VS Code,
    and Claude Desktop can connect to for exploring Snowflake schemas.

    Prerequisites:
      1. Run 'uv run komodo login' to authenticate
      2. Run 'uv run komodo account set' to select your account
    """
    from kom_mcp import run_server

    run_server()


@mcp_app.command(name="show-config")
def show_config(
    name: str = typer.Option("komodo", "--name", "-n", help="Name for the server in the config"),
):
    """Show the MCP server configuration JSON and copy to clipboard.

    Use this to manually add the Komodo MCP server to any MCP-compatible application.
    """
    server_config = _get_mcp_server_config(name)
    full_config = {"mcpServers": server_config}
    config_json = json.dumps(full_config, indent=2)

    console.print(Panel(config_json, title="MCP Configuration", subtitle="Add this to your MCP client's config file", border_style="blue"))

    console.print()
    console.print(
        Panel(
            "[bold]Configuration Fields:[/bold]\n\n"
            f"[dim]cwd[/dim] - Working directory for uv to find pyproject.toml\n"
            f"       Currently set to: {_get_connector_root()}",
            title="Notes",
            border_style="dim",
        )
    )

    try:
        pyperclip.copy(config_json)
        console.print(Text("Configuration copied to clipboard", style="bold green"))
    except Exception:
        console.print(Text("Could not copy to clipboard. Please copy manually.", style="bold red"))


@mcp_app.callback()
def mcp_callback():
    """Komodo MCP Server - Connect AI assistants to Snowflake data.

    The MCP (Model Context Protocol) server allows AI assistants like Cursor,
    VS Code Copilot, Claude Desktop, and Amp to explore your Snowflake schemas
    and understand Komodo Health's healthcare data.

    Prerequisites:
      1. Run 'uv run komodo login' to authenticate
      2. Run 'uv run komodo account set' to select your account

    Quick Start:
      uv run komodo mcp show-config    # Show config JSON to add manually
      uv run komodo mcp run            # Run server (called by MCP clients)
    """
