"""
Enhanced Report Generator - Comprehensive HTML dashboard with all UI features
Based on praisonaibench-ui React application
"""

from typing import List, Dict, Any
from datetime import datetime
import json
import os


class EnhancedReportGenerator:
    """Generate comprehensive HTML reports with all UI features"""
    
    @staticmethod
    def generate(results: List[Dict[str, Any]], summary: Dict[str, Any], output_path: str = None) -> str:
        """Generate enhanced HTML report"""
        if not results:
            print("No results to generate report from")
            return None
        
        if not output_path:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_path = f"output/reports/enhanced_report_{timestamp}.html"
        
        # Ensure directory exists
        output_dir = os.path.dirname(output_path)
        if output_dir:
            os.makedirs(output_dir, exist_ok=True)
        else:
            output_path = f"output/reports/{output_path}"
            os.makedirs("output/reports", exist_ok=True)
        
        # Generate HTML content
        html_content = EnhancedReportGenerator._build_html(results, summary)
        
        # Write to file
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        print(f"📊 Enhanced report generated: {output_path}")
        return output_path
    
    @staticmethod
    def _build_html(results: List[Dict[str, Any]], summary: Dict[str, Any]) -> str:
        """Build complete HTML document"""
        
        # Calculate comprehensive statistics
        stats = EnhancedReportGenerator._calculate_stats(results, summary)
        
        # Generate sections
        css = EnhancedReportGenerator._generate_css()
        header_html = EnhancedReportGenerator._generate_header()
        nav_html = EnhancedReportGenerator._generate_navigation()
        summary_cards_html = EnhancedReportGenerator._generate_summary_cards(stats)
        leaderboard_html = EnhancedReportGenerator._generate_leaderboard(stats)
        charts_html = EnhancedReportGenerator._generate_charts(stats)
        comparison_table_html = EnhancedReportGenerator._generate_comparison_table(stats)
        detailed_results_html = EnhancedReportGenerator._generate_detailed_results(results)
        javascript = EnhancedReportGenerator._generate_javascript(stats)
        
        html = f'''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PraisonAI Bench - Enhanced Report</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>{css}</style>
</head>
<body>
    {header_html}
    {nav_html}
    
    <div class="container">
        <!-- Dashboard Tab -->
        <div id="dashboard" class="tab-content active">
            <h2 class="section-title">📊 Dashboard</h2>
            {summary_cards_html}
            {charts_html}
        </div>
        
        <!-- Leaderboard Tab -->
        <div id="leaderboard" class="tab-content">
            <h2 class="section-title">🏆 Leaderboard</h2>
            {leaderboard_html}
        </div>
        
        <!-- Comparison Tab -->
        <div id="comparison" class="tab-content">
            <h2 class="section-title">⚖️ Detailed Comparison</h2>
            {comparison_table_html}
        </div>
        
        <!-- Detailed Results Tab -->
        <div id="results" class="tab-content">
            <h2 class="section-title">📋 All Test Results</h2>
            {detailed_results_html}
        </div>
    </div>
    
    <footer>
        <p>Generated by PraisonAI Bench v0.0.12 | <a href="https://github.com/MervinPraison/praisonaibench" target="_blank">GitHub</a></p>
    </footer>
    
    <script>{javascript}</script>
</body>
</html>'''
        
        return html
    
    @staticmethod
    def _calculate_stats(results: List[Dict[str, Any]], summary: Dict[str, Any]) -> Dict[str, Any]:
        """Calculate comprehensive statistics"""
        
        # Group by model
        by_model = {}
        for r in results:
            model = r.get('model')
            if isinstance(model, dict):
                model_name = model.get('model', 'unknown')
            else:
                model_name = str(model) if model else 'unknown'
            
            if model_name not in by_model:
                by_model[model_name] = []
            by_model[model_name].append(r)
        
        # Calculate model statistics
        model_stats = []
        for model_name, model_results in by_model.items():
            total = len(model_results)
            success = sum(1 for r in model_results if r.get('status') == 'success')
            
            # Evaluation metrics
            with_eval = [r for r in model_results if r.get('evaluation')]
            passed = sum(1 for r in with_eval if r.get('evaluation', {}).get('passed'))
            
            func_scores = [r.get('evaluation', {}).get('functional', {}).get('score', 0) 
                          for r in with_eval]
            qual_scores = [r.get('evaluation', {}).get('quality', {}).get('quality_score', 0) 
                          for r in with_eval]
            overall_scores = [r.get('evaluation', {}).get('overall_score', 0) 
                            for r in with_eval]
            
            errors = sum(len(r.get('evaluation', {}).get('functional', {}).get('errors', [])) 
                        for r in with_eval)
            warnings = sum(len(r.get('evaluation', {}).get('functional', {}).get('warnings', [])) 
                          for r in with_eval)
            
            avg_time = sum(r.get('execution_time', 0) for r in model_results) / total if total > 0 else 0
            
            model_stats.append({
                'model': model_name,
                'total_tests': total,
                'success_count': success,
                'success_rate': (success / total * 100) if total > 0 else 0,
                'pass_count': passed,
                'pass_rate': (passed / len(with_eval) * 100) if with_eval else 0,
                'avg_functional': sum(func_scores) / len(func_scores) if func_scores else 0,
                'avg_quality': sum(qual_scores) / len(qual_scores) if qual_scores else 0,
                'avg_overall': sum(overall_scores) / len(overall_scores) if overall_scores else 0,
                'median_overall': sorted(overall_scores)[len(overall_scores)//2] if overall_scores else 0,
                'avg_time': avg_time,
                'total_errors': errors,
                'total_warnings': warnings,
                'tests_with_eval': len(with_eval)
            })
        
        # Sort by median overall score
        model_stats.sort(key=lambda x: x['median_overall'], reverse=True)
        
        return {
            'summary': summary,
            'results': results,
            'by_model': by_model,
            'model_stats': model_stats,
            'total_tests': len(results),
            'total_models': len(by_model),
            'success_count': sum(1 for r in results if r.get('status') == 'success'),
            'avg_time': sum(r.get('execution_time', 0) for r in results) / len(results) if results else 0
        }
    
    @staticmethod
    def _generate_css() -> str:
        """Generate comprehensive CSS"""
        return '''
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; color: #2c3e50; line-height: 1.6; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 2rem; text-align: center; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .header h1 { font-size: 2.5em; margin-bottom: 0.5rem; }
        .header p { opacity: 0.9; font-size: 1.1em; }
        
        /* Navigation */
        .nav-tabs { background: white; border-bottom: 2px solid #e5e7eb; display: flex; justify-content: center; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .nav-tab { padding: 1rem 2rem; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.3s; font-weight: 500; }
        .nav-tab:hover { background: #f9fafb; }
        .nav-tab.active { border-bottom-color: #667eea; color: #667eea; }
        
        /* Container */
        .container { max-width: 1400px; margin: 0 auto; padding: 2rem; }
        .section-title { font-size: 1.8em; margin-bottom: 1.5rem; color: #1f2937; }
        
        /* Tab Content */
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        
        /* Summary Cards */
        .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 1.5rem; margin-bottom: 2rem; }
        .summary-card { background: white; padding: 1.5rem; border-radius: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); transition: transform 0.2s; }
        .summary-card:hover { transform: translateY(-4px); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
        .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; }
        .card-icon { width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-center; font-size: 24px; }
        .card-title { font-size: 0.875rem; color: #6b7280; text-transform: uppercase; letter-spacing: 0.05em; }
        .card-value { font-size: 2rem; font-weight: bold; color: #1f2937; }
        
        /* Leaderboard */
        .leaderboard-criteria { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
        .criteria-btn { background: white; border: 2px solid #e5e7eb; padding: 1rem; border-radius: 8px; cursor: pointer; transition: all 0.3s; text-align: center; }
        .criteria-btn:hover { border-color: #667eea; }
        .criteria-btn.active { border-color: #667eea; background: #eef2ff; }
        .criteria-icon { font-size: 1.5rem; margin-bottom: 0.5rem; }
        .criteria-label { font-size: 0.875rem; font-weight: 600; color: #374151; }
        
        .leaderboard-list { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .leaderboard-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 1.5rem; }
        .leaderboard-item { display: flex; align-items: center; gap: 1.5rem; padding: 1.5rem; border-bottom: 1px solid #e5e7eb; transition: background 0.2s; }
        .leaderboard-item:hover { background: #f9fafb; }
        .leaderboard-item.top-3 { background: linear-gradient(90deg, rgba(255,215,0,0.1) 0%, rgba(255,255,255,0) 100%); }
        .rank-badge { width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 1.5rem; flex-shrink: 0; }
        .rank-1 { background: linear-gradient(135deg, #fbbf24, #f59e0b); color: white; }
        .rank-2 { background: linear-gradient(135deg, #e5e7eb, #9ca3af); color: white; }
        .rank-3 { background: linear-gradient(135deg, #fb923c, #f97316); color: white; }
        .rank-other { background: #f3f4f6; color: #6b7280; }
        .model-info { flex: 1; min-width: 0; }
        .model-name { font-size: 1.125rem; font-weight: 600; color: #1f2937; }
        .model-subtitle { font-size: 0.875rem; color: #6b7280; }
        .score-value { font-size: 2rem; font-weight: bold; color: #667eea; text-align: right; }
        .score-label { font-size: 0.75rem; color: #6b7280; text-align: right; }
        .quick-stats { display: flex; gap: 1.5rem; }
        .quick-stat { text-align: center; }
        .quick-stat-value { font-weight: 600; color: #1f2937; }
        .quick-stat-label { font-size: 0.75rem; color: #6b7280; }
        
        /* Charts */
        .charts-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); gap: 2rem; margin-bottom: 2rem; }
        .chart-container { background: white; padding: 2rem; border-radius: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .chart-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 1.5rem; color: #1f2937; }
        canvas { max-height: 300px !important; }
        
        /* Comparison Table */
        .comparison-table { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 2rem; }
        table { width: 100%; border-collapse: collapse; }
        thead { background: #1f2937; color: white; }
        th { padding: 1rem; text-align: left; font-weight: 600; }
        td { padding: 1rem; border-bottom: 1px solid #e5e7eb; }
        tbody tr:hover { background: #f9fafb; }
        .status-success { color: #10b981; font-weight: 600; }
        .status-error { color: #ef4444; font-weight: 600; }
        .badge { display: inline-block; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.875rem; font-weight: 600; }
        .badge-success { background: #d1fae5; color: #065f46; }
        .badge-warning { background: #fef3c7; color: #92400e; }
        .badge-error { background: #fee2e2; color: #991b1b; }
        
        /* Footer */
        footer { text-align: center; padding: 2rem; color: #6b7280; font-size: 0.875rem; background: white; margin-top: 3rem; }
        footer a { color: #667eea; text-decoration: none; }
        footer a:hover { text-decoration: underline; }
        
        /* Responsive */
        @media (max-width: 768px) {
            .charts-grid { grid-template-columns: 1fr; }
            .summary-grid { grid-template-columns: 1fr; }
            .quick-stats { display: none; }
        }
        '''
    
    @staticmethod
    def _generate_header() -> str:
        """Generate header section"""
        return f'''
        <div class="header">
            <h1>🚀 PraisonAI Bench</h1>
            <p>Enhanced Benchmark Report - Generated on {datetime.now().strftime("%B %d, %Y at %H:%M:%S")}</p>
        </div>
        '''
    
    @staticmethod
    def _generate_navigation() -> str:
        """Generate navigation tabs"""
        return '''
        <div class="nav-tabs">
            <div class="nav-tab active" onclick="switchTab('dashboard')">📊 Dashboard</div>
            <div class="nav-tab" onclick="switchTab('leaderboard')">🏆 Leaderboard</div>
            <div class="nav-tab" onclick="switchTab('comparison')">⚖️ Comparison</div>
            <div class="nav-tab" onclick="switchTab('results')">📋 Results</div>
        </div>
        '''
    
    @staticmethod
    def _generate_summary_cards(stats: Dict[str, Any]) -> str:
        """Generate summary cards section"""
        summary = stats['summary']
        cost_summary = summary.get('cost_summary', {})
        
        success_rate = (stats['success_count'] / stats['total_tests'] * 100) if stats['total_tests'] > 0 else 0
        
        cards = [
            {
                'title': 'Total Tests',
                'value': f"{stats['total_tests']}",
                'icon': '📝',
                'color': '#3b82f6'
            },
            {
                'title': 'Models',
                'value': f"{stats['total_models']}",
                'icon': '🤖',
                'color': '#8b5cf6'
            },
            {
                'title': 'Success Rate',
                'value': f"{success_rate:.1f}%",
                'icon': '✅',
                'color': '#10b981' if success_rate >= 80 else '#f59e0b'
            },
            {
                'title': 'Avg Time',
                'value': f"{stats['avg_time']:.1f}s",
                'icon': '⏱️',
                'color': '#6366f1'
            },
            {
                'title': 'Total Cost',
                'value': f"${cost_summary.get('total_cost_usd', 0):.4f}",
                'icon': '💰',
                'color': '#10b981'
            },
            {
                'title': 'Total Tokens',
                'value': f"{cost_summary.get('total_tokens', 0):,}",
                'icon': '🪙',
                'color': '#f59e0b'
            }
        ]
        
        html = '<div class="summary-grid">'
        for card in cards:
            html += f'''
            <div class="summary-card">
                <div class="card-header">
                    <span class="card-title">{card['title']}</span>
                    <div class="card-icon" style="background: {card['color']}20; color: {card['color']};">
                        {card['icon']}
                    </div>
                </div>
                <div class="card-value">{card['value']}</div>
            </div>
            '''
        html += '</div>'
        
        return html
    
    @staticmethod
    def _generate_leaderboard(stats: Dict[str, Any]) -> str:
        """Generate leaderboard section"""
        
        # Criteria buttons
        criteria = [
            ('overall', '🏆 Overall Score'),
            ('functional', '⚡ Functional'),
            ('quality', '⭐ Quality'),
            ('pass_rate', '✅ Pass Rate'),
            ('speed', '🚀 Speed')
        ]
        
        html = '<div class="leaderboard-criteria">'
        for key, label in criteria:
            active_class = 'active' if key == 'overall' else ''
            html += f'''
            <div class="criteria-btn {active_class}" onclick="rankBy('{key}')">
                <div class="criteria-icon">{label.split()[0]}</div>
                <div class="criteria-label">{' '.join(label.split()[1:])}</div>
            </div>
            '''
        html += '</div>'
        
        # Leaderboard list
        html += '''
        <div class="leaderboard-list">
            <div class="leaderboard-header">
                <h3 style="font-size: 1.5rem; margin-bottom: 0.5rem;">🏆 Model Rankings</h3>
                <p style="font-size: 0.875rem; opacity: 0.9;">Ranked by <span id="rank-criteria">Overall Score</span></p>
            </div>
            <div id="leaderboard-items">
        '''
        
        for i, model in enumerate(stats['model_stats'][:10]):  # Top 10
            rank = i + 1
            rank_class = f"rank-{rank}" if rank <= 3 else "rank-other"
            top_class = "top-3" if rank <= 3 else ""
            medal = "🏆" if rank <= 3 else str(rank)
            
            model_short = model['model'].split('/')[-1] if '/' in model['model'] else model['model']
            
            html += f'''
            <div class="leaderboard-item {top_class}">
                <div class="rank-badge {rank_class}">{medal}</div>
                <div class="model-info">
                    <div class="model-name">{model_short}</div>
                    <div class="model-subtitle">{model['total_tests']} tests</div>
                </div>
                <div>
                    <div class="score-value">{model['median_overall']:.0f}</div>
                    <div class="score-label">Score</div>
                </div>
                <div class="quick-stats">
                    <div class="quick-stat">
                        <div class="quick-stat-value">{model['avg_functional']:.0f}</div>
                        <div class="quick-stat-label">Functional</div>
                    </div>
                    <div class="quick-stat">
                        <div class="quick-stat-value">{model['avg_quality']:.1f}</div>
                        <div class="quick-stat-label">Quality</div>
                    </div>
                    <div class="quick-stat">
                        <div class="quick-stat-value">{model['pass_rate']:.0f}%</div>
                        <div class="quick-stat-label">Pass</div>
                    </div>
                    <div class="quick-stat">
                        <div class="quick-stat-value">{model['avg_time']:.1f}s</div>
                        <div class="quick-stat-label">Time</div>
                    </div>
                </div>
            </div>
            '''
        
        html += '</div></div>'
        
        return html
    
    @staticmethod
    def _generate_charts(stats: Dict[str, Any]) -> str:
        """Generate charts section"""
        html = '<div class="charts-grid">'
        
        # Chart containers
        charts = [
            ('statusChart', '📊 Status Distribution'),
            ('timeChart', '⏱️ Execution Time by Model'),
            ('scoreChart', '📈 Evaluation Scores'),
            ('errorChart', '⚠️ Errors & Warnings')
        ]
        
        for chart_id, title in charts:
            html += f'''
            <div class="chart-container">
                <h3 class="chart-title">{title}</h3>
                <canvas id="{chart_id}"></canvas>
            </div>
            '''
        
        html += '</div>'
        return html
    
    @staticmethod
    def _generate_comparison_table(stats: Dict[str, Any]) -> str:
        """Generate detailed comparison table"""
        html = '''
        <div class="comparison-table">
            <table>
                <thead>
                    <tr>
                        <th>Model</th>
                        <th>Tests</th>
                        <th>Overall</th>
                        <th>Functional</th>
                        <th>Quality</th>
                        <th>Pass Rate</th>
                        <th>Avg Time</th>
                        <th>Errors</th>
                        <th>Warnings</th>
                    </tr>
                </thead>
                <tbody>
        '''
        
        for model in stats['model_stats']:
            model_short = model['model'].split('/')[-1] if '/' in model['model'] else model['model']
            
            pass_badge_class = 'badge-success' if model['pass_rate'] >= 80 else 'badge-warning' if model['pass_rate'] >= 50 else 'badge-error'
            
            html += f'''
                <tr>
                    <td><strong>{model_short}</strong><br><small style="color: #6b7280;">{model['model']}</small></td>
                    <td>{model['total_tests']}</td>
                    <td style="font-size: 1.25rem; font-weight: bold; color: #667eea;">{model['median_overall']:.0f}</td>
                    <td style="color: #10b981; font-weight: 600;">{model['avg_functional']:.0f}</td>
                    <td style="color: #8b5cf6; font-weight: 600;">{model['avg_quality']:.1f}</td>
                    <td><span class="badge {pass_badge_class}">{model['pass_rate']:.0f}%</span></td>
                    <td>{model['avg_time']:.1f}s</td>
                    <td style="color: {'#ef4444' if model['total_errors'] > 0 else '#9ca3af'}; font-weight: 600;">{model['total_errors']}</td>
                    <td style="color: {'#f59e0b' if model['total_warnings'] > 0 else '#9ca3af'}; font-weight: 600;">{model['total_warnings']}</td>
                </tr>
            '''
        
        html += '''
                </tbody>
            </table>
        </div>
        '''
        
        return html
    
    @staticmethod
    def _generate_detailed_results(results: List[Dict[str, Any]]) -> str:
        """Generate detailed results table"""
        html = '''
        <div class="comparison-table">
            <table>
                <thead>
                    <tr>
                        <th>Test Name</th>
                        <th>Model</th>
                        <th>Status</th>
                        <th>Overall</th>
                        <th>Time</th>
                        <th>Tokens</th>
                        <th>Cost</th>
                    </tr>
                </thead>
                <tbody>
        '''
        
        for r in results:
            model = r.get('model')
            if isinstance(model, dict):
                model_name = model.get('model', 'unknown')
            else:
                model_name = str(model) if model else 'unknown'
            
            model_short = model_name.split('/')[-1] if '/' in model_name else model_name
            
            status = r.get('status', 'unknown')
            status_class = 'status-success' if status == 'success' else 'status-error'
            status_icon = '✅' if status == 'success' else '❌'
            
            overall_score = r.get('evaluation', {}).get('overall_score', '—')
            tokens = r.get('token_usage', {}).get('total_tokens', '—')
            cost = r.get('cost', {}).get('total_usd', 0)
            cost_str = f"${cost:.6f}" if cost else '—'
            
            html += f'''
                <tr>
                    <td><strong>{r.get('test_name', 'Unknown')}</strong></td>
                    <td>{model_short}</td>
                    <td class="{status_class}">{status_icon} {status.upper()}</td>
                    <td style="font-weight: 600;">{overall_score}</td>
                    <td>{r.get('execution_time', 0):.2f}s</td>
                    <td>{tokens}</td>
                    <td>{cost_str}</td>
                </tr>
            '''
        
        html += '''
                </tbody>
            </table>
        </div>
        '''
        
        return html
    
    @staticmethod
    def _generate_javascript(stats: Dict[str, Any]) -> str:
        """Generate JavaScript for interactivity and charts"""
        
        # Prepare data for charts
        model_labels = [m['model'].split('/')[-1] if '/' in m['model'] else m['model'] for m in stats['model_stats'][:10]]
        overall_scores = [m['median_overall'] for m in stats['model_stats'][:10]]
        functional_scores = [m['avg_functional'] for m in stats['model_stats'][:10]]
        quality_scores = [m['avg_quality'] for m in stats['model_stats'][:10]]
        exec_times = [m['avg_time'] for m in stats['model_stats'][:10]]
        errors_data = [m['total_errors'] for m in stats['model_stats'][:10]]
        warnings_data = [m['total_warnings'] for m in stats['model_stats'][:10]]
        
        success_count = stats['success_count']
        failed_count = stats['total_tests'] - success_count
        
        return f'''
        // Tab switching
        function switchTab(tabName) {{
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {{
                tab.classList.remove('active');
            }});
            document.querySelectorAll('.nav-tab').forEach(tab => {{
                tab.classList.remove('active');
            }});
            
            // Show selected tab
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');
        }}
        
        // Leaderboard ranking
        function rankBy(criteria) {{
            document.querySelectorAll('.criteria-btn').forEach(btn => {{
                btn.classList.remove('active');
            }});
            event.target.closest('.criteria-btn').classList.add('active');
            
            const labels = {{
                'overall': 'Overall Score',
                'functional': 'Functional Score',
                'quality': 'Quality Score',
                'pass_rate': 'Pass Rate',
                'speed': 'Speed (Fastest)'
            }};
            document.getElementById('rank-criteria').textContent = labels[criteria];
        }}
        
        // Status Chart
        new Chart(document.getElementById('statusChart'), {{
            type: 'doughnut',
            data: {{
                labels: ['Success', 'Failed'],
                datasets: [{{
                    data: [{success_count}, {failed_count}],
                    backgroundColor: ['#10b981', '#ef4444'],
                    borderWidth: 0
                }}]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: true,
                plugins: {{
                    legend: {{ position: 'bottom' }}
                }}
            }}
        }});
        
        // Execution Time Chart
        new Chart(document.getElementById('timeChart'), {{
            type: 'bar',
            data: {{
                labels: {json.dumps(model_labels)},
                datasets: [{{
                    label: 'Execution Time (s)',
                    data: {json.dumps(exec_times)},
                    backgroundColor: '#667eea',
                    borderRadius: 8
                }}]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: true,
                scales: {{ y: {{ beginAtZero: true }} }},
                plugins: {{ legend: {{ display: false }} }}
            }}
        }});
        
        // Evaluation Scores Chart
        new Chart(document.getElementById('scoreChart'), {{
            type: 'radar',
            data: {{
                labels: {json.dumps(model_labels)},
                datasets: [
                    {{
                        label: 'Overall Score',
                        data: {json.dumps(overall_scores)},
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.2)',
                        pointBackgroundColor: '#667eea'
                    }},
                    {{
                        label: 'Functional',
                        data: {json.dumps(functional_scores)},
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.2)',
                        pointBackgroundColor: '#10b981'
                    }},
                    {{
                        label: 'Quality',
                        data: {json.dumps(quality_scores)},
                        borderColor: '#8b5cf6',
                        backgroundColor: 'rgba(139, 92, 246, 0.2)',
                        pointBackgroundColor: '#8b5cf6'
                    }}
                ]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: true,
                scales: {{
                    r: {{
                        beginAtZero: true,
                        max: 100
                    }}
                }}
            }}
        }});
        
        // Errors & Warnings Chart
        new Chart(document.getElementById('errorChart'), {{
            type: 'bar',
            data: {{
                labels: {json.dumps(model_labels)},
                datasets: [
                    {{
                        label: 'Errors',
                        data: {json.dumps(errors_data)},
                        backgroundColor: '#ef4444',
                        borderRadius: 8
                    }},
                    {{
                        label: 'Warnings',
                        data: {json.dumps(warnings_data)},
                        backgroundColor: '#f59e0b',
                        borderRadius: 8
                    }}
                ]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: true,
                scales: {{ y: {{ beginAtZero: true }} }}
            }}
        }});
        '''
