"""CLI entry point: ``minitrail serve [logs_dir] [--port PORT]``."""

from __future__ import annotations

import argparse
import sys


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(
        prog="minitrail",
        description="Lightweight file-based OTel tracing for AI agent frameworks",
    )
    sub = parser.add_subparsers(dest="command")

    serve = sub.add_parser("serve", help="Launch the trace viewer web UI")
    serve.add_argument(
        "logs_dir",
        nargs="?",
        default="logs",
        help="Path to the logs directory (default: ./logs)",
    )
    serve.add_argument(
        "--port", "-p",
        type=int,
        default=8000,
        help="Port to listen on (default: 8000)",
    )
    serve.add_argument(
        "--host",
        default="127.0.0.1",
        help="Host to bind to (default: 127.0.0.1)",
    )
    serve.add_argument(
        "--pricing",
        default=None,
        help="Path to a minitrail_pricing.toml with custom model prices",
    )

    args = parser.parse_args(argv)

    if args.command == "serve":
        _serve(args.logs_dir, args.host, args.port, args.pricing)
    else:
        parser.print_help()
        sys.exit(1)


def _serve(logs_dir: str, host: str, port: int, pricing: str | None = None) -> None:
    import uvicorn

    from minitrail._pricing import set_user_pricing
    from minitrail._server import create_app

    set_user_pricing(pricing)
    app = create_app(logs_dir)
    print(f"minitrail viewer — http://{host}:{port}")
    print(f"Reading traces from: {logs_dir}")
    uvicorn.run(app, host=host, port=port)
