from typing import Any

from fastapi import Request
from fastapi.responses import JSONResponse


class GatewayError(Exception):
    """Base application error."""

    def __init__(
        self,
        message: str,
        *,
        code: str = "gateway_error",
        status_code: int = 500,
        details: dict[str, Any] | None = None,
    ) -> None:
        self.message = message
        self.code = code
        self.status_code = status_code
        self.details = details or {}
        super().__init__(message)


class NotImplementedStubError(GatewayError):
    def __init__(self, capability: str) -> None:
        super().__init__(
            f"{capability} is stubbed and not yet implemented",
            code="not_implemented",
            status_code=501,
            details={"capability": capability},
        )


async def gateway_error_handler(_: Request, exc: GatewayError) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "error": {
                "code": exc.code,
                "message": exc.message,
                "details": exc.details,
            }
        },
    )
