"""HTTP/REST transport for Albus.

This is a thin translation layer - no business logic.
Routes are organized by domain in handlers/ subdirectory.
Middleware stack is assembled from server config (timeouts, auth, CORS, etc.).
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING

from aiohttp import web

from server.config.env import get_config
from server.transport.middleware import build_middleware_stack
from server.transport.routes import register_routes
from server.transport.utils import RUNTIME_KEY

if TYPE_CHECKING:
    from server.runtime import Runtime

logger = logging.getLogger(__name__)


def create_http_app(runtime: Runtime) -> web.Application:
    """Create aiohttp application with Albus routes.

    The middleware stack is built from ``AlbusConfig.server`` so that
    timeouts, CORS, rate-limiting, and auth are all configurable via
    environment variables rather than hardcoded.

    Args:
        runtime: Runtime instance

    Returns
    -------
        Configured aiohttp Application
    """
    config = get_config()
    sc = config.server

    app = web.Application()

    # Store runtime in app state
    app[RUNTIME_KEY] = runtime

    # Build middleware from config
    middlewares = build_middleware_stack(
        request_timeout=sc.request_timeout,
        cors_allowed_origins=sc.cors_allowed_origins,
        cors_allowed_methods=sc.cors_allowed_methods,
        cors_allowed_headers=sc.cors_allowed_headers,
        api_keys=sc.api_keys if sc.api_keys else None,
        rate_limit_rpm=sc.rate_limit_rpm,
    )
    for mw in middlewares:
        app.middlewares.append(mw)

    # Register all routes
    register_routes(app)

    logger.info("HTTP routes registered")
    return app


__all__ = [
    "create_http_app",
]
