"""CLI entry point: python -m agent_preflight <command> [args]

Commands:
    status [run_id]       — Show run status dashboard (defaults to latest run)
    cache-report [run_id] — Show detailed cache analytics (defaults to latest run)
    preflight             — Run preflight checks (reads env vars)
"""

from __future__ import annotations

import os
import sys
from pathlib import Path


def _cmd_status(argv: list[str]) -> None:
    from .status import main as status_main
    run_id = argv[0] if argv else None
    status_main(run_id=run_id)


def _cmd_cache_report(argv: list[str]) -> None:
    from .cache_report import main as cache_report_main
    run_id = argv[0] if argv else None
    cache_report_main(run_id=run_id)


def _cmd_preflight(argv: list[str]) -> None:  # noqa: ARG001
    from .preflight import preflight

    admin_key = os.environ.get("OR_ADMIN_KEY") or os.environ.get("OPENROUTER_ADMIN_KEY")
    or_key = os.environ.get("OPENROUTER_API_KEY")
    models_raw = os.environ.get("PREFLIGHT_MODELS", "")
    budget = float(os.environ.get("PREFLIGHT_BUDGET", "0.25"))

    if not admin_key:
        print("Error: OR_ADMIN_KEY / OPENROUTER_ADMIN_KEY not set.", file=sys.stderr)
        sys.exit(1)
    if not or_key:
        print("Error: OPENROUTER_API_KEY not set.", file=sys.stderr)
        sys.exit(1)

    models = [m.strip() for m in models_raw.split(",") if m.strip()]
    if not models:
        print("Error: PREFLIGHT_MODELS not set (comma-separated model IDs).", file=sys.stderr)
        sys.exit(1)

    try:
        preflight(
            admin_key=admin_key,
            or_key=or_key,
            models=models,
            budget_per_model=budget,
        )
    except Exception as exc:
        print(f"\nPreflight failed: {exc}", file=sys.stderr)
        sys.exit(1)


_COMMANDS = {
    "status": _cmd_status,
    "cache-report": _cmd_cache_report,
    "preflight": _cmd_preflight,
}


def main() -> None:
    argv = sys.argv[1:]
    if not argv or argv[0] in ("-h", "--help"):
        print(__doc__)
        sys.exit(0)

    cmd = argv[0]
    if cmd not in _COMMANDS:
        print(f"Unknown command: {cmd!r}. Available: {', '.join(_COMMANDS)}", file=sys.stderr)
        sys.exit(1)

    _COMMANDS[cmd](argv[1:])


if __name__ == "__main__":
    main()
