"""MyBurn CLI — launch the dashboard or push stats."""
from __future__ import annotations

import argparse
import threading
import webbrowser

from myburn import __version__


def _cmd_dashboard(args):
    """Launch the local dashboard (default command)."""
    import sys

    if not args.no_browser:
        url = f"http://localhost:{args.port}/dashboard"
        threading.Timer(1.5, lambda: webbrowser.open(url)).start()

    print(f"\n\U0001f525 MyBurn v{__version__} \u2014 http://localhost:{args.port}/dashboard\n")

    import uvicorn
    try:
        uvicorn.run("myburn.server:app", host=args.host, port=args.port, log_level="warning")
    except OSError as e:
        if "address already in use" in str(e).lower() or "10048" in str(e):
            print(f"\n  Port {args.port} is already in use.")
            print(f"  Try: myburn --port {args.port + 1}\n")
            sys.exit(1)
        raise


def _cmd_push(args):
    """Build payload, preview, and save receipt."""
    from myburn.push import run_push
    run_push(dry_run=args.dry_run, month=args.month, yes=args.yes)


def _cmd_login(args):
    """Authenticate via GitHub Device Flow."""
    from myburn.auth import login
    login()


def _cmd_logout(args):
    """Clear stored credentials."""
    from myburn.auth import logout
    logout()


def _cmd_verify(args):
    """Compare local receipts with server data."""
    from myburn.push import run_verify
    run_verify()


def main():
    import sys
    # Ensure Unicode output works on Windows terminals (cp1252/cp850)
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    if hasattr(sys.stderr, "reconfigure"):
        sys.stderr.reconfigure(encoding="utf-8", errors="replace")

    parser = argparse.ArgumentParser(
        prog="myburn",
        description="MyBurn \u2014 Your Claude Code Dashboard",
    )
    parser.add_argument("--version", "-V", action="version", version=f"myburn {__version__}")

    sub = parser.add_subparsers(dest="command")

    # --- push ---
    push_p = sub.add_parser("push", help="Publish your stats (local receipt)")
    push_p.add_argument("--dry-run", action="store_true", help="Show payload only, don't save")
    push_p.add_argument("--month", type=str, default=None, help="Month to push (MM or YYYY-MM)")
    push_p.add_argument("--yes", "-y", action="store_true", help="Skip confirmation")

    # --- login ---
    sub.add_parser("login", help="Authenticate via GitHub")

    # --- logout ---
    sub.add_parser("logout", help="Clear stored credentials")

    # --- verify ---
    sub.add_parser("verify", help="Compare local receipts with server")

    # --- dashboard (default) flags on the main parser ---
    parser.add_argument("--port", "-p", type=int, default=7734, help="Port to serve on (default: 7734)")
    parser.add_argument("--host", default="127.0.0.1", help="Host to bind to (default: 127.0.0.1)")
    parser.add_argument("--no-browser", action="store_true", help="Don't open browser automatically")

    args = parser.parse_args()

    if args.command == "push":
        _cmd_push(args)
    elif args.command == "login":
        _cmd_login(args)
    elif args.command == "logout":
        _cmd_logout(args)
    elif args.command == "verify":
        _cmd_verify(args)
    else:
        _cmd_dashboard(args)
