import os
from pathlib import Path

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

from pages import router as pages_router, files_router, ensure_default_pages
from docker_utils import router as docker_router
from converter import router as converter_router
from browse import router as browse_router, start_browser

app = FastAPI(title="µFrame Editor")

app.include_router(converter_router, prefix="/api")
app.include_router(pages_router, prefix="/api")
app.include_router(files_router, prefix="/api")
app.include_router(docker_router, prefix="/api")
app.include_router(browse_router, prefix="/api")


@app.on_event("startup")
async def startup():
    ensure_default_pages()
    start_browser()


@app.get("/api/health")
async def health():
    return {"status": "ok"}


# Serve built frontend as static files with SPA fallback
static_dir = Path(__file__).parent / "static"
if static_dir.is_dir():
    from fastapi.responses import FileResponse

    app.mount("/assets", StaticFiles(directory=str(static_dir / "assets")), name="assets")

    @app.get("/{path:path}")
    async def spa_fallback(path: str):
        file = static_dir / path
        if file.is_file():
            return FileResponse(file)
        return FileResponse(static_dir / "index.html")
