# backend/app/main.py
import os

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

from app.api.admin import router as admin_router
from app.api.auth import router as auth_router
from app.api.cases import router as cases_router
from app.api.coding import router as coding_router
from app.api.import_router import router as import_router
from app.api.notifications import router as notifications_router
from app.api.filter_presets import router as filter_presets_router
from app.api.reports import router as reports_router
from app.config import get_settings

settings = get_settings()

app = FastAPI(title=settings.APP_NAME, docs_url="/docs")

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS.split(","),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- Routers ---
app.include_router(auth_router, prefix="/api/auth", tags=["auth"])
app.include_router(admin_router, prefix="/api/admin", tags=["admin"])
app.include_router(import_router, prefix="/api/import", tags=["import"])
app.include_router(cases_router, prefix="/api/cases", tags=["cases"])
app.include_router(notifications_router, prefix="/api/notifications", tags=["notifications"])
app.include_router(coding_router, prefix="/api/coding", tags=["coding"])
app.include_router(reports_router, prefix="/api/reports", tags=["reports"])
app.include_router(filter_presets_router, prefix="/api/filter-presets", tags=["filter-presets"])


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


# --- Serve uploaded files ---
_uploads_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "uploads")
if os.path.isdir(_uploads_dir):
    app.mount("/uploads", StaticFiles(directory=_uploads_dir), name="uploads")

# --- Serve frontend SPA ---
_frontend_dist = os.path.join(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
    "frontend", "dist",
)

if os.path.isdir(_frontend_dist):
    app.mount("/assets", StaticFiles(directory=os.path.join(_frontend_dist, "assets")), name="static")

    @app.get("/{full_path:path}")
    async def serve_spa(request: Request, full_path: str):
        file_path = os.path.join(_frontend_dist, full_path)
        if full_path and os.path.isfile(file_path):
            return FileResponse(file_path)
        return FileResponse(os.path.join(_frontend_dist, "index.html"))
