import json
from dataclasses import dataclass
from typing import Any
from app.analysis_models import RobustnessMatrix

REPORT_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RiskLab Report</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { background-color: #0f172a; color: #e2e8f0; }
        .card { background-color: #1e293b; border-radius: 0.5rem; padding: 1.5rem; }
    </style>
</head>
<body class="font-sans antialiased">
    <div class="container mx-auto px-4 py-8">
        <header class="flex justify-between items-center mb-8">
            <h1 class="text-3xl font-bold text-blue-400 tracking-tight">RiskLab <span class="text-gray-500 text-lg font-normal">| Robustness Report</span></h1>
            <div id="scoreBadge" class="bg-gray-700 text-gray-300 text-sm px-3 py-2 rounded font-mono">
                Agg. Score: <span id="aggScore">--</span>
            </div>
        </header>

        <!-- Main Grid -->
        <div class="grid grid-cols-1 md:grid-cols-1 gap-6">
            
            <!-- Robustness Matrix -->
            <div class="card">
                <h2 class="text-xl font-semibold mb-4 text-gray-100">Robustness Matrix</h2>
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="text-gray-400 border-b border-gray-700">
                                <th class="py-3">Scenario</th>
                                <th class="py-3">Robustness Score</th>
                                <th class="py-3">Max Drawdown</th>
                                <th class="py-3">Sharpe Ratio</th>
                            </tr>
                        </thead>
                        <tbody id="resultsBody" class="divide-y divide-gray-700">
                            <!-- JS will populate -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Charts Area -->
        <div class="mt-8 grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="card h-80">
                <h3 class="text-gray-400 mb-2 font-semibold">Scenario Scores</h3>
                <div class="relative h-full w-full p-2">
                    <canvas id="scoreChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Data Injection
        const matrix = {{DATA_JSON}};

        document.addEventListener('DOMContentLoaded', () => {
            renderTable(matrix);
            renderChart(matrix);
            
            document.getElementById('aggScore').innerText = matrix.aggregate_score.toFixed(1);
            const badge = document.getElementById('scoreBadge');
            
            if(matrix.aggregate_score > 40) {
                 badge.classList.remove('bg-gray-700');
                 badge.classList.add('bg-green-900', 'text-green-300');
            } else {
                 badge.classList.remove('bg-gray-700');
                 badge.classList.add('bg-red-900', 'text-red-300');
            }
        });

        function renderTable(matrix) {
            const tbody = document.getElementById('resultsBody');
            tbody.innerHTML = '';
            
            matrix.scenario_results.forEach(res => {
                const tr = document.createElement('tr');
                const scoreColor = res.robustness_score < 30 ? 'text-red-400' : 'text-green-400';
                
                tr.innerHTML = `
                    <td class="py-3 font-medium text-gray-200">${res.scenario_name}</td>
                    <td class="py-3 ${scoreColor} font-bold">${res.robustness_score.toFixed(1)}</td>
                    <td class="py-3 text-red-300">${(res.max_drawdown * 100).toFixed(1)}%</td>
                    <td class="py-3 text-blue-300">${res.sharpe_ratio.toFixed(2)}</td>
                `;
                tbody.appendChild(tr);
            });
        }

        function renderChart(matrix) {
            const ctx = document.getElementById('scoreChart').getContext('2d');
            const labels = matrix.scenario_results.map(r => r.scenario_name);
            const data = matrix.scenario_results.map(r => r.robustness_score);
            const colors = data.map(v => v < 30 ? 'rgba(239, 68, 68, 0.7)' : 'rgba(34, 197, 94, 0.7)');

            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Robustness Score',
                        data: data,
                        backgroundColor: colors,
                        borderColor: colors.map(c => c.replace('0.7', '1')),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            grid: { color: '#334155' },
                            ticks: { color: '#94a3b8' }
                        },
                        x: {
                            grid: { display: false },
                            ticks: { color: '#94a3b8' }
                        }
                    },
                    plugins: {
                        legend: { display: false }
                    }
                }
            });
        }
    </script>
</body>
</html>
"""

class RiskReport:
    def __init__(self, matrix: RobustnessMatrix):
        self.matrix = matrix

    def to_file(self, filename: str) -> None:
        """
        Generates the HTML report and writes it to the specified file.
        """
        # Convert Pydantic model to dict, then JSON
        json_data = json.dumps(self.matrix.model_dump(mode='json'))
        
        # Inject into template
        html_content = REPORT_TEMPLATE.replace("{{DATA_JSON}}", json_data)
        
        with open(filename, 'w') as f:
            f.write(html_content)
        
        print(f"Report saved to {filename}")
