"""
Module: dev_command
Description: Development session with local sandbox server and cloud execution

Implements:
    - docs/cli/reference.md#huitzo-pack-dev
    - docs/cli/reference.md#interactive-repl
    - docs/guides/developer-environment.md#development-session-flow
"""

import asyncio
import subprocess
import sys
import time

import typer
from rich.console import Console

from huitzo_cli.auth import AuthClient
from huitzo_cli.config import ConfigManager
from huitzo_cli.validator import PackValidator

console = Console()


def dev(
    docs: bool = typer.Option(False, "--docs", help="Start docs server"),
    port: int = typer.Option(8080, "--port", help="Sandbox port"),
    repl: bool = typer.Option(
        True, "--repl/--no-repl", help="Start interactive REPL for command testing"
    ),
) -> None:
    """Start pack development session with local sandbox.

    1. Validates pack structure
    2. Installs pack in editable mode
    3. Discovers commands from entry_points
    4. Starts HTTPS sandbox at localhost:{port}
    5. Optionally starts docs server at localhost:8124
    6. Starts interactive REPL (default) or blocks until Ctrl+C

    Args:
        docs: Start local docs server
        port: Local sandbox port
        repl: Start interactive REPL (default True)
    """
    # Require authentication
    config = ConfigManager()
    auth = AuthClient(config)
    token = auth.get_token()
    if not token:
        console.print("[red]Not authenticated. Run: huitzo login[/red]")
        raise typer.Exit(1)

    # Validate pack
    console.print("[bold]Validating pack...[/bold]")
    validator = PackValidator()
    result = validator.validate()

    if not result.valid:
        console.print("[red]Pack validation failed[/red]")
        for error in result.errors:
            console.print(f"  {error}")
        raise typer.Exit(1)

    console.print("[green]Pack validation passed[/green]")

    # Editable install
    console.print("[bold]Installing pack in editable mode...[/bold]")
    install_result = subprocess.run(
        [sys.executable, "-m", "pip", "install", "-e", "."],
        capture_output=True,
        text=True,
        check=False,
    )
    if install_result.returncode != 0:
        console.print(f"[red]Editable install failed: {install_result.stderr}[/red]")
        raise typer.Exit(1)

    console.print("[green]Pack installed[/green]")

    # Start sandbox
    from huitzo_cli.sandbox.proxy import LocalSandbox

    sandbox = LocalSandbox(auth_token=token)
    commands = sandbox.discover_commands()

    # Surface discovery failures
    failures = sandbox.get_discovery_failures()
    if failures:
        console.print(f"[yellow]Warning: {len(failures)} command(s) failed to load:[/yellow]")
        for failure in failures:
            console.print(f"  [yellow]{failure}[/yellow]")

    if not commands:
        console.print(
            "[yellow]No commands found. Check your entry_points in pyproject.toml.[/yellow]"
        )
    else:
        console.print(f"[bold]Discovered {len(commands)} command(s):[/bold]")
        for name, meta in commands.items():
            console.print(f"  {meta.get('namespace', name)} - {meta.get('description', '')[:60]}")

    base_url = sandbox.start(port=port)
    console.print(f"\n[green]Sandbox ready at {base_url}[/green]")
    if base_url.startswith("https"):
        console.print("[dim]Note: Uses a self-signed certificate (browser warnings expected)[/dim]")
    console.print("  GET  /commands      - List available commands")
    console.print("  POST /commands/NAME - Execute a command")
    console.print("  GET  /health        - Health check")
    console.print("[dim]Endpoints require Authorization: Bearer <token>[/dim]")

    # Start docs server if requested
    docs_server = None
    if docs:
        try:
            from huitzo_cli.docs_server.server import DocsServer

            docs_server = DocsServer(port=8124)
            docs_server.start()
            console.print("\n[green]Docs server at http://localhost:8124[/green]")
        except (OSError, ImportError) as e:
            console.print(f"[yellow]Could not start docs server: {e}[/yellow]")

    # Use try/finally to guarantee cleanup on any exit path
    try:
        if repl:
            from huitzo_cli.repl.session import REPLSession

            session = REPLSession(base_url, auth_token=token, console=console)
            try:
                asyncio.run(session.run())
            except (KeyboardInterrupt, EOFError):
                console.print("\nGoodbye!")
        else:
            console.print("\nPress Ctrl+C to stop...")
            while True:
                time.sleep(1)
    except (KeyboardInterrupt, SystemExit):
        pass
    finally:
        console.print("\n[yellow]Shutting down...[/yellow]")
        sandbox.stop()
        if docs_server:
            docs_server.stop()
