from __future__ import annotations

from pathlib import Path

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

from app.api.v1.router import api_router
from app.core.config import settings
from app.db.session import SessionLocal
from app.modules.orion.template_service import ReportTemplateService

app = FastAPI(title=settings.app_name, version="0.1.0")
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Path("/app/uploads").mkdir(parents=True, exist_ok=True)
app.mount("/uploads", StaticFiles(directory="/app/uploads"), name="uploads")
app.include_router(api_router)


@app.on_event("startup")
def load_reference_templates() -> None:
    with SessionLocal() as session:
        ReportTemplateService(session).ensure_default_template()
        session.commit()


@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}
