from contextlib import asynccontextmanager
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api.main import router
import asyncio
from app.rag.rag import chunkize, chunkize_async

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(router)

@asynccontextmanager
async def lifespan(app: FastAPI):
    print("Iniciant tasques de prestart...")
    asyncio.create_task(chunkize_async())
    yield
    print("Aplicació aturada.")

app.router.lifespan_context = lifespan
