from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pathlib import Path

from backend.core.config import settings
from backend.database.connection import init_db


@asynccontextmanager
async def lifespan(app: FastAPI):
    init_db()
    from backend.services.scheduler import start_scheduler, load_settings_from_db
    start_scheduler()
    load_settings_from_db()
    yield
    from backend.services.scheduler import stop_scheduler
    stop_scheduler()


app = FastAPI(
    title=settings.APP_NAME,
    lifespan=lifespan,
)

BASE_DIR = Path(__file__).resolve().parent.parent
app.mount("/static", StaticFiles(directory=BASE_DIR / "frontend" / "static"), name="static")
app.mount("/downloads", StaticFiles(directory=settings.download_path), name="downloads")

templates = Jinja2Templates(directory=BASE_DIR / "frontend" / "templates")


from backend.api.routes import router as api_router  # noqa: E402
from backend.api.pages import router as pages_router  # noqa: E402

app.include_router(api_router, prefix="/api")
app.include_router(pages_router)
