"""APICOMPAT-01: validation input·예외 원문을 Stream 오류에 반환하지 않는다."""

from fastapi.exceptions import RequestValidationError
from fastapi.exception_handlers import request_validation_exception_handler
from fastapi.responses import JSONResponse

from app.stream_config_store import ConfigPersistenceError


def install_stream_error_handlers(application):
    @application.exception_handler(ConfigPersistenceError)
    async def persistence_error(_request, _error):
        return JSONResponse(status_code=503, content={"detail": {
            "error_code": "CONFIG_PERSISTENCE_FAILED",
            "message": "Stream configuration could not be persisted.",
        }})

    @application.exception_handler(RequestValidationError)
    async def validation_error(request, error):
        if request.url.path.startswith(("/api/v1/streams", "/api/v1/cameras")):
            return JSONResponse(status_code=422, content={"detail": [{
                "type": "value_error", "loc": ["body"],
                "msg": "Invalid stream request.",
            }]})
        return await request_validation_exception_handler(request, error)
