"""Gateway2 server -- re-exports from keiro.gateway.server.

The ``create_app`` function is the canonical entry point.  It now lives in
``keiro.gateway.server`` and is re-exported here for backward compatibility.
The ``main`` / ``_parse_args`` CLI helpers remain local because they are
gateway2-specific (env-var naming, argparse description).
"""

from __future__ import annotations

import argparse
import logging
import os

from aiohttp import web

from keiro.gateway.server import create_app  # noqa: F401

LOG = logging.getLogger(__name__)


def _env_int(name: str, default: int) -> int:
    value = os.environ.get(name)
    if not value:
        return default
    try:
        candidate = int(value)
    except ValueError:
        return default
    return max(candidate, 0)


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Run the experimental gateway2 service.")
    parser.add_argument("--host", default=os.environ.get("GATEWAY2_HOST", "0.0.0.0"))
    parser.add_argument("--port", type=int, default=int(os.environ.get("GATEWAY2_PORT", "9000")))
    parser.add_argument(
        "--access-log",
        action="store_true",
        default=False,
        help="Enable aiohttp access logging.",
    )
    parser.add_argument(
        "--backlog",
        type=int,
        default=_env_int("GATEWAY2_BACKLOG", 65_535),
        help="Backlog size passed to the listening socket.",
    )
    parser.add_argument(
        "--shutdown-timeout",
        type=int,
        default=_env_int("GATEWAY2_SHUTDOWN_TIMEOUT_S", 300),
        help="Seconds to wait for graceful shutdown before aborting connections.",
    )
    parser.add_argument(
        "--keepalive-timeout",
        type=int,
        default=_env_int("GATEWAY2_KEEPALIVE_TIMEOUT_S", 120),
        help="Seconds to wait for keepalive activity on idle connections.",
    )
    parser.add_argument(
        "--enable-judge-stream",
        action="store_true",
        default=False,
        help=(
            "Enable native judge streaming for eb1-codex "
            "(passes through reasoning summary deltas)."
        ),
    )
    return parser.parse_args()


def main() -> None:
    logging.basicConfig(level=os.environ.get("GATEWAY2_LOG_LEVEL", "INFO"))
    args = _parse_args()
    app = create_app(enable_judge_stream=args.enable_judge_stream)
    LOG.info(
        "Starting gateway2 server on %s:%s (judge_stream=%s)",
        args.host,
        args.port,
        args.enable_judge_stream,
    )
    access_logger = LOG if args.access_log else None
    web.run_app(
        app,
        host=args.host,
        port=args.port,
        access_log=access_logger,
        backlog=args.backlog,
        shutdown_timeout=args.shutdown_timeout,
        keepalive_timeout=args.keepalive_timeout,
        print=None,
    )


if __name__ == "__main__":
    main()
