from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
from app.api.v1 import auth, topics, quizzes, study_plan, votes, mentors, sessions
from app.core.db import init_db
from app.core.config import settings
from app.core.limiter import limiter


@asynccontextmanager
async def lifespan(app: FastAPI):
    init_db()  # sync — safe to call from async context
    yield


app = FastAPI(title="Quiz API", version="1.0.0", lifespan=lifespan, redirect_slashes=False)

# Rate Limiter
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Routers
app.include_router(auth.router, tags=["auth"])
app.include_router(topics.router, tags=["topics"])
app.include_router(quizzes.router, tags=["quizzes"])
app.include_router(study_plan.router, tags=["study-plan"])
app.include_router(votes.router, tags=["votes"])
app.include_router(mentors.router, tags=["mentors"])
app.include_router(sessions.router, tags=["sessions"])


@app.get("/")
async def root():
    return {"message": "Welcome to the Quiz API"}


@app.get("/health")
async def health():
    return {"status": "ok"}


@app.post("/test-post")
async def test_post():
    return {"method": "POST", "status": "ok"}
