import re
import logging
from typing import Dict, Any
from plugins import CountermeasurePlugin
from core.log_utils import sanitize_for_log

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class InjectContentCountermeasure(CountermeasurePlugin):
    """
    在响应内容中注入HTML或JS代码的反制动作实现
    """

    def execute(self, context: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行内容注入动作。
        注意：这个插件的设计是让规则引擎在需要时调用它，
        并将注入的代码通过 context 传给它。
        实际的注入逻辑需要在 HTTP 服务器层面实现，
        这个 execute 方法主要用于记录和返回结果。
        """
        config = context.get('config', {})
        inject_location = config.get('location', 'before_body_end') # before_body_end, head, body_start
        content_to_inject = config.get('content', '')
        
        if not content_to_inject:
            logger.warning("No content specified to inject.")
            return {'success': False, 'message': 'No content specified to inject.'}

        preview = sanitize_for_log(content_to_inject[:200])
        safe_location = sanitize_for_log(inject_location)
        logger.info(f"Prepared to inject content at '{safe_location}': {preview}...")
        
        # 这个插件本身不修改 context，而是返回需要注入的信息
        # 实际的注入将在 api/server.py 的响应处理逻辑中完成
        return {
            'success': True, 
            'message': 'Content injection prepared.',
            'inject_info': {
                'location': inject_location,
                'content': content_to_inject
            }
        }

    def get_description(self) -> str:
        return "Prepares HTML/JS content to be injected into the HTTP response body."