from fastapi import FastAPI
from contextlib import asynccontextmanager
from app.api.routes.health import router as health_router
from app.api.routes.workflow import router as workflow_router
from app.core.config import settings
from app.core.logging import setup_logging
from app.repositories.qdrant_repository import QdrantRepository

setup_logging()

@asynccontextmanager
async def lifespan(app: FastAPI):
    print("[Startup] Initialisation de Qdrant...")
    qdrant_repo = QdrantRepository()
    try:
        await qdrant_repo.init_collection(vector_size=1024) 
        app.state.qdrant_repo = qdrant_repo
        print("[Startup] Qdrant prêt et attaché à l'application.")
    except Exception as e:
        print(f"[Startup] Erreur fatale lors de l'initialisation de Qdrant : {e}")
        raise e
    
    yield
    
    print("[Shutdown] Fermeture propre de la connexion Qdrant...")
    await qdrant_repo.close()


app = FastAPI(
    title=settings.app_name,
    docs_url=None,
    redoc_url=None,
    openapi_url=None,
    lifespan=lifespan
)

app.include_router(health_router, prefix="/api")
app.include_router(workflow_router, prefix="/api")