"""
enhanced_report_generator.py

Enhanced report generation utilities
"""

import pandas as pd
import numpy as np
from typing import Dict, Any, Optional
from datetime import datetime


class EnhancedReportGenerator:
    """Enhanced report generator with additional features"""

    def generate_enhanced_report(
        self,
        optimization_data: Dict[str, Any],
        plots_data: Optional[Dict[str, str]] = None,
        format: str = "html",
    ) -> str:
        """Generate an enhanced optimization report"""
        try:
            # Extract key information
            n_experiments = optimization_data.get("n_experiments", 0)
            status = optimization_data.get("status", "Unknown")
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            # Generate HTML report
            if format == "html":
                return self._generate_html_report(
                    optimization_data, plots_data, timestamp
                )
            else:
                return self._generate_markdown_report(optimization_data, timestamp)

        except Exception as e:
            return f"<html><body><h1>Report Generation Failed</h1><p>Error: {str(e)}</p></body></html>"

    def _generate_html_report(
        self, data: Dict[str, Any], plots: Optional[Dict[str, str]], timestamp: str
    ) -> str:
        """Generate HTML format report"""

        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Enhanced Optimization Report</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; }}
        .header {{ background-color: #f0f0f0; padding: 20px; border-radius: 5px; }}
        .section {{ margin: 20px 0; }}
        .plot {{ margin: 10px 0; text-align: center; }}
        table {{ border-collapse: collapse; width: 100%; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        th {{ background-color: #f2f2f2; }}
    </style>
</head>
<body>
    <div class="header">
        <h1>Multi-Objective Optimization Report</h1>
        <p><strong>Generated:</strong> {timestamp}</p>
        <p><strong>Status:</strong> {data.get('status', 'N/A')}</p>
        <p><strong>Experiments:</strong> {data.get('n_experiments', 'N/A')}</p>
    </div>
    
    <div class="section">
        <h2>Summary</h2>
        <p>{data.get('summary', 'No summary available')}</p>
    </div>
    
    <div class="section">
        <h2>Data Quality</h2>
        <table>
            <tr><th>Metric</th><th>Value</th></tr>
            <tr><td>Validation Status</td><td>{data.get('validation_status', 'N/A')}</td></tr>
            <tr><td>Data Completeness</td><td>{data.get('completeness', 'N/A')}</td></tr>
            <tr><td>Quality Score</td><td>{data.get('data_quality', 'N/A')}</td></tr>
        </table>
    </div>
"""

        # Add plots if available
        if plots:
            html_content += """
    <div class="section">
        <h2>Optimization Plots</h2>
"""
            for plot_name, plot_base64 in plots.items():
                if plot_base64:
                    html_content += f"""
        <div class="plot">
            <h3>{plot_name.replace('_', ' ').title()}</h3>
            <img src="data:image/png;base64,{plot_base64}" alt="{plot_name}" style="max-width: 100%; height: auto;">
        </div>
"""
            html_content += "    </div>"

        html_content += """
    
    <div class="section">
        <h2>System Information</h2>
        <p>Generated by Multi-Objective Optimization Laboratory v3.1.4</p>
        <p>Enhanced with Acquisition Function Heatmap Visualization</p>
    </div>
    
</body>
</html>"""

        return html_content

    def _generate_markdown_report(self, data: Dict[str, Any], timestamp: str) -> str:
        """Generate Markdown format report"""
        return f"""# Enhanced Optimization Report

**Generated:** {timestamp}  
**Status:** {data.get('status', 'N/A')}  
**Experiments:** {data.get('n_experiments', 'N/A')}

## Summary
{data.get('summary', 'No summary available')}

## Data Quality
- **Validation Status:** {data.get('validation_status', 'N/A')}
- **Data Completeness:** {data.get('completeness', 'N/A')}
- **Quality Score:** {data.get('data_quality', 'N/A')}

---
*Generated by Multi-Objective Optimization Laboratory v3.1.4*
"""


# Create global instance
enhanced_report_generator = EnhancedReportGenerator()
