from enum import Enum
from typing import Dict, Any, Union, Optional

class ErrorCode(Enum):
    '''错误码枚举'''

    # status code
    SUCCESS                 = '000'
    FAIL                    = '001'

    # command error
    INVALID_COMMAND         = '010'
    INVALID_FORMAT          = '012'

    # config error
    EMPTY_CONFIG            = '020'

    # File error
    FILE_NOT_FOUND_ERROR    = '030'

    # module error
    IMPORT_ERROR            = '040'

    # network error
    NETWORK_ERROR           = '050'

    # timeout error
    TIMEOUT_ERROR           = '100'

    # yaml error
    YAML_PARSE_ERROR        = '402'

    @classmethod
    def get_all_codes(cls):
        return [code.value for code in cls]

class ErrorMessages:
    '''错误消息枚举'''
    _MESSAGES = {
        ErrorCode.SUCCESS: 'success',
        ErrorCode.FAIL: 'fail',
        ErrorCode.INVALID_COMMAND: 'invalid command',
        ErrorCode.EMPTY_CONFIG: 'empty config',
        ErrorCode.INVALID_FORMAT: 'invalid format',
        ErrorCode.FILE_NOT_FOUND_ERROR: 'file not found',
        ErrorCode.IMPORT_ERROR: 'import error',
        ErrorCode.NETWORK_ERROR: 'network error',
        ErrorCode.TIMEOUT_ERROR: 'timeout error',
        ErrorCode.YAML_PARSE_ERROR: 'yaml parse error',
    }

    @classmethod
    def get_message(cls, err_code: Union[ErrorCode, str]) -> str:
        if isinstance(err_code, str):
            try:
                error_code = ErrorCode(err_code)
            except ValueError:
                return f'unknown error code: {err_code}'
                
        return cls._MESSAGES.get(error_code, f'unknown error code: {err_code}')

SUCCESS = ErrorCode.SUCCESS.value
FAIL = ErrorCode.FAIL.value
INVALID_COMMAND = ErrorCode.INVALID_COMMAND.value
INVALID_FORMAT = ErrorCode.INVALID_FORMAT.value
EMPTY_CONFIG = ErrorCode.EMPTY_CONFIG.value
FILE_NOT_FOUND_ERROR = ErrorCode.FILE_NOT_FOUND_ERROR.value
IMPORT_ERROR = ErrorCode.IMPORT_ERROR.value
NETWORK_ERROR = ErrorCode.NETWORK_ERROR.value
TIMEOUT_ERROR = ErrorCode.TIMEOUT_ERROR.value
YAML_PARSE_ERROR = ErrorCode.YAML_PARSE_ERROR.value

def is_error(data: Any) -> bool:
    '''
    判断数据是否为错误码
    : param data: 待判断数据
    : return: True表示错误码，False表示正常码
    '''
    if not isinstance(data, str):
        return False

    if len(data) == 3 and data.isdigit():
        return data in [ c.value for c in ErrorCode if c != ErrorCode.SUCCESS]
    return False