"""
VexRay CLI — command-line interface for starting topics and playgrounds.

Usage:
    vexray start "linear regression"
    vexray playground svm
    vexray list
    vexray list --playgrounds
"""

import argparse
import sys


def main():
    parser = argparse.ArgumentParser(
        prog="vexray",
        description="⚡ VexRay — Interactive ML/DL Concept Explorer",
    )
    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # ── vexray start ──
    start_parser = subparsers.add_parser("start", help="Open a topic page in the browser")
    start_parser.add_argument("topic", nargs="+", help="Topic name (e.g. 'linear regression')")
    start_parser.add_argument("-p", "--port", type=int, default=5556, help="Port (default: 5556)")

    # ── vexray playground ──
    pg_parser = subparsers.add_parser("playground", help="Open an interactive playground")
    pg_parser.add_argument("algorithm", nargs="+", help="Algorithm name (e.g. 'svm')")
    pg_parser.add_argument("-p", "--port", type=int, default=5556, help="Port (default: 5556)")

    # ── vexray list ──
    list_parser = subparsers.add_parser("list", help="List available topics or playgrounds")
    list_parser.add_argument("--playgrounds", action="store_true", help="List playgrounds instead of topics")

    args = parser.parse_args()

    if args.command == "start":
        from .server import start
        topic = " ".join(args.topic)
        start(topic, port=args.port)

    elif args.command == "playground":
        from .server import start_playground
        algorithm = " ".join(args.algorithm)
        start_playground(algorithm, port=args.port)

    elif args.command == "list":
        if args.playgrounds:
            from .playgrounds import list_playgrounds
            playgrounds = list_playgrounds()
            print(f"\n  ⚡ VexRay Playgrounds ({len(playgrounds)})\n")
            for pg in playgrounds:
                print(f"     • {pg}")
            print(f"\n  Usage: vexray playground \"<name>\"\n")
        else:
            from .registry import list_topics
            topics = list_topics()
            print(f"\n  ⚡ VexRay Topics ({len(topics)})\n")
            for t in topics:
                print(f"     • {t}")
            print(f"\n  Usage: vexray start \"<name>\"\n")

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


if __name__ == "__main__":
    main()
