"""koan mcp — MCP server development tools."""

from __future__ import annotations

import subprocess
import sys

import typer
from rich.console import Console

console = Console()

mcp_app = typer.Typer(help="MCP server development tools.", no_args_is_help=True)


@mcp_app.command("dev")
def mcp_dev_command(
    server: str = typer.Argument(help="Path to MCP server Python file"),
    port: int = typer.Option(8080, "--port", "-p", help="Port to run the dev server on"),
) -> None:
    """Run an MCP server in development mode with auto-reload."""
    console.print(f"[bold cyan]Starting MCP dev server:[/bold cyan] {server} on port {port}")
    console.print("[dim]Press Ctrl+C to stop.[/dim]\n")

    try:
        subprocess.run(  # noqa: S603
            [sys.executable, server],
            env={**__import__("os").environ, "MCP_DEV_PORT": str(port)},
            check=True,
        )
    except FileNotFoundError:
        console.print(f"[red]Error:[/red] File not found: {server}")
        raise typer.Exit(code=1) from None
    except KeyboardInterrupt:
        console.print("\n[yellow]Server stopped.[/yellow]")
    except subprocess.CalledProcessError as exc:
        console.print(f"[red]Server exited with code {exc.returncode}[/red]")
        raise typer.Exit(code=exc.returncode) from None
