"""FastAPI application factory."""
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.v1.router import v1_router
from app.config import settings
from app.middleware.disclaimer import DisclaimerMiddleware
from app.middleware.rate_limit import RateLimitMiddleware


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage startup and shutdown events."""
    # Startup: initialize connections, warm caches, etc.
    yield
    # Shutdown: close connections, flush buffers, etc.


def create_app() -> FastAPI:
    """Create and configure the FastAPI application."""
    application = FastAPI(
        title=settings.app_name,
        description=(
            "FastAPI template for medical and healthcare applications. "
            "Includes drug interaction checking, device-based auth, "
            "medical disclaimer middleware, and HIPAA compliance patterns."
        ),
        version="0.1.0",
        docs_url="/docs",
        redoc_url="/redoc",
        lifespan=lifespan,
    )

    # Middleware (order matters -- outermost first)
    application.add_middleware(DisclaimerMiddleware, disclaimer_text=settings.disclaimer_text)
    application.add_middleware(
        RateLimitMiddleware, requests_per_minute=settings.rate_limit_per_minute
    )
    application.add_middleware(
        CORSMiddleware,
        allow_origins=settings.cors_origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # Routes
    application.include_router(v1_router, prefix="/api/v1")

    @application.get("/health", tags=["system"])
    async def health_check():
        return {"status": "healthy"}

    return application


app = create_app()
