from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

from logsetup import setup_logging

setup_logging()

from config import FRONTEND_DIST, STORAGE_DIR
from database import init_db, close_db
from guide import reconcile_guides
from routes import router


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


app = FastAPI(title="Creator", lifespan=lifespan)

app.include_router(router)

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