from typing import Dict, Optional
import re


class ErrorSimulator:
    """错误场景模拟器"""

    # 错误码映射表
    ERROR_CODES = {
        "40100": {"code": "40100", "message": "未知异常"},
        "40101": {"code": "40101", "message": "appId错误"},
        "40102": {"code": "40102", "message": "appSecretCode错误"},
        "40104": {"code": "40104", "message": "可使用项目次数为0，无法创建项目"},
        "40105": {"code": "40105", "message": "只读模式下无法新建项目"},
        "40106": {"code": "40106", "message": "错误的分析类型，不在规定的取值范围内"},
        "40107": {"code": "40107", "message": "当前系统不支持的分析类型"},
        "40108": {"code": "40108", "message": "当前用户所属行社无权限"},
        "501014": {"code": "501014", "message": "无行内流水文件"},
    }

    @staticmethod
    def detect_error_marker(value: str) -> Optional[str]:
        """检测字符串中的错误标记

        规则：如果字符串包含 error_XXXX，则返回 XXXX
        例如：
        - "project_error_40101" -> "40101"
        - "test_error_501014" -> "501014"
        """
        if not value:
            return None

        pattern = r'error_(\d+)'
        match = re.search(pattern, value)
        if match:
            return match.group(1)
        return None

    @staticmethod
    def build_error_response(error_code: str) -> Optional[Dict]:
        """构建错误响应"""
        if error_code in ErrorSimulator.ERROR_CODES:
            error_info = ErrorSimulator.ERROR_CODES[error_code]
            return {
                "code": error_info["code"],
                "message": error_info["message"],
                "status": error_info["code"],
                "successResponse": False
            }
        return None
