from __future__ import annotations

import argparse
import sys
import webbrowser

from danom import Err, safe


@safe
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        prog="blackbox",
        description="Flight data recorder for AI coding agent sessions",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    serve_parser = subparsers.add_parser("serve", help="Launch the session dashboard")
    serve_parser.add_argument("--port", type=int, default=7100)
    serve_parser.add_argument("--no-open", action="store_true", help="Don't open browser automatically")

    return parser.parse_args(argv)


@safe
def run(args: argparse.Namespace) -> None:
    if args.command == "serve":
        run_serve(args)
    else:
        msg = f"Unknown command: {args.command}"
        raise ValueError(msg)


def run_serve(args: argparse.Namespace) -> None:
    import uvicorn  # noqa: PLC0415

    from blackbox.dashboard.app import app  # noqa: PLC0415

    if not args.no_open:
        import threading  # noqa: PLC0415

        def open_browser() -> None:
            import time  # noqa: PLC0415

            time.sleep(1.0)
            webbrowser.open(f"http://localhost:{args.port}")

        threading.Thread(target=open_browser, daemon=True).start()

    uvicorn.run(app, host="127.0.0.1", port=args.port, log_level="warning")


def main() -> None:
    args = parse_args().unwrap()
    result = run(args)
    if isinstance(result, Err):
        print(f"Error: {result.error}", file=sys.stderr)  # noqa: T201
        sys.exit(1)
