from typing import TypeVar

from .status_code import BasicApiId, BasicApiInnerErrorCode, BasicStatusCode


class BasicException(Exception):
    """
    基础异常类
    """

    def __init__(self, code: int, msg: str):
        super().__init__(msg)
        self.code = code
        self.msg = msg


# 定义泛型变量 T，限定为 BasicStatusCode 的子类
T = TypeVar("T", bound=BasicStatusCode)


class BasicCommonException(BasicException):
    def __init__(self, status_code: T, **kwargs):
        super().__init__(code=status_code.code, msg=status_code.msg.format(**kwargs))


# 定义泛型变量 ET，限定为 BasicApiInnerErrorCode 的子类
ET = TypeVar("ET", bound=BasicApiInnerErrorCode)


class BasicApiInnerException(BasicException):
    """
    接口内部异常类的基类
    """

    def __init__(self, status_code: ET, **kwargs):
        super().__init__(code=status_code.code, msg=status_code.msg.format(**kwargs))

    def add_api_id(self, api_id: BasicApiId) -> "BasicApiInnerException":
        self.code = BasicApiInnerErrorCode.gen_standard_code(
            api_id=api_id, inner_error_code=self.code
        )
        return self
