from pathlib import Path

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

from app import admin, benefits_api, frontend, reports_api
from app.config import get_settings
from app.db import init_db
from app.web_search import web_search_app

settings = get_settings()

app = FastAPI(title="taller-wox.fitlabs.dev", version="1.0.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

_STATIC_DIR = Path(__file__).parent.parent / "static"
app.mount("/static", StaticFiles(directory=str(_STATIC_DIR)), name="static")

app.include_router(frontend.router)
app.include_router(benefits_api.router)
app.include_router(reports_api.router)
app.include_router(admin.router)

_reports_dir = Path(settings.reports_output_dir)
_reports_dir.mkdir(parents=True, exist_ok=True)
app.mount(
    "/api/reports/output",
    StaticFiles(directory=str(_reports_dir)),
    name="reports_output",
)

app.mount("/web-search", web_search_app)


@app.on_event("startup")
def on_startup() -> None:
    init_db()


@app.get("/health")
def health():
    return {"status": "ok", "base_url": settings.base_url}
