import os
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

from imptune.api import clients, drivers, health, icons, pages, packages, printers, scripts
from imptune.config import DATA_DIR, DRIVERS_DIR, ICONS_DIR
from imptune.db.database import db, init_db


@asynccontextmanager
async def lifespan(app: FastAPI):
    os.makedirs(DATA_DIR, exist_ok=True)
    os.makedirs(DRIVERS_DIR, exist_ok=True)
    os.makedirs(ICONS_DIR, exist_ok=True)
    init_db()
    yield
    # Close DB connection on shutdown so test fixtures can re-initialize cleanly
    if not db.is_closed():
        db.close()


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

# Serve baked-in static assets (pico.min.css, htmx.min.js, alpine.min.js)
_static_dir = Path(__file__).parent / "static"
app.mount("/static", StaticFiles(directory=str(_static_dir)), name="static")

# Register routers
app.include_router(health.router)
app.include_router(pages.router)
app.include_router(drivers.router)
app.include_router(printers.router)
app.include_router(clients.router)
app.include_router(scripts.router)
app.include_router(packages.router)
app.include_router(icons.router)
