"""``keiro serve`` command implementation.

Starts the Keiro gateway server that serves EB1 ensemble models
as drop-in endpoints compatible with OpenAI Chat Completions,
Responses API, and Anthropic Messages API formats.

Example::

    keiro serve --port 9000
    keiro serve --port 8080 --in-memory  # local development
"""

from __future__ import annotations

import argparse
import os
import sys


def _env_int(name: str, default: int) -> int:
    """Read an integer from an environment variable with a fallback."""
    value = os.environ.get(name)
    if not value:
        return default
    try:
        return max(int(value), 0)
    except ValueError:
        return default


def build_parser() -> argparse.ArgumentParser:
    """Build the argument parser for ``keiro serve``.

    Returns:
        Configured ArgumentParser.
    """
    parser = argparse.ArgumentParser(
        prog="keiro serve",
        description="Start the Keiro inference gateway.",
    )
    parser.add_argument(
        "--host",
        default=os.environ.get("KEIRO_HOST", "0.0.0.0"),
        help="Bind address (default: 0.0.0.0, env: KEIRO_HOST).",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=int(os.environ.get("KEIRO_PORT", "9000")),
        help="Bind port (default: 9000, env: KEIRO_PORT).",
    )
    parser.add_argument(
        "--in-memory",
        action="store_true",
        default=False,
        help="Use in-memory stores (no Postgres/Redis required). For development only.",
    )
    parser.add_argument(
        "--access-log",
        action="store_true",
        default=False,
        help="Enable aiohttp access logging.",
    )
    parser.add_argument(
        "--backlog",
        type=int,
        default=_env_int("KEIRO_BACKLOG", 65_535),
        help="Listening socket backlog size.",
    )
    parser.add_argument(
        "--shutdown-timeout",
        type=int,
        default=_env_int("KEIRO_SHUTDOWN_TIMEOUT_S", 300),
        help="Seconds to wait for graceful shutdown.",
    )
    parser.add_argument(
        "--keepalive-timeout",
        type=int,
        default=_env_int("KEIRO_KEEPALIVE_TIMEOUT_S", 120),
        help="Seconds for keepalive on idle connections.",
    )
    return parser


def run(args: argparse.Namespace) -> int:
    """Execute the serve command.

    Args:
        args: Parsed command-line arguments.

    Returns:
        Exit code (0 on success).
    """
    try:
        from keiro.gateway.server import run_server
    except ImportError as exc:
        print(
            "Error: gateway dependencies not installed.\n"
            "Install with: pip install 'keiro[gateway]'\n"
            f"\nMissing: {exc}",
            file=sys.stderr,
        )
        return 1

    run_server(
        host=args.host,
        port=args.port,
        allow_in_memory_fallback=args.in_memory,
        access_log=args.access_log,
        backlog=args.backlog,
        shutdown_timeout=args.shutdown_timeout,
        keepalive_timeout=args.keepalive_timeout,
    )
    return 0
