"""Main application entry point."""

from contextlib import asynccontextmanager

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

from src.core.registry import ROUTERS
from src.core.config import settings
{% if db_type %}
from src.core.database import init_db
{% endif %}
{% if use_redis %}
from src.core.cache import init_cache
{% endif %}


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan handler."""
    # Startup
{% if db_type %}
    await init_db()
{% endif %}
{% if use_redis %}
    await init_cache()
{% endif %}
    yield
    # Shutdown
    pass


app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    description=settings.DESCRIPTION,
    lifespan=lifespan,
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Register all routers from registry
for router in ROUTERS:
    app.include_router(router)


@app.get("/")
async def root():
    """Root endpoint."""
    return {
        "message": "Welcome to {{ project_name }}",
        "version": settings.VERSION,
        "docs_url": "/docs",
    }
