"""Keiro command-line interface.

Usage::

    keiro serve [--port PORT] [--in-memory] [--enable-judge-stream]
    keiro --version
    keiro --help
"""

from __future__ import annotations

import argparse
import logging
import os
import sys

import keiro


def main(argv: list[str] | None = None) -> int:
    """Keiro CLI entry point.

    Args:
        argv: Command-line arguments. Defaults to sys.argv[1:].

    Returns:
        Exit code.
    """
    parser = argparse.ArgumentParser(
        prog="keiro",
        description="Keiro: EB1 inference service.",
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"keiro {keiro.__version__}",
    )

    subparsers = parser.add_subparsers(dest="command")

    # keiro serve
    from keiro.cli.serve import build_parser as _serve_parser, run as _serve_run

    serve_parser = _serve_parser()
    subparsers.add_parser(
        "serve",
        parents=[serve_parser],
        add_help=False,
        help="Start the Keiro inference gateway.",
    )

    # keiro setup
    from keiro.cli.setup import build_parser as _setup_parser, run as _setup_run

    setup_parser = _setup_parser()
    subparsers.add_parser(
        "setup",
        parents=[setup_parser],
        add_help=False,
        help="Configure Keiro API credentials.",
    )

    args = parser.parse_args(argv)

    if args.command is None:
        parser.print_help()
        return 1

    logging.basicConfig(
        level=os.environ.get("KEIRO_LOG_LEVEL", "INFO"),
        format="%(asctime)s %(levelname)s %(name)s: %(message)s",
    )

    if args.command == "serve":
        return _serve_run(args)

    if args.command == "setup":
        return _setup_run(args)

    parser.print_help()
    return 1


def cli_entry() -> None:
    """Script entry point for ``pyproject.toml [project.scripts]``."""
    sys.exit(main())
