"""
Enterprise Report Generator - Level 2.5

Features:
- Schema summary with version info
- Drift statistics across files
- Per-column anomalies  
- File-to-file comparisons
- Column lineage visualization
- Transformation DAG
"""

from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Any
import json

HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DataShaper AI - Enterprise Report</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
        
        * { font-family: 'Inter', sans-serif; }
        
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
        }
        
        .badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .badge-success { background: #10b981; color: white; }
        .badge-warning { background: #f59e0b; color: white; }
        .badge-error { background: #ef4444; color: white; }
        .badge-info { background: #3b82f6; color: white; }
        
        table { width: 100%; border-collapse: collapse; }
        th { background: #f3f4f6; font-weight: 600; text-align: left; padding: 0.75rem; }
        td { padding: 0.75rem; border-bottom: 1px solid #e5e7eb; }
        
        .progress-bar {
            background: #e5e7eb;
            border-radius: 9999px;
            height: 8px;
            overflow: hidden;
        }
        
        .progress-fill {
            background: linear-gradient(90deg, #10b981 0%, #059669 100%);
            height: 100%;
            transition: width 0.3s ease;
        }
        
        .lineage-node {
            background: #f3f4f6;
            border: 2px solid #667eea;
            border-radius: 8px;
            padding: 0.5rem 1rem;
            display: inline-block;
            margin: 0.25rem;
        }
        
        .dag-node {
            background: white;
            border: 2px solid #667eea;
            border-radius: 12px;
            padding: 1rem;
            margin: 0.5rem;
            display: inline-block;
        }
        
        .arrow { color: #667eea; font-size: 1.5em; margin: 0 0.5rem; }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Header -->
    <div class="gradient-bg text-white py-12 px-6">
        <div class="max-w-7xl mx-auto">
            <h1 class="text-5xl font-bold mb-2">✨ DataShaper AI</h1>
            <p class="text-xl opacity-90">Enterprise Data Healing Report</p>
            <p class="text-sm opacity-75 mt-2">Generated {{ timestamp }}</p>
        </div>
    </div>
    
    <!-- Executive Summary -->
    <div class="max-w-7xl mx-auto px-6 py-8">
        <h2 class="text-3xl font-bold mb-6">📊 Executive Summary</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="stat-card">
                <div class="text-4xl font-bold">{{ metrics.files_processed }}</div>
                <div class="text-sm opacity-90 mt-1">Files Processed</div>
            </div>
            <div class="stat-card">
                <div class="text-4xl font-bold">{{ metrics.issues_found }}</div>
                <div class="text-sm opacity-90 mt-1">Issues Detected</div>
            </div>
            <div class="stat-card">
                <div class="text-4xl font-bold">{{ metrics.fixes_applied }}</div>
                <div class="text-sm opacity-90 mt-1">Fixes Applied</div>
            </div>
            <div class="stat-card">
                <div class="text-4xl font-bold">{{ metrics.quality_score }}%</div>
                <div class="text-sm opacity-90 mt-1">Quality Score</div>
            </div>
        </div>
        
        <!-- Schema Summary -->
        {% if schema_summary %}
        <div class="card p-6 mb-8">
            <h3 class="text-2xl font-bold mb-4">📋 Schema Summary</h3>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <p class="text-gray-600 text-sm">Schema Name</p>
                    <p class="font-semibold">{{ schema_summary.name }}</p>
                </div>
                <div>
                    <p class="text-gray-600 text-sm">Version</p>
                    <p class="font-semibold">{{ schema_summary.version }}</p>
                </div>
                <div>
                    <p class="text-gray-600 text-sm">Total Columns</p>
                    <p class="font-semibold">{{ schema_summary.column_count }}</p>
                </div>
                <div>
                    <p class="text-gray-600 text-sm">Schema Changes</p>
                    <p class="font-semibold">
                        <span class="badge badge-success">+{{ schema_summary.columns_added|length }}</span>
                        <span class="badge badge-error">-{{ schema_summary.columns_removed|length }}</span>
                    </p>
                </div>
            </div>
            
            {% if schema_summary.columns_added %}
            <div class="mt-4">
                <p class="text-sm font-semibold text-gray-700 mb-2">Columns Added:</p>
                <div class="flex flex-wrap gap-2">
                    {% for col in schema_summary.columns_added %}
                    <span class="badge badge-success">{{ col }}</span>
                    {% endfor %}
                </div>
            </div>
            {% endif %}
        </div>
        {% endif %}
        
        <!-- Drift Statistics -->
        {% if drift_stats %}
        <div class="card p-6 mb-8">
            <h3 class="text-2xl font-bold mb-4">📈 Drift Statistics</h3>
            <div class="space-y-4">
                <div>
                    <div class="flex justify-between mb-1">
                        <span class="text-sm font-medium">Schema Alignment</span>
                        <span class="text-sm font-semibold">{{ drift_stats.alignment_score }}%</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: {{ drift_stats.alignment_score }}%"></div>
                    </div>
                </div>
                
                <div class="grid grid-cols-3 gap-4 mt-6">
                    <div class="text-center">
                        <div class="text-3xl font-bold text-blue-600">{{ drift_stats.type_drifts }}</div>
                        <div class="text-sm text-gray-600">Type Drifts</div>
                    </div>
                    <div class="text-center">
                        <div class="text-3xl font-bold text-orange-600">{{ drift_stats.missing_columns }}</div>
                        <div class="text-sm text-gray-600">Missing Columns</div>
                    </div>
                    <div class="text-center">
                        <div class="text-3xl font-bold text-green-600">{{ drift_stats.resolved }}</div>
                        <div class="text-sm text-gray-600">Resolved</div>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}
        
        <!-- Per-Column Anomalies -->
        {% if column_anomalies %}
        <div class="card p-6 mb-8">
            <h3 class="text-2xl font-bold mb-4">🔍 Per-Column Analysis</h3>
            <table class="w-full">
                <thead>
                    <tr>
                        <th>Column</th>
                        <th>Type</th>
                        <th>Null %</th>
                        <th>Unique</th>
                        <th>Anomalies</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    {% for col in column_anomalies %}
                    <tr>
                        <td class="font-semibold">{{ col.name }}</td>
                        <td><span class="badge badge-info">{{ col.type }}</span></td>
                        <td>{{ col.null_pct }}%</td>
                        <td>{{ col.unique_count }}</td>
                        <td>
                            {% for anomaly in col.anomalies %}
                            <span class="badge badge-warning">{{ anomaly }}</span>
                            {% endfor %}
                        </td>
                        <td>
                            {% if col.fixed %}
                            <span class="badge badge-success">✓ Fixed</span>
                            {% else %}
                            <span class="badge badge-warning">⚠ Flagged</span>
                            {% endif %}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% endif %}
        
        <!-- File-to-File Comparison -->
        {% if file_comparison %}
        <div class="card p-6 mb-8">
            <h3 class="text-2xl font-bold mb-4">📂 File-to-File Comparison</h3>
            <div class="overflow-x-auto">
                <table>
                    <thead>
                        <tr>
                            <th>File</th>
                            <th>Rows</th>
                            <th>Columns</th>
                            <th>Issues</th>
                            <th>Fixes</th>
                            <th>Quality</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for file in file_comparison %}
                        <tr>
                            <td class="font-semibold">{{ file.name }}</td>
                            <td>{{ file.rows }}</td>
                            <td>{{ file.columns }}</td>
                            <td><span class="badge badge-warning">{{ file.issues }}</span></td>
                            <td><span class="badge badge-success">{{ file.fixes }}</span></td>
                            <td>
                                <div class="flex items-center">
                                    <div class="progress-bar w-24 mr-2">
                                        <div class="progress-fill" style="width: {{ file.quality }}%"></div>
                                    </div>
                                    <span class="text-sm font-semibold">{{ file.quality }}%</span>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        {% endif %}
        
        <!-- Column Lineage -->
        {% if column_lineage %}
        <div class="card p-6 mb-8">
            <h3 class="text-2xl font-bold mb-4">🔗 Column Lineage</h3>
            <div class="space-y-4">
                {% for lineage in column_lineage %}
                <div class="bg-gray-50 p-4 rounded-lg">
                    <p class="font-semibold mb-2">{{ lineage.canonical_name }}</p>
                    <div class="flex flex-wrap items-center">
                        {% for source in lineage.sources %}
                        <div class="lineage-node">{{ source }}</div>
                        {% if not loop.last %}<span class="arrow">→</span>{% endif %}
                        {% endfor %}
                        <span class="arrow">→</span>
                        <div class="lineage-node" style="background: #667eea; color: white;">
                            <strong>{{ lineage.canonical_name }}</strong>
                        </div>
                    </div>
                    <p class="text-xs text-gray-600 mt-2">Confidence: {{ lineage.confidence }}%</p>
                </div>
                {% endfor %}
            </div>
        </div>
        {% endif %}
        
        <!-- Transformation DAG -->
        {% if transformation_dag %}
        <div class="card p-6 mb-8">
            <h3 class="text-2xl font-bold mb-4">🔄 Transformation DAG</h3>
            <div class="bg-gray-50 p-6 rounded-lg">
                <div class="flex flex-wrap items-center justify-center">
                    {% for step in transformation_dag %}
                    <div class="dag-node text-center">
                        <div class="text-2xl mb-1">{{ step.icon }}</div>
                        <div class="font-semibold text-sm">{{ step.name }}</div>
                        <div class="text-xs text-gray-600">{{ step.count }} items</div>
                    </div>
                    {% if not loop.last %}
                    <span class="arrow">→</span>
                    {% endif %}
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
        
        <!-- Detailed Issues -->
        <div class="card p-6 mb-8">
            <h3 class="text-2xl font-bold mb-4">🔧 Detailed Changes</h3>
            {% for file in detailed_issues %}
            <div class="mb-6">
                <h4 class="font-bold text-lg mb-3 text-gray-800">{{ file.name }}</h4>
                <div class="space-y-2">
                    {% for issue in file.issues %}
                    <div class="bg-green-50 border-l-4 border-green-500 p-3 rounded">
                        <div class="flex items-start">
                            <span class="text-green-600 mr-2">✓</span>
                            <div class="flex-1">
                                <p class="font-semibold text-sm">{{ issue.type }}</p>
                                <p class="text-sm text-gray-700">{{ issue.description }}</p>
                                <p class="text-xs text-gray-500 mt-1">{{ issue.fix_applied }}</p>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
    
    <!-- Footer -->
    <div class="gradient-bg text-white py-8 px-6 mt-12">
        <div class="max-w-7xl mx-auto text-center">
            <p class="text-lg font-semibold">DataShaper AI - Level 2.5</p>
            <p class="text-sm opacity-90 mt-2">100% Deterministic • Zero Hallucinations • Enterprise-Grade</p>
            <p class="text-xs opacity-75 mt-4">All transformations are auditable and repeatable</p>
        </div>
    </div>
</body>
</html>
"""


class EnterpriseReportGenerator:
    """Enterprise-grade HTML report generator with visualizations."""
    
    def generate(
        self,
        metrics: Dict[str, Any],
        schema_summary: Optional[Dict] = None,
        drift_stats: Optional[Dict] = None,
        column_anomalies: Optional[List[Dict]] = None,
        file_comparison: Optional[List[Dict]] = None,
        column_lineage: Optional[List[Dict]] = None,
        transformation_dag: Optional[List[Dict]] = None,
        detailed_issues: Optional[List[Dict]] = None,
        output_path: Path = None
    ) -> str:
        """
        Generate enterprise HTML report.
        
        Args:
            metrics: Overall metrics
            schema_summary: Schema information
            drift_stats: Drift statistics
            column_anomalies: Per-column analysis
            file_comparison: File-to-file comparison
            column_lineage: Column lineage mappings
            transformation_dag: Transformation flow
            detailed_issues: Detailed issue list
            output_path: Where to save report
        """
        from jinja2 import Template
        
        template = Template(HTML_TEMPLATE)
        
        html = template.render(
            timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            metrics=metrics,
            schema_summary=schema_summary,
            drift_stats=drift_stats,
            column_anomalies=column_anomalies or [],
            file_comparison=file_comparison or [],
            column_lineage=column_lineage or [],
            transformation_dag=transformation_dag or [],
            detailed_issues=detailed_issues or []
        )
        
        if output_path:
            Path(output_path).write_text(html, encoding='utf-8')
        
        return html
