"""OpOp CLI -- monitor training runs with the optimizer optimizer."""

import argparse
import sys


def main():
    parser = argparse.ArgumentParser(
        prog="opop",
        description="OpOp -- The Optimizer Optimizer. Monitor, control, compare, contribute.",
    )
    sub = parser.add_subparsers(dest="command")

    # ── monitor ──
    mon = sub.add_parser("monitor", aliases=["mon", "m"],
                         help="Launch the TUI dashboard")
    mon.add_argument("--log", "-l", action="append", default=[],
                     help="Log file to tail (repeatable for multi-run)")
    mon.add_argument("--control", "-c", type=str, default=None,
                     help="Control JSON file for live editing")
    mon.add_argument("--control-dir", type=str, default=None,
                     help="Directory of control JSONs (auto-discovers)")
    mon.add_argument("--gpu-poll", type=int, default=5,
                     help="GPU poll interval in seconds (0=disable)")
    mon.add_argument("--tail-interval", type=float, default=0.5,
                     help="Log tail poll interval in seconds")

    # ── version ──
    sub.add_parser("version", aliases=["v"], help="Print version")

    # ── brain ──
    sub.add_parser("brain", help="Show brain state explanation")

    # ── telemetry ──
    tel = sub.add_parser("telemetry", aliases=["tel"],
                         help="View telemetry collection status")
    tel.add_argument("action", nargs="?", default="status",
                     choices=["status", "clear", "disable", "enable"],
                     help="status (default), clear, disable, enable")

    # ── contribute ──
    contrib = sub.add_parser("contribute",
                             help="Package and share collected brain data")
    contrib.add_argument("--output", "-o", type=str, default=None,
                         help="Output path for the contribution package")
    contrib.add_argument("--upload", action="store_true",
                         help="Upload to the collection server")
    contrib.add_argument("--endpoint", type=str, default=None,
                         help="Upload endpoint URL")

    args = parser.parse_args()

    if args.command in ("version", "v"):
        from opop import __version__
        print(f"opop {__version__}")

    elif args.command in ("monitor", "mon", "m"):
        try:
            from opop.tui import OpOpApp
        except ImportError:
            print("TUI requires textual and rich:")
            print("  pip install opop[tui]")
            sys.exit(1)

        # Auto-discover logs in control dir
        if args.control_dir and not args.log:
            import os, glob
            logs = sorted(glob.glob(os.path.join(args.control_dir, "*.log")))
            args.log.extend(logs)

        # Auto-discover control files
        if args.control_dir and not args.control:
            import os, glob
            jsons = sorted(glob.glob(os.path.join(args.control_dir, "*.json")))
            if jsons:
                args.control = jsons[0]

        app = OpOpApp(
            log_paths=args.log,
            control_path=args.control,
            control_dir=args.control_dir,
            gpu_poll_interval=args.gpu_poll,
            tail_interval=args.tail_interval,
        )
        app.run()

    elif args.command == "brain":
        from opop.brain import OptBrain
        print(OptBrain.__doc__)

    elif args.command in ("telemetry", "tel"):
        _handle_telemetry(args)

    elif args.command == "contribute":
        _handle_contribute(args)

    else:
        parser.print_help()
        sys.exit(0)


def _handle_telemetry(args):
    """Handle telemetry subcommand."""
    from opop.telemetry import (get_collection_stats, clear_telemetry,
                                 OPOP_DIR, NOTICE_FLAG, _is_enabled)

    if args.action == "status":
        stats = get_collection_stats()
        enabled = "ON" if stats['enabled'] else "OFF"
        print(f"  Telemetry:        {enabled}")
        print(f"  Data directory:   {stats['telemetry_dir']}")
        print(f"  Brain checkpoints: {stats['brains']}")
        print(f"  Experience files:  {stats['experience_files']}")
        print(f"  Run summaries:     {stats['run_summaries']}")
        print(f"  Total size:        {stats['total_size_mb']} MB")
        if not stats['enabled']:
            print("\n  Enable: opop telemetry enable")
            print("          or: unset OPOP_TELEMETRY")

    elif args.action == "clear":
        count = clear_telemetry()
        print(f"  Cleared {count} telemetry files.")

    elif args.action == "disable":
        print("  To disable telemetry:")
        print("    export OPOP_TELEMETRY=0")
        print("  Or pass telemetry=False to OptBrain/TwinCrack")
        print("  To persist: add OPOP_TELEMETRY=0 to your shell profile")

    elif args.action == "enable":
        print("  Telemetry is ON by default.")
        print("  If you disabled it: unset OPOP_TELEMETRY")
        # Remove notice flag so disclaimer shows again
        if NOTICE_FLAG.exists():
            NOTICE_FLAG.unlink()
            print("  Notice flag reset — disclaimer will show on next run.")


def _handle_contribute(args):
    """Handle contribute subcommand."""
    from opop.telemetry import (get_collection_stats, package_contribution,
                                 upload_contribution)

    stats = get_collection_stats()
    total = stats['brains'] + stats['experience_files']

    if total == 0:
        print("  Nothing to contribute yet.")
        print("  Train with OpOp first — telemetry collects automatically.")
        return

    print(f"  Packaging {stats['brains']} brain(s) + "
          f"{stats['experience_files']} experience file(s)...")

    path = package_contribution(output_path=args.output)
    if path is None:
        print("  Failed to create package.")
        return

    import os
    size_mb = round(os.path.getsize(path) / (1024 * 1024), 2)
    print(f"  Package saved: {path} ({size_mb} MB)")

    if args.upload:
        print("  Uploading...")
        ok = upload_contribution(path, endpoint=args.endpoint)
        if ok:
            print("  Upload successful! Thanks for making OpOp smarter.")
        else:
            print("  Upload failed. You can share the .npz file manually.")
    else:
        print("\n  To upload: opop contribute --upload")
        print("  Or share the .npz file directly.")
        print(f"\n  Every brain you share makes OpOp smarter for everyone.")


if __name__ == "__main__":
    main()
