"""CLI entry point for agentradar."""
from __future__ import annotations

import sys
from pathlib import Path

import click


@click.group()
@click.version_option(version="1.0.0", prog_name="agentradar")
def main():
    """agentradar — local-first visual debugger for multi-agent AI systems."""
    pass


@main.command("view")
@click.argument("snapshot_path", type=click.Path(exists=True))
@click.option("--port", default=None, type=int, help="Port to serve on (default: from config or 7111)")
@click.option("--no-browser", is_flag=True, default=False, help="Don't open browser automatically")
def view_snapshot(snapshot_path: str, port: int | None, no_browser: bool):
    """View a .agtrace snapshot file."""
    from agentradar.storage import snapshots as snap
    from agentradar.storage import config as cfg
    from agentradar.server import app as server_app

    click.echo(f"Loading snapshot: {snapshot_path}")

    try:
        data = snap.load_snapshot(snapshot_path)
        run_state = data.get("run", {})
    except Exception as e:
        click.echo(f"Error loading snapshot: {e}", err=True)
        sys.exit(1)

    # Inject snapshot into server state
    server_app._run_state.update(run_state)
    server_app._run_state["status"] = "complete"
    server_app._run_state["is_snapshot"] = True
    server_app._run_state["snapshot_path"] = str(snapshot_path)

    config = cfg.load_config()
    serve_port = port or config.get("port", 7111)
    open_browser = not no_browser

    click.echo(f"Serving at http://localhost:{serve_port}")
    _start_server(serve_port, open_browser)


@main.command("failures")
@click.option("--clear", is_flag=True, default=False, help="Clear all failure history")
def show_failures(clear: bool):
    """List or clear failure history."""
    from agentradar.storage import failures as fail

    if clear:
        count = fail.clear_failures()
        click.echo(f"Cleared {count} failure(s).")
        return

    failures = fail.list_failures()
    if not failures:
        click.echo("No failure history found.")
        return

    click.echo(f"\nFailure History ({len(failures)} run(s)):\n")
    for i, f in enumerate(failures, 1):
        pinned = " [PINNED]" if f.get("pinned") else ""
        failed = ", ".join(f.get("failed_agents", [])) or "unknown"
        click.echo(f"  {i}. {f['run_id']}{pinned}")
        click.echo(f"     Failed agent(s): {failed}")
        click.echo(f"     Time: {f.get('created_at', 'unknown')}")
        click.echo(f"     ID: {f['id']}")
        click.echo()


@main.command("serve")
@click.option("--port", default=None, type=int, help="Port to serve on")
@click.option("--no-browser", is_flag=True, default=False)
def serve(port: int | None, no_browser: bool):
    """Start the agentradar dashboard server (idle mode)."""
    from agentradar.storage import config as cfg
    config = cfg.load_config()
    serve_port = port or config.get("port", 7111)
    click.echo(f"agentradar dashboard at http://localhost:{serve_port}")
    _start_server(serve_port, not no_browser)


def _start_server(port: int, open_browser: bool):
    import uvicorn
    import threading
    import time

    if open_browser:
        def _open():
            time.sleep(1.2)
            import webbrowser
            webbrowser.open(f"http://localhost:{port}")
        threading.Thread(target=_open, daemon=True).start()

    from agentradar.server.app import app
    uvicorn.run(app, host="0.0.0.0", port=port, log_level="warning")


if __name__ == "__main__":
    main()
