"""
Report generator - creates HTML reports of cleaning results.
"""

from pathlib import Path
from datetime import datetime
from jinja2 import Template

from app.autoclean.batch_processor import BatchResult
from app.core.logging import get_logger

logger = get_logger(__name__)


HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>DataShaper AutoClean Report</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 40px 20px;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 700;
        }
        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }
        .summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            padding: 40px;
            background: #f8f9fa;
        }
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            text-align: center;
        }
        .stat-value {
            font-size: 2.5em;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 8px;
        }
        .stat-label {
            color: #666;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .section {
            padding: 40px;
        }
        .section h2 {
            font-size: 1.8em;
            margin-bottom: 20px;
            color: #333;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
        }
        .issue-item {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px 20px;
            margin-bottom: 15px;
            border-radius: 8px;
        }
        .issue-item.fixed {
            background: #d4edda;
            border-left-color: #28a745;
        }
        .issue-title {
            font-weight: 600;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.75em;
            font-weight: 600;
            text-transform: uppercase;
        }
        .badge-success { background: #28a745; color: white; }
        .badge-warning { background: #ffc107; color: #333; }
        .badge-danger { background: #dc3545; color: white; }
        .file-list {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
        }
        .file-item {
            background: white;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .file-name {
            font-weight: 500;
        }
        .file-stats {
            color: #666;
            font-size: 0.9em;
        }
        .footer {
            background: #f8f9fa;
            padding: 30px;
            text-align: center;
            color: #666;
            border-top: 1px solid #dee2e6;
        }
        .check-icon { color: #28a745; font-size: 1.2em; }
        .warning-icon { color: #ffc107; font-size: 1.2em; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>✨ DataShaper AutoClean Report</h1>
            <p>Generated on {{ timestamp }}</p>
        </div>
        
        <div class="summary">
            <div class="stat-card">
                <div class="stat-value">{{ result.total_files }}</div>
                <div class="stat-label">Files Processed</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">{{ result.total_issues_found }}</div>
                <div class="stat-label">Issues Detected</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">{{ result.total_fixes_applied }}</div>
                <div class="stat-label">Fixes Applied</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">{{ total_rows }}</div>
                <div class="stat-label">Total Rows</div>
            </div>
        </div>
        
        <div class="section">
            <h2>📊 Processing Summary</h2>
            <div class="file-list">
                {% for file_result in result.file_results %}
                <div class="file-item">
                    <div>
                        <div class="file-name">{{ file_result.filename }}</div>
                        <div class="file-stats">
                            {{ file_result.original_rows }} rows → {{ file_result.final_rows }} rows
                            | {{ file_result.issues_found|length }} issues | {{ file_result.fixes_applied|length }} fixes
                        </div>
                    </div>
                    {% if file_result.success %}
                        <span class="badge badge-success">✓ Success</span>
                    {% else %}
                        <span class="badge badge-danger">✗ Failed</span>
                    {% endif %}
                </div>
                {% endfor %}
            </div>
        </div>
        
        <div class="section">
            <h2>🔧 Issues Detected & Fixed</h2>
            {% for file_result in result.file_results %}
                {% if file_result.fixes_applied %}
                    <h3 style="color: #667eea; margin: 20px 0 10px 0;">{{ file_result.filename }}</h3>
                    {% for fix in file_result.fixes_applied %}
                    <div class="issue-item fixed">
                        <div class="issue-title">
                            <span class="check-icon">✓</span>
                            <span>{{ fix.message }}</span>
                        </div>
                    </div>
                    {% endfor %}
                {% endif %}
            {% endfor %}
        </div>
        
        <div class="footer">
            <p><strong>DataShaper AutoClean</strong> - 100% Deterministic, Zero Hallucinations</p>
            <p style="margin-top: 10px; font-size: 0.9em;">
                All transformations are safe, repeatable, and auditable.
            </p>
        </div>
    </div>
</body>
</html>
"""


class ReportGenerator:
    """Generates HTML reports for cleaning results."""
    
    def __init__(self):
        """Initialize generator."""
        self.logger = logger
    
    def generate_html(self, result: BatchResult, output_path: Path) -> None:
        """
        Generate HTML report.
        
        Args:
            result: Batch processing result
            output_path: Where to save the report
        """
        template = Template(HTML_TEMPLATE)
        
        # Calculate total rows
        total_rows = sum(r.final_rows for r in result.file_results if r.success)
        
        html = template.render(
            result=result,
            total_rows=total_rows,
            timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        )
        
        output_path = Path(output_path)
        output_path.write_text(html, encoding='utf-8')
        
        self.logger.info(f"Generated report: {output_path}")
