"""HTTP error handlers."""

from __future__ import annotations

from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse

from ocr_sprint.utils.logging import get_logger

_logger = get_logger(__name__)


class OCRServiceError(Exception):
    """Base class for application errors that should map to a 4xx response."""

    http_status: int = status.HTTP_400_BAD_REQUEST


class UnsupportedDocumentError(OCRServiceError):
    """Uploaded file is neither a PDF nor a recognized image format."""


class JobNotFoundError(OCRServiceError):
    http_status = status.HTTP_404_NOT_FOUND


def register_error_handlers(app: FastAPI) -> None:
    """Wire OCRServiceError + a final fallback for unexpected exceptions."""

    @app.exception_handler(OCRServiceError)
    async def _ocr_error_handler(_: Request, exc: OCRServiceError) -> JSONResponse:
        return JSONResponse(
            status_code=exc.http_status,
            content={"error": exc.__class__.__name__, "message": str(exc)},
        )

    @app.exception_handler(Exception)
    async def _unexpected_handler(_: Request, exc: Exception) -> JSONResponse:
        _logger.exception("api.unhandled_exception", error=str(exc))
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content={"error": "InternalServerError", "message": "Unexpected error"},
        )
