"""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.",
    )
    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")

    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__)

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


if __name__ == "__main__":
    main()
