"""Keiro gateway server.

Creates and runs the aiohttp application that serves EB1 as a
drop-in model endpoint.

Example::

    from keiro.gateway.server import create_app
    app = create_app()
    # Or run directly:
    # keiro serve --port 9000
"""

from __future__ import annotations

import logging

from aiohttp import web

from .adapters.runtime import RuntimeOptions
from .boot.bootstrap import bootstrap
from .http.app import build_app

LOG = logging.getLogger(__name__)


def create_app(
    *,
    allow_in_memory_fallback: bool = False,
    enable_judge_stream: bool = False,
) -> web.Application:
    """Build the Keiro gateway application.

    Constructs the full middleware stack, bootstraps service dependencies,
    registers API routes, and returns a ready-to-run aiohttp Application.

    Args:
        allow_in_memory_fallback: When True, use in-memory stores instead
            of requiring Postgres/Redis. Useful for local development and
            testing.
        enable_judge_stream: When True, enable native judge streaming for
            eb1-codex models (passes through reasoning summary deltas).

    Returns:
        Configured aiohttp Application ready for ``web.run_app()``.
    """
    runtime_options = RuntimeOptions(
        allow_in_memory_fallback=allow_in_memory_fallback,
        enable_judge_stream=enable_judge_stream,
    )
    services = bootstrap(options=runtime_options)
    app = build_app(services, options=runtime_options)
    LOG.info("Keiro gateway application created")
    return app


def run_server(
    *,
    host: str = "0.0.0.0",
    port: int = 9000,
    allow_in_memory_fallback: bool = False,
    enable_judge_stream: bool = False,
    access_log: bool = False,
    backlog: int = 65_535,
    shutdown_timeout: int = 300,
    keepalive_timeout: int = 120,
) -> None:
    """Start the Keiro gateway server.

    Args:
        host: Bind address.
        port: Bind port.
        allow_in_memory_fallback: Use in-memory stores for development.
        enable_judge_stream: Enable native judge streaming.
        access_log: Enable aiohttp access logging.
        backlog: Listening socket backlog.
        shutdown_timeout: Seconds to wait for graceful shutdown.
        keepalive_timeout: Seconds for keepalive on idle connections.
    """
    app = create_app(
        allow_in_memory_fallback=allow_in_memory_fallback,
        enable_judge_stream=enable_judge_stream,
    )
    LOG.info("Starting Keiro on %s:%d", host, port)
    web.run_app(
        app,
        host=host,
        port=port,
        access_log=LOG if access_log else None,
        backlog=backlog,
        shutdown_timeout=shutdown_timeout,
        keepalive_timeout=keepalive_timeout,
        print=None,
    )


__all__ = ["create_app", "run_server"]
