from json import loads
from fastapi import status

from fastapi.requests import Request
from fastapi.exceptions import HTTPException
from fastapi.responses import JSONResponse


def exception_handler_http(request: Request, exc: HTTPException):
    exc_detail = getattr(exc, "detail", None)
    try:
        detail = loads(str(exc_detail))
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "Data": detail.get("data", {}),
                "Error": detail.get("error_case", "UNKNOWN"),
                "Message": detail.get(
                    "message", "An error occurred while processing the request"
                ),
            },
        )
    except Exception as e:
        return JSONResponse(
            status_code=exc.status_code,
            content={"Error": str(exc_detail), "Message": f"{str(e)}", "Data": {}},
        )


def exception_handler_exception(request: Request, exc: Exception):
    return JSONResponse(
        status_code=status.HTTP_417_EXPECTATION_FAILED,
        content={"message": exc.__str__()},
    )
