"""TieMeasureFlow Server - FastAPI Entry Point."""
from contextlib import asynccontextmanager
from collections.abc import AsyncGenerator

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

from src.backend.config import settings
from src.backend.database import init_db
from src.backend.api.middleware.logging import AccessLogMiddleware
from src.backend.api.middleware.rate_limit import RateLimitMiddleware
from src.backend.api.middleware.security_headers import SecurityHeadersMiddleware
from src.backend.api.routers.auth import router as auth_router
from src.backend.api.routers.users import router as users_router
from src.backend.api.routers.recipes import router as recipes_router
from src.backend.api.routers.tasks import router as tasks_router
from src.backend.api.routers.measurements import router as measurements_router
from src.backend.api.routers.files import router as files_router
from src.backend.api.routers.settings import router as settings_router
from src.backend.api.routers.reports import router as reports_router
from src.backend.api.routers.statistics import router as statistics_router
from src.backend.api.routers.setup import router as setup_router
from src.backend.api.routers.stations import router as stations_router


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """Application lifespan: startup and shutdown events."""
    # Startup
    # Ensure upload directories exist
    for subdir in ["images", "pdfs", "logos", "reports"]:
        (settings.upload_path / subdir).mkdir(parents=True, exist_ok=True)

    yield

    # Shutdown (cleanup if needed)


app = FastAPI(
    title="TieMeasureFlow API",
    description="API per gestione task misurazioni con calibro manuale",
    version="0.1.0",
    lifespan=lifespan,
)

# Rate limiting middleware (outermost - checked first)
app.add_middleware(RateLimitMiddleware)

# Security headers middleware
app.add_middleware(SecurityHeadersMiddleware)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["Content-Type", "X-API-Key", "Accept"],
)

# Access logging middleware
app.add_middleware(AccessLogMiddleware)

# Register routers
app.include_router(auth_router)
app.include_router(users_router)
app.include_router(recipes_router)
app.include_router(tasks_router)
app.include_router(measurements_router)
app.include_router(files_router)
app.include_router(settings_router)
app.include_router(statistics_router)
app.include_router(reports_router)
app.include_router(setup_router)
app.include_router(stations_router)


@app.get("/api/health")
async def health_check() -> dict:
    """Health check endpoint."""
    return {"status": "ok", "service": "TieMeasureFlow API", "version": "0.1.0"}
