from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

from app.utils.json_sanitize import sanitize_for_json


class SanitizedJSONResponse(JSONResponse):
    """JSONResponse that guarantees JSON-compliant output.

    Starlette JSONResponse uses `allow_nan=False`, so NaN/Inf will raise.
    This response class sanitizes the content (after jsonable_encoder) to avoid crashes.
    """

    def render(self, content) -> bytes:
        encoded = jsonable_encoder(content)
        sanitized = sanitize_for_json(encoded)
        return super().render(sanitized)
