from loguru import logger
from fastapi.exceptions import StarletteHTTPException
from fastapi.responses import JSONResponse
from starlette.requests import Request

from huibiao_framework.backend import BaseRespVo, CommonStatusCode
from huibiao_framework.backend.utils import extract_url


def http_exception_interceptor(request: Request, exc: StarletteHTTPException):
    url = extract_url(request)

    reqid: str = request.headers.get("x-request-id", None)

    logger.info(f"req_id: {url} | 错误码: {exc.status_code} | 错误信息: {exc.detail}")
    if exc.status_code == 405:
        vo = BaseRespVo.from_status_code(CommonStatusCode.ERROR_REQ_METHOD, url=url)
    elif exc.status_code == 404:
        vo = BaseRespVo.from_status_code(CommonStatusCode.ERROR_REQ_URL)
    else:
        vo = BaseRespVo.from_status_code(
            CommonStatusCode.UNKNOWN_ERROR, msg=f"{exc.status_code},{exc.detail}"
        )

    return JSONResponse(content=vo.set_request_id(reqid).model_dump(), status_code=200)
