"""Compliance report generation."""

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

from jinja2 import Template


class ReportGenerator:
    """Generates HTML compliance reports."""

    def generate(self, results: List[Dict[str, Any]], output_path: Path, config: Dict[str, Any]):
        """Generate compliance report."""

        # Calculate statistics
        total = len(results)
        successful = sum(1 for r in results if r["success"])
        failed = total - successful

        # Group by file type
        by_type = {}
        for result in results:
            if not result["success"]:
                continue
            file_path = Path(result["file"])
            ext = file_path.suffix.lower()
            by_type[ext] = by_type.get(ext, 0) + 1

        # Render template
        html = self._render_template(
            results=results,
            total=total,
            successful=successful,
            failed=failed,
            by_type=by_type,
            config=config,
            generated_at=datetime.utcnow().isoformat(),
        )

        output_path.write_text(html)

    def _render_template(self, **context) -> str:
        """Render HTML template."""

        template = Template(
            """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Compliance Report - {{ generated_at }}</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: #f5f5f5;
            padding: 20px;
            line-height: 1.6;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 32px;
        }
        .subtitle {
            color: #7f8c8d;
            margin-bottom: 30px;
            font-size: 14px;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        .stat-card {
            background: #ecf0f1;
            padding: 20px;
            border-radius: 6px;
            text-align: center;
        }
        .stat-card.success { background: #d5f4e6; }
        .stat-card.fail { background: #fadbd8; }
        .stat-number {
            font-size: 36px;
            font-weight: bold;
            color: #2c3e50;
        }
        .stat-label {
            color: #7f8c8d;
            text-transform: uppercase;
            font-size: 12px;
            margin-top: 5px;
        }
        .section {
            margin: 40px 0;
        }
        .section-title {
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
            margin-bottom: 20px;
            font-size: 24px;
        }
        .config-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            background: #f8f9fa;
            padding: 20px;
            border-radius: 6px;
        }
        .config-item {
            display: flex;
            flex-direction: column;
        }
        .config-label {
            color: #7f8c8d;
            font-size: 12px;
            text-transform: uppercase;
            margin-bottom: 5px;
        }
        .config-value {
            color: #2c3e50;
            font-weight: 500;
        }
        .file-list {
            margin-top: 20px;
        }
        .file-item {
            background: #f8f9fa;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 6px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .file-item.success { border-left: 4px solid #27ae60; }
        .file-item.fail { border-left: 4px solid #e74c3c; }
        .file-name {
            font-family: monospace;
            color: #2c3e50;
            flex: 1;
        }
        .file-status {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        .file-status.success {
            background: #d5f4e6;
            color: #27ae60;
        }
        .file-status.fail {
            background: #fadbd8;
            color: #e74c3c;
        }
        .badge {
            display: inline-block;
            padding: 2px 8px;
            background: #3498db;
            color: white;
            border-radius: 3px;
            font-size: 11px;
            margin-left: 10px;
        }
        .footer {
            margin-top: 50px;
            padding-top: 20px;
            border-top: 1px solid #ecf0f1;
            color: #7f8c8d;
            font-size: 12px;
            text-align: center;
        }
        @media print {
            body { background: white; padding: 0; }
            .container { box-shadow: none; }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🛡️ Compliance Report</h1>
        <div class="subtitle">Generated: {{ generated_at }}</div>

        <div class="stats">
            <div class="stat-card">
                <div class="stat-number">{{ total }}</div>
                <div class="stat-label">Total Files</div>
            </div>
            <div class="stat-card success">
                <div class="stat-number">{{ successful }}</div>
                <div class="stat-label">Processed</div>
            </div>
            <div class="stat-card fail">
                <div class="stat-number">{{ failed }}</div>
                <div class="stat-label">Failed</div>
            </div>
        </div>

        <div class="section">
            <h2 class="section-title">Processing Configuration</h2>
            <div class="config-grid">
                <div class="config-item">
                    <div class="config-label">Watermark Text</div>
                    <div class="config-value">{{ config.watermark_text }}</div>
                </div>
                <div class="config-item">
                    <div class="config-label">Opacity</div>
                    <div class="config-value">{{ config.watermark_opacity }}</div>
                </div>
                <div class="config-item">
                    <div class="config-label">Invisible Watermark</div>
                    <div class="config-value">{{ "Enabled" if config.invisible else "Disabled" }}</div>
                </div>
                <div class="config-item">
                    <div class="config-label">Digital Signature</div>
                    <div class="config-value">{{ "Enabled" if config.sign else "Disabled" }}</div>
                </div>
            </div>
        </div>

        <div class="section">
            <h2 class="section-title">File Types Processed</h2>
            <div class="config-grid">
                {% for ext, count in by_type.items() %}
                <div class="config-item">
                    <div class="config-label">{{ ext.upper() }}</div>
                    <div class="config-value">{{ count }} files</div>
                </div>
                {% endfor %}
            </div>
        </div>

        <div class="section">
            <h2 class="section-title">Processing Results</h2>
            <div class="file-list">
                {% for result in results %}
                <div class="file-item {{ 'success' if result.success else 'fail' }}">
                    <div class="file-name">
                        {{ result.file }}
                        {% if result.signature %}
                        <span class="badge">SIGNED</span>
                        {% endif %}
                    </div>
                    <div class="file-status {{ 'success' if result.success else 'fail' }}">
                        {{ "✓ SUCCESS" if result.success else "✗ FAILED" }}
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>

        <div class="section">
            <h2 class="section-title">Compliance Statement</h2>
            <p style="color: #2c3e50; line-height: 1.8;">
                This report certifies that {{ successful }} out of {{ total }} media files have been processed
                with compliance watermarks and metadata in accordance with the EU AI Act (Regulation 2024/1689).
                Each processed file contains:
            </p>
            <ul style="margin: 20px 0 20px 40px; color: #2c3e50;">
                <li>Visible watermark identifying AI-generated content</li>
                {% if config.invisible %}
                <li>Invisible forensic watermark for tamper detection</li>
                {% endif %}
                {% if config.sign %}
                <li>Cryptographic digital signature (RSA-SHA256)</li>
                {% endif %}
                <li>Embedded metadata including generation timestamp and file provenance</li>
            </ul>
        </div>

        <div class="footer">
            Generated by synth-media-compliance-cli v0.1.0 |
            Report ID: {{ generated_at.replace(':', '').replace('.', '')[:16] }}
        </div>
    </div>
</body>
</html>
        """.strip()
        )

        return template.render(**context)
