"""ComplyForm API — FastAPI application entry point.

Cloud Run service serving license validation, health checks,
Paddle billing webhooks, and dashboard pages.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

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

from backend.api.middleware.api_key_auth import (
    APIKeyAuthError,
    api_key_auth_error_response,
)
from backend.api.routes.dashboard_api import router as dashboard_api_router
from backend.api.routes.dashboard_configure import router as configure_router
from backend.api.routes.data import data_router
from backend.api.routes.health import router as health_router
from backend.api.routes.license import router as license_router
from backend.api.routes.nps import router as nps_router
from backend.api.routes.paddle_webhook import router as paddle_router
from backend.api.routes.report import router as report_router
from backend.api.routes.scim import scim_router
from backend.dashboard.auth_routes import auth_router
from backend.dashboard.founder.routes import founder_router
from backend.dashboard.middleware import (
    DashboardAuthError,
    dashboard_auth_error_response,
)
from backend.dashboard.middleware.security_headers import (
    SecurityHeadersMiddleware,
)
from backend.dashboard.routes import router as dashboard_page_router

if TYPE_CHECKING:
    from fastapi import Request
    from fastapi.responses import JSONResponse

app = FastAPI(
    title="ComplyForm API",
    docs_url=None,
    redoc_url=None,
)

app.add_middleware(SecurityHeadersMiddleware)

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://complyform.dev",
        "https://dashboard.complyform.dev",
    ],
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=[
        "Authorization",
        "X-API-Key",
        "Content-Type",
        "X-CSRF-Token",
    ],
)

app.mount(
    "/static",
    StaticFiles(directory="backend/dashboard/static"),
    name="static",
)

app.include_router(health_router)
app.include_router(license_router)
app.include_router(paddle_router)
app.include_router(dashboard_api_router)
app.include_router(configure_router)
app.include_router(auth_router)
app.include_router(scim_router)
app.include_router(data_router)
app.include_router(report_router)
app.include_router(nps_router)
app.include_router(founder_router)
app.include_router(dashboard_page_router)


@app.exception_handler(APIKeyAuthError)
async def _api_key_error_handler(
    request: Request,
    exc: APIKeyAuthError,
) -> JSONResponse:
    return api_key_auth_error_response(exc)


@app.exception_handler(DashboardAuthError)
async def _dashboard_auth_error_handler(
    request: Request,
    exc: DashboardAuthError,
) -> JSONResponse:  # type: ignore[return-value]
    return dashboard_auth_error_response(exc, request)
