import random
import logging
from typing import Dict, Any
from plugins import CountermeasurePlugin

# 配置日志
logger = logging.getLogger(__name__)

class RandomErrorCountermeasure(CountermeasurePlugin):
    """
    随机返回HTTP错误码的反制动作实现
    """

    def execute(self, context: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行随机错误码返回动作。
        :param context: 包含 'config' 键的字典，'config' 中可包含 'error_codes' 列表。
                          默认值: [400, 401, 403, 404, 500, 502, 503]。
        :return: 包含执行结果的字典。
        """
        config = context.get('config', {})
        error_codes = config.get('error_codes', [400, 401, 403, 404, 500, 502, 503])
        
        if not error_codes:
            logger.warning("No error codes provided in config, using default list.")
            error_codes = [400, 401, 403, 404, 500, 502, 503]
            
        selected_error = random.choice(error_codes)
        logger.info(f"Simulated returning random error code: {selected_error}")
        return {'error_code_applied': selected_error}

    def get_description(self) -> str:
        return "Randomly returns an HTTP error code (40x/50x) to the client."