import os
from datetime import datetime
from typing import Dict, Any, List, Optional
import json
from jinja2 import Environment, FileSystemLoader

class SimpleReporter:
    """简单的文本报告生成器（原有）"""
    def generate(self, original_info: dict, mechanism, search_results: dict) -> str:
        lines = []
        lines.append("Privacy Tuner 运行报告")
        lines.append("=" * 40)
        lines.append(f"原始数据信息: {original_info}")
        lines.append(f"使用的隐私机制: {mechanism.__class__.__name__}")
        lines.append(f"最优参数: {search_results['best_params']}")
        lines.append(f"最优效用: {search_results['best_utility']:.4f}")
        lines.append(f"对应风险: {search_results['best_risk']:.4f}")
        return "\n".join(lines)

class HTMLReporter:
    """生成 HTML 格式的报告，可包含图表"""
    def __init__(self, template_dir: Optional[str] = None):
        if template_dir is None:
            # 默认模板目录为当前文件所在目录下的 templates
            base = os.path.dirname(__file__)
            template_dir = os.path.join(base, 'templates')
        self.env = Environment(loader=FileSystemLoader(template_dir))
        self.template = self.env.get_template('report_template.html')

    def generate(self,
                 original_info: Dict[str, Any],
                 mechanism,
                 param_space: Dict[str, Any],
                 risk_constraint: tuple,
                 all_results: List[Dict[str, Any]],
                 best_params: Dict[str, Any],
                 best_utility: float,
                 best_risk: float,
                 scatter_plot_path: Optional[str] = None,
                 sensitivity_plots: Optional[List[Dict]] = None,
                 output_path: str = 'report.html') -> str:
        """
        生成 HTML 报告并保存到 output_path。
        返回报告的完整路径。
        """
        # 准备模板数据
        data = {
            'generation_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'original_info': original_info,
            'mechanism_name': mechanism.__class__.__name__,
            'param_space': param_space,  # 直接传递字典，不序列化
            'risk_constraint': risk_constraint,
            'best_params': best_params,
            'best_utility': f"{best_utility:.4f}",
            'best_risk': f"{best_risk:.4f}",
            'scatter_plot_path': scatter_plot_path,
            'sensitivity_plots': sensitivity_plots or [],
            'all_results': all_results
        }

        html_content = self.template.render(data)

        # 确保输出目录存在
        os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)

        return output_path