"""hdx dev — start a dev server with hot reload and interactive REPL."""

from __future__ import annotations

import asyncio

import click

from hatchdx.utils import console
from hatchdx.utils.config import ConfigError, load_config


@click.command("dev")
@click.option(
    "--no-repl",
    is_flag=True,
    help="Watch and restart only — no interactive REPL",
)
@click.option(
    "--port",
    type=int,
    default=None,
    help="Port for HTTP transport (not yet supported)",
)
def dev_cmd(no_repl, port):
    """Start your MCP server with hot reload and an interactive REPL."""
    # 1. Load project config
    try:
        config = load_config()
    except ConfigError as exc:
        console.error(str(exc))
        raise SystemExit(1)

    if port is not None:
        console.warning("HTTP transport is not yet supported. Ignoring --port flag.")

    # 2. Print startup banner
    console.info(f"Starting dev server for {config.server_name}")
    console.step(f"Command: {config.server_command}")
    if no_repl:
        console.step("REPL disabled — watching for file changes only")
    else:
        console.step("REPL enabled — type 'help' for commands, 'quit' to exit")
    click.echo()

    # 3. Start the dev server engine
    from hatchdx.devserver.engine import DevServerEngine

    engine = DevServerEngine(
        command=config.server_command,
        repl=not no_repl,
        server_name=config.server_name,
    )

    try:
        asyncio.run(engine.run())
    except KeyboardInterrupt:
        pass

    click.echo()
    console.success("Dev server stopped")
