"""Dashboard command - launch a local web dashboard."""

from __future__ import annotations

import webbrowser

import typer

from manta_client.config import get_config
from manta_client.output import console, print_error

app = typer.Typer(help="Web dashboard")


@app.callback(invoke_without_command=True)
def dashboard(
    port: int = typer.Option(8050, "--port", "-p", help="Local server port"),
    no_open: bool = typer.Option(False, "--no-open", help="Don't auto-open browser"),
) -> None:
    """Launch a local web dashboard in the browser."""
    config = get_config()

    if not config.access_token:
        print_error("Not authenticated. Run 'manta-client auth login' first.")
        raise typer.Exit(1)

    from manta_client.dashboard.server import run_server

    try:
        server, actual_port = run_server(
            api_url=config.api_url,
            auth_token=config.access_token,
            port=port,
        )
    except RuntimeError as e:
        print_error(str(e))
        raise typer.Exit(1) from None

    url = f"http://127.0.0.1:{actual_port}"
    console.print(f"[green]Dashboard running at [bold]{url}[/bold][/green]")
    console.print("[dim]Press Ctrl+C to stop[/dim]")

    if not no_open:
        webbrowser.open(url)

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        console.print("\n[dim]Shutting down dashboard...[/dim]")
        server.shutdown()
