import subprocess
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

from folkugat_web import log
from folkugat_web.api import router
from folkugat_web.config import db, directories
from folkugat_web.dal.sql.ddl import create_db


@asynccontextmanager
async def lifespan(_: FastAPI):
    """
    Context manager for FastAPI app. It will run all code before `yield`
    on app startup, and will run code after `yeld` on app shutdown.
    """

    log.logger.info("Running Tailwind CSS...")
    try:
        subprocess.run([
            "tailwindcss",
            "-i",
            directories.STATIC_DIR / "src" / "tw.css",
            "-o",
            directories.STATIC_DIR / "css" / "main.css",
            # "--minify"
        ])
        log.logger.info("Tailwind CSS done")
    except Exception as e:
        log.logger.error(f"Error running tailwindcss: {e}")

    log.logger.info("Creating DB...")
    create_db()
    log.logger.info("DB created")

    yield


def get_app() -> FastAPI:
    app = FastAPI(lifespan=lifespan)
    app.include_router(router)

    app.mount("/static", StaticFiles(directory=directories.STATIC_DIR), name="static")
    app.mount(db.DB_FILES_URL, StaticFiles(directory=db.DB_FILES_DIR), name="fitxers")

    return app


app = get_app()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)
