import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..')))

from myffe.core.master_judge import evaluate_dataset, print_evaluation_result
from myffe.tools.color_printer import ColorPrinter

def with_evaluation(func):
    """
    用于预处理模块的装饰器，在处理前后评估数据集并比较得分变化
    
    Args:
        func: 预处理模块的__call__方法
    
    Returns:
        包装后的__call__方法
    """
    def wrapper(self, data, *args, **kwargs):
        # 保存原始数据的副本用于对比
        original_data = data.copy()
        
        # 处理前评估
        ColorPrinter.print_info("=" * 80)
        ColorPrinter.print_info("处理前数据集评估")
        ColorPrinter.print_info("=" * 80)
        # 尝试获取data_label参数
        data_label = None
        if len(args) > 0:
            data_label = args[0]
        pre_evaluation = evaluate_dataset(original_data, label_column=data_label)
        print_evaluation_result(pre_evaluation)
        
        # 执行原始处理方法
        # 根据函数签名调用
        import inspect
        sig = inspect.signature(func)
        params = list(sig.parameters.keys())
        
        # 构建参数字典
        call_args = {'self': self, 'data': data}
        
        # 处理额外参数
        param_names = params[2:]  # 跳过 self 和 data
        for i, param_name in enumerate(param_names):
            if i < len(args):
                call_args[param_name] = args[i]
            elif param_name in kwargs:
                call_args[param_name] = kwargs[param_name]
        
        # 调用原始函数
        result = func(**call_args)
        
        # 处理后评估
        ColorPrinter.print_info("=" * 80)
        ColorPrinter.print_info("处理后数据集评估")
        ColorPrinter.print_info("=" * 80)
        post_evaluation = evaluate_dataset(result, original_data, data_label)
        print_evaluation_result(post_evaluation)
        
        # 计算得分变化
        score_change = post_evaluation['total_score'] - pre_evaluation['total_score']
        ColorPrinter.print_info("=" * 80)
        ColorPrinter.print_info(f"得分变化: {score_change:.2f}")
        
        # 如果得分变化为0，提示可能没有正确处理
        if score_change == 0:
            ColorPrinter.print_warning("警告: 得分变化为0，可能没有正确处理数据！")
        elif score_change < 0:
            ColorPrinter.print_warning(f"警告: 得分下降了 {abs(score_change):.2f}，处理可能不理想！")
        else:
            ColorPrinter.print_success(f"成功: 得分提升了 {score_change:.2f}！")
        ColorPrinter.print_info("=" * 80)
        
        return result
    
    return wrapper
