"""MCP integration CLI commands."""

from __future__ import annotations

import importlib
import json
import sys
from pathlib import Path

import click

from .utils import _ensure_verbose, console, verbose_option


def _resolve_module_class(entry: str):
    """Dynamically import the module class from an entrypoint string."""
    if ":" not in entry:
        console.print(f"[red]Invalid entrypoint '{entry}'. Expected 'module.path:ClassName'.[/red]")
        sys.exit(1)

    module_path, class_name = entry.split(":", 1)

    # Ensure the current directory is importable
    cwd = str(Path.cwd())
    if cwd not in sys.path:
        sys.path.insert(0, cwd)

    try:
        mod = importlib.import_module(module_path)
    except ImportError as exc:
        console.print(f"[red]Cannot import module '{module_path}': {exc}[/red]")
        sys.exit(1)

    clazz = getattr(mod, class_name, None)
    if clazz is None:
        console.print(f"[red]Class '{class_name}' not found in '{module_path}'[/red]")
        sys.exit(1)

    return clazz


def _load_manifest_or_exit(manifest_path: Path) -> dict:
    if not manifest_path.exists():
        console.print("[red]manifest.json not found in current directory[/red]")
        sys.exit(1)

    try:
        return json.loads(manifest_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        console.print(f"[red]manifest.json is not valid JSON: {exc}[/red]")
        sys.exit(1)


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


@mcp.command()
@verbose_option
@click.option(
    "--transport",
    type=click.Choice(["stdio"]),
    default="stdio",
    show_default=True,
    help="MCP transport type",
)
@click.pass_context
def serve(ctx, transport):
    """Start a local MCP server for the module in this directory."""
    _ensure_verbose(ctx)

    manifest_path = Path("manifest.json")
    manifest = _load_manifest_or_exit(manifest_path)
    entry = manifest.get("execution", {}).get("entrypoint", "backend.main:Module")

    module_class = _resolve_module_class(entry)

    try:
        from ..mcp import MCPModuleServer
    except ImportError:
        console.print("[red]MCP support requires the 'mcp' package.[/red]")
        console.print("Install with: pip install 'hla-compass[mcp]'")
        sys.exit(1)

    console.print(f"[cyan]Starting MCP server for '{manifest.get('name', '?')}' ({transport})...[/cyan]")
    server = MCPModuleServer(module_class, manifest_path=str(manifest_path))
    server.run(transport=transport)


@mcp.command()
@verbose_option
@click.pass_context
def schema(ctx):
    """Print the MCP tool definition for this module."""
    _ensure_verbose(ctx)

    manifest_path = Path("manifest.json")
    manifest = _load_manifest_or_exit(manifest_path)

    from ..mcp import module_to_mcp_tool

    tool_def = module_to_mcp_tool(manifest)
    click.echo(json.dumps(tool_def, indent=2))
