"""
plyra-trace CLI

Commands:
  plyra-trace serve             Start collector + UI
  plyra-trace serve --port 7700 --otlp-port 4318
  plyra-trace keys create --project NAME
  plyra-trace keys list
  plyra-trace keys revoke KEY_PREFIX
  plyra-trace version
"""

import argparse
import sys


def main() -> None:
    """Entry point for the plyra-trace CLI."""
    parser = argparse.ArgumentParser(
        prog="plyra-trace",
        description="plyra-trace — behavioral observability for agentic AI.",
    )
    sub = parser.add_subparsers(dest="command")

    # ── serve ──────────────────────────────────────────────────────────────────
    serve = sub.add_parser("serve", help="Start the collector and UI")
    serve.add_argument("--host", default="127.0.0.1", help="Bind host (default: 127.0.0.1)")
    serve.add_argument("--port", type=int, default=7700, help="UI + API port (default: 7700)")
    serve.add_argument(
        "--otlp-port",
        type=int,
        default=None,
        dest="otlp_port",
        help="Separate OTLP port (default: same as --port, /v1/traces route)",
    )
    serve.add_argument(
        "--db",
        default="~/.plyra/traces.db",
        help="SQLite database path (default: ~/.plyra/traces.db)",
    )
    serve.add_argument(
        "--no-auth",
        action="store_true",
        help="Disable API key authentication (dev mode)",
    )

    # ── keys ───────────────────────────────────────────────────────────────────
    keys = sub.add_parser("keys", help="Manage API keys")
    keys_sub = keys.add_subparsers(dest="keys_command")

    create = keys_sub.add_parser("create", help="Create a new API key")
    create.add_argument("--project", required=True, help="Project name for this key")

    keys_sub.add_parser("list", help="List all API keys")

    revoke = keys_sub.add_parser("revoke", help="Revoke an API key by prefix")
    revoke.add_argument("key_prefix", help="Key prefix to revoke (e.g. plt_live_7f3a)")

    # ── version ────────────────────────────────────────────────────────────────
    sub.add_parser("version", help="Print version and exit")

    args = parser.parse_args()

    if args.command == "serve":
        from plyra_trace.collector.server import run_server

        run_server(
            host=args.host,
            port=args.port,
            otlp_port=args.otlp_port,
            db_path=args.db,
            auth_enabled=not args.no_auth,
        )

    elif args.command == "keys":
        from plyra_trace.collector.auth import handle_keys_command

        handle_keys_command(args)

    elif args.command == "version":
        from plyra_trace import __version__

        print(f"plyra-trace {__version__}")

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