import logging
from typing import Optional

from algo_backend.exception import (
    BasicApiId,
    BasicApiInnerException,
    BasicCommonException,
    CommonStatusCode,
)
from algo_backend.schema import AbstractRespVo

logger = logging.getLogger(__name__)


def gen_vo_from_exception(
    vo_cls: type(AbstractRespVo),
    e: Exception,
    api_name: Optional[str] = None,
    request_id: Optional[str] = None,
    api_id: Optional[BasicApiId] = None,
) -> AbstractRespVo:
    """
    将异常转换为vo
    """

    _params = dict(api_name=api_name, request_id=request_id)
    if isinstance(e, BasicCommonException):
        vo = vo_cls.from_exception(e, **_params)
    elif isinstance(e, BasicApiInnerException):
        vo = vo_cls.from_exception(e.add_api_id(api_id=api_id), **_params)
    else:
        vo = vo_cls.from_exception(
            BasicCommonException(CommonStatusCode.UNKNOWN_ERROR, msg=str(e)),
            **_params,
        )

    return vo
