from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

from config import FRONTEND_DIST, STORAGE_DIR, PROJECTS_CACHE_DIR
from database import init_db, close_db
from routes import router


@asynccontextmanager
async def lifespan(app: FastAPI):
    (STORAGE_DIR / "html").mkdir(parents=True, exist_ok=True)
    (STORAGE_DIR / "pdf").mkdir(parents=True, exist_ok=True)
    PROJECTS_CACHE_DIR.mkdir(parents=True, exist_ok=True)
    await init_db()
    yield
    await close_db()


app = FastAPI(title="Guides Generator", lifespan=lifespan)

app.include_router(router)

if FRONTEND_DIST.exists():
    app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend")
