"""Generate HTML benchmark report from results JSON.

Produces a standalone HTML file with Chart.js bar charts comparing
baseline vs turbo performance across all scenarios.
"""

from __future__ import annotations

import html
import json
from pathlib import Path
from typing import Any


def generate_html_report(results: list[dict[str, Any]], output_path: str) -> str:
    """Generate an HTML benchmark report with Chart.js charts.

    Args:
        results: List of scenario result dicts from the benchmark runner.
        output_path: Path for the output HTML file.

    Returns:
        The output file path.
    """
    labels = json.dumps([r["name"] for r in results])
    baseline_data = json.dumps([r["baseline_ms"] for r in results])
    turbo_data = json.dumps([r["turbo_ms"] for r in results])
    speedup_data = json.dumps([r["speedup"] for r in results])

    table_rows = ""
    for r in results:
        table_rows += f"""<tr>
            <td>{html.escape(r["name"])}</td>
            <td>{html.escape(r["description"])}</td>
            <td>{r["iterations"]:,}</td>
            <td>{r["baseline_ms"]:,.1f}</td>
            <td>{r["turbo_ms"]:,.1f}</td>
            <td><strong>{r["speedup"]:.2f}x</strong></td>
            <td>{r["saved_per_query_us"]:.1f}</td>
        </tr>\n"""

    html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>QueryTurbo Benchmark Results</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {{ font-family: -apple-system, sans-serif; background: #1a1b2e; color: #e8e8f0; padding: 2rem; }}
        h1 {{ color: #8b9bf0; text-align: center; }}
        table {{ width: 100%; border-collapse: collapse; margin: 2rem 0; background: #2a2b45; border-radius: 8px; overflow: hidden; }}
        th {{ background: #252640; padding: 0.75rem; text-align: left; color: #a0a0b8; font-size: 0.85rem; text-transform: uppercase; }}
        td {{ padding: 0.75rem; border-top: 1px solid #383860; }}
        .chart-container {{ background: #2a2b45; border-radius: 8px; padding: 1.5rem; margin: 1.5rem 0; max-width: 800px; margin-left: auto; margin-right: auto; }}
        .footer {{ text-align: center; color: #a0a0b8; margin-top: 2rem; font-size: 0.85rem; }}
    </style>
</head>
<body>
    <h1>QueryTurbo Benchmark Results</h1>
    <p style="text-align:center;color:#a0a0b8;">django-query-doctor v2.0 &mdash; SQL Compilation Cache Performance</p>

    <table>
        <thead>
            <tr>
                <th>Scenario</th>
                <th>Description</th>
                <th>Iterations</th>
                <th>Baseline (ms)</th>
                <th>Turbo (ms)</th>
                <th>Speedup</th>
                <th>Saved/Query (&mu;s)</th>
            </tr>
        </thead>
        <tbody>
            {table_rows}
        </tbody>
    </table>

    <div class="chart-container">
        <canvas id="comparisonChart" height="300"></canvas>
    </div>

    <div class="chart-container">
        <canvas id="speedupChart" height="250"></canvas>
    </div>

    <div class="footer">Generated by django-query-doctor benchmark suite</div>

    <script>
    Chart.defaults.color = '#a0a0b8';
    Chart.defaults.borderColor = 'rgba(56, 56, 96, 0.5)';

    new Chart(document.getElementById('comparisonChart'), {{
        type: 'bar',
        data: {{
            labels: {labels},
            datasets: [
                {{ label: 'Baseline (ms)', data: {baseline_data}, backgroundColor: '#e85050', borderRadius: 4 }},
                {{ label: 'Turbo (ms)', data: {turbo_data}, backgroundColor: '#4caf88', borderRadius: 4 }},
            ],
        }},
        options: {{
            responsive: true,
            plugins: {{ title: {{ display: true, text: 'Baseline vs Turbo (lower is better)' }} }},
            scales: {{ y: {{ beginAtZero: true, title: {{ display: true, text: 'Time (ms)' }} }} }},
        }},
    }});

    new Chart(document.getElementById('speedupChart'), {{
        type: 'bar',
        data: {{
            labels: {labels},
            datasets: [{{ label: 'Speedup Factor', data: {speedup_data}, backgroundColor: '#6c7ce8', borderRadius: 4 }}],
        }},
        options: {{
            responsive: true,
            plugins: {{ title: {{ display: true, text: 'Speedup Factor (higher is better)' }} }},
            scales: {{ y: {{ beginAtZero: true, title: {{ display: true, text: 'Speedup (x)' }} }} }},
        }},
    }});
    </script>
</body>
</html>"""

    Path(output_path).write_text(html_content, encoding="utf-8")
    return output_path
