"""FastAPI application entry point."""

from contextlib import asynccontextmanager
from typing import AsyncGenerator

import structlog
from fastapi import FastAPI

from src.api.middleware import (
    add_cors_middleware,
    add_exception_handlers,
    add_request_middleware,
)
from src.api.routes import (
    admin_taxonomy_router,
    documents_router,
    health_router,
    query_router,
    tags_router,
)
from src.core.logging import configure_logging

# Configure structured logging before anything else
configure_logging()

logger = structlog.get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """Manage application lifespan events.

    Handles startup and shutdown operations.
    Future: Initialize database connections, redis, etc.

    Args:
        app: FastAPI application instance.

    Yields:
        None during application runtime.
    """
    # Startup
    logger.info("api_starting", version=app.version)

    yield

    # Shutdown
    logger.info("api_shutting_down")


app = FastAPI(
    title="DSOL",
    description="LLM-powered document processing service for Excel file extraction and semantic Q&A",
    version="1.0.0",
    lifespan=lifespan,
)

# Add middleware (order matters)
add_cors_middleware(app)
add_exception_handlers(app)
add_request_middleware(app)  # Adds request ID and logging middleware

# Include routers
app.include_router(health_router)
app.include_router(documents_router)
app.include_router(query_router)
app.include_router(tags_router)
app.include_router(admin_taxonomy_router)
