"""
CloudSearch Transfer — 错误码定义 v1.0.0
参考 netdisk Go SDK 的错误码设计 + 各项目实践
"""

from enum import IntEnum


class TransferErrorCode(IntEnum):
    """统一错误码"""
    # 通用错误 (40xxx)
    URL_INVALID = 40001          # URL格式错误或无法识别平台
    NOT_LOGIN = 40002            # 未登录或凭证已失效
    CAPACITY_FULL = 40003        # 存储空间容量不足
    SHARE_NOT_EXIST = 40004      # 分享不存在或已失效
    PASSCODE_WRONG = 40005       # 提取码错误
    RESOURCE_EMPTY = 40006       # 资源内容为空或全为广告文件
    NETWORK_ERROR = 40007        # 网络请求失败
    TIMEOUT = 40008              # 操作超时
    NO_CONFIG = 40009            # 该平台未配置凭证
    SHARE_LINK_FAIL = 40010      # 分享创建失败
    SHARE_LIMIT = 40011          # 今日分享次数过多
    DIR_NOT_EXIST = 40012        # 目标存储目录不存在
    SENSITIVE_RESOURCE = 40013   # 资源内容违规

    # 平台特有错误 (41xxx)
    BAIDU_BDSTOKEN_FAIL = 41001  # 百度bdstoken获取失败
    ALIYUN_TOKEN_EXPIRED = 41002 # 阿里Token过期
    XUNLEI_CAPTCHA_FAIL = 41003  # 迅雷验证码失败
    QUARK_LOGIN_REQUIRED = 41004 # 夸克需要重新登录


class TransferError(Exception):
    """转存异常"""
    def __init__(self, code: TransferErrorCode, message: str = None,
                 platform: str = None, details: dict = None):
        self.code = code
        self.message = message or self._default_message(code)
        self.platform = platform
        self.details = details or {}
        super().__init__(self.message)

    @staticmethod
    def _default_message(code: TransferErrorCode) -> str:
        messages = {
            TransferErrorCode.URL_INVALID: "URL格式错误或无法识别平台",
            TransferErrorCode.NOT_LOGIN: "未登录或凭证已失效",
            TransferErrorCode.CAPACITY_FULL: "存储空间容量不足",
            TransferErrorCode.SHARE_NOT_EXIST: "分享不存在或已失效",
            TransferErrorCode.PASSCODE_WRONG: "提取码错误",
            TransferErrorCode.RESOURCE_EMPTY: "资源内容为空或全为广告文件",
            TransferErrorCode.NETWORK_ERROR: "网络请求失败",
            TransferErrorCode.TIMEOUT: "操作超时",
            TransferErrorCode.NO_CONFIG: "该平台未配置凭证",
            TransferErrorCode.SHARE_LINK_FAIL: "分享创建失败",
            TransferErrorCode.SHARE_LIMIT: "今日分享次数过多",
            TransferErrorCode.DIR_NOT_EXIST: "目标存储目录不存在",
            TransferErrorCode.SENSITIVE_RESOURCE: "资源内容违规",
        }
        return messages.get(code, f"未知错误 (code={code})")

    def to_dict(self) -> dict:
        return {
            "code": self.code.value,
            "message": self.message,
            "platform": self.platform,
            "details": self.details,
        }
