import logging

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

from algo_backend.exception import BasicCommonException, CommonStatusCode

from .common import BasicExceptionInterceptor

logger = logging.getLogger(__name__)


class HTTPExceptionInterceptor(BasicExceptionInterceptor):
    """
    拦截接口关于http异常的报错，并返回约定的body
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def intercept(self, request: Request, exc: StarletteHTTPException):
        url: str = self.extract_url(request)
        reqid: str = self.get_request_id(request)

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

        vo = self.get_vo_type(url).from_exception(e, request_id=reqid)

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