"""FastAPI application factory for the Ilum API."""

from __future__ import annotations

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI

from ilum.api.auth import require_auth
from ilum.api.errors import ilum_error_handler
from ilum.api.routers import modules, operations, release, status, values
from ilum.errors import IlumError


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """Startup/shutdown lifecycle — auto-connect to the release."""
    from ilum.api.startup import auto_connect

    auto_connect()
    yield


def create_app() -> FastAPI:
    """Build and return the FastAPI application."""
    app = FastAPI(
        title="Ilum API",
        description="REST API for Ilum module management",
        version="0.1.0",
        lifespan=lifespan,
        root_path="",
    )

    # Exception handlers
    app.add_exception_handler(IlumError, ilum_error_handler)  # type: ignore[arg-type]

    # Routers — health has no auth, all others require it
    app.include_router(status.router, prefix="/api/v1")
    auth_deps = [Depends(require_auth)]
    app.include_router(modules.router, prefix="/api/v1", dependencies=auth_deps)
    app.include_router(values.router, prefix="/api/v1", dependencies=auth_deps)
    app.include_router(operations.router, prefix="/api/v1", dependencies=auth_deps)
    app.include_router(release.router, prefix="/api/v1", dependencies=auth_deps)

    return app
