<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RepliMap Security Audit Report</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* Custom styles for code blocks */
        .code-block {
            font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
            font-size: 0.8rem;
            line-height: 1.5;
        }
        .code-block .affected {
            background-color: rgba(239, 68, 68, 0.1);
        }
        /* Collapsible sections */
        details > summary {
            cursor: pointer;
            list-style: none;
        }
        details > summary::-webkit-details-marker {
            display: none;
        }
        details > summary::before {
            content: '▶';
            display: inline-block;
            margin-right: 0.5rem;
            transition: transform 0.2s;
        }
        details[open] > summary::before {
            transform: rotate(90deg);
        }
        /* Print styles */
        @media print {
            .no-print { display: none; }
            .page-break { page-break-before: always; }
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-900">
    <!-- Header -->
    <header class="bg-gradient-to-r from-indigo-600 to-purple-600 text-white py-8">
        <div class="container mx-auto px-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold">🔒 Security Audit Report</h1>
                    <p class="mt-2 text-indigo-100">Generated by RepliMap</p>
                </div>
                <div class="text-right text-sm">
                    <p><strong>Account:</strong> {{ account_id }}</p>
                    <p><strong>Region:</strong> {{ region }}</p>
                    {% if profile %}<p><strong>Profile:</strong> {{ profile }}</p>{% endif %}
                    {% if vpc_id %}<p><strong>VPC:</strong> {{ vpc_id }}</p>{% endif %}
                    <p class="mt-2 text-indigo-200">{{ generated_at }}</p>
                </div>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-6 py-8">
        <!-- Urgent CTA Banner (if issues found) -->
        {% if failed > 0 %}
        <div class="bg-gradient-to-r from-indigo-600 to-purple-600 text-white px-6 py-4 rounded-lg mb-8 shadow-lg no-print">
            <div class="flex items-center justify-between flex-wrap gap-4">
                <div class="flex items-center">
                    <span class="text-2xl mr-3">🔧</span>
                    <div>
                        <p class="font-bold">Found {{ failed }} security issues in your AWS infrastructure</p>
                        <p class="text-indigo-200 text-sm">Get expert help to fix them quickly and correctly</p>
                    </div>
                </div>
                <div class="flex gap-3">
                    <a href="mailto:hello@comply.sh?subject=SOC2%20Remediation%20Request&body=Hi,%0A%0AI%20ran%20a%20RepliMap%20audit%20and%20found%20{{ failed }}%20issues.%0A%0ACan%20you%20help%20me%20fix%20them?%0A%0AThanks!"
                       class="inline-block px-5 py-2 bg-white text-indigo-600 font-bold rounded-lg hover:bg-indigo-50 transition">
                        ✉️ Get Help
                    </a>
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Enhanced Executive Summary -->
        <section class="bg-white rounded-xl shadow-lg p-8 mb-8">
            <h2 class="text-2xl font-bold mb-6 text-gray-800">📊 Executive Summary</h2>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

                <!-- Left: Big Score Card -->
                <div class="flex flex-col items-center justify-center p-6 bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl">
                    <div class="text-8xl font-black {% if score >= 80 %}text-green-600{% elif score >= 60 %}text-yellow-600{% else %}text-red-600{% endif %}">{{ grade }}</div>
                    <div class="text-3xl font-bold text-gray-600 mt-2">{{ score }}/100</div>
                    <div class="text-sm text-gray-500 mt-1">Security Score</div>

                    <!-- Score interpretation -->
                    <div class="mt-4 text-center">
                        {% if score >= 90 %}
                        <span class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium">
                            ✓ Excellent - Production Ready
                        </span>
                        {% elif score >= 70 %}
                        <span class="px-3 py-1 bg-yellow-100 text-yellow-800 rounded-full text-sm font-medium">
                            ⚠ Needs Improvement
                        </span>
                        {% else %}
                        <span class="px-3 py-1 bg-red-100 text-red-800 rounded-full text-sm font-medium">
                            ✗ Critical Issues Found
                        </span>
                        {% endif %}
                    </div>
                </div>

                <!-- Center: Donut Chart -->
                <div class="flex flex-col items-center justify-center">
                    <canvas id="severityChart" width="220" height="220"></canvas>
                    <div class="mt-4 grid grid-cols-2 gap-2 text-sm">
                        <div class="flex items-center">
                            <span class="w-3 h-3 rounded-full bg-purple-500 mr-2"></span>
                            Critical: {{ critical_count }}
                        </div>
                        <div class="flex items-center">
                            <span class="w-3 h-3 rounded-full bg-red-500 mr-2"></span>
                            High: {{ high_count }}
                        </div>
                        <div class="flex items-center">
                            <span class="w-3 h-3 rounded-full bg-yellow-500 mr-2"></span>
                            Medium: {{ medium_count }}
                        </div>
                        <div class="flex items-center">
                            <span class="w-3 h-3 rounded-full bg-blue-500 mr-2"></span>
                            Low: {{ low_count }}
                        </div>
                    </div>
                </div>

                <!-- Right: Stats Cards -->
                <div class="grid grid-cols-2 gap-4">
                    <div class="bg-red-50 rounded-xl p-4 text-center">
                        <div class="text-4xl font-bold text-red-600">{{ failed }}</div>
                        <div class="text-sm text-red-700 font-medium">Failed</div>
                    </div>
                    <div class="bg-green-50 rounded-xl p-4 text-center">
                        <div class="text-4xl font-bold text-green-600">{{ passed }}</div>
                        <div class="text-sm text-green-700 font-medium">Passed</div>
                    </div>
                    <div class="bg-gray-50 rounded-xl p-4 text-center">
                        <div class="text-4xl font-bold text-gray-600">{{ skipped }}</div>
                        <div class="text-sm text-gray-700 font-medium">Skipped</div>
                    </div>
                    <div class="bg-indigo-50 rounded-xl p-4 text-center">
                        <div class="text-4xl font-bold text-indigo-600">{{ total }}</div>
                        <div class="text-sm text-indigo-700 font-medium">Total Checks</div>
                    </div>
                </div>

            </div>

            <!-- Metadata -->
            <div class="mt-6 pt-6 border-t border-gray-200 flex flex-wrap gap-6 text-sm text-gray-500">
                <div><strong>Account:</strong> {{ account_id }}</div>
                <div><strong>Region:</strong> {{ region }}</div>
                {% if vpc_id %}<div><strong>VPC:</strong> {{ vpc_id }}</div>{% endif %}
                <div><strong>Scanned:</strong> {{ generated_at[:19] if generated_at|length > 19 else generated_at }}</div>
            </div>
        </section>

        <!-- Top 3 Critical Risks Section -->
        {% if high_severity %}
        <section class="mb-8">
            <h2 class="text-xl font-bold mb-4 text-red-700 flex items-center">
                <span class="text-2xl mr-2">🚨</span>
                Immediate Action Required
            </h2>

            <div class="space-y-4">
                {% for finding in high_severity[:3] %}
                <div class="bg-gradient-to-r from-red-50 to-orange-50 border-l-4 border-red-500 rounded-lg p-5 shadow-sm">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <span class="inline-flex items-center justify-center w-10 h-10 rounded-full bg-red-100">
                                <span class="text-xl">
                                    {% if loop.index == 1 %}🔥{% elif loop.index == 2 %}⚠️{% else %}🛡️{% endif %}
                                </span>
                            </span>
                        </div>
                        <div class="ml-4 flex-1">
                            <div class="flex items-center justify-between flex-wrap gap-2">
                                <h3 class="text-lg font-bold text-red-800">{{ finding.check_name }}</h3>
                                <span class="px-2 py-1 text-xs font-bold rounded
                                    {% if finding.severity == 'CRITICAL' %}bg-purple-100 text-purple-800
                                    {% else %}bg-red-100 text-red-800{% endif %}">
                                    {{ finding.severity }}
                                </span>
                            </div>

                            <!-- Scary business impact message -->
                            <p class="mt-2 text-red-700 font-medium">
                                {% if 'encryption' in finding.check_name|lower or 'encrypt' in finding.check_id|lower %}
                                💀 <strong>Data Breach Risk:</strong> Without encryption, stolen storage devices expose all your data in plain text. This is a SOC2 audit failure.
                                {% elif 'public' in finding.check_name|lower or finding.check_id == 'CKV_AWS_20' %}
                                🌐 <strong>Public Exposure:</strong> This resource is accessible from the entire internet. Attackers are scanning for this right now.
                                {% elif 'security group' in finding.check_name|lower or finding.check_id in ['CKV_AWS_23', 'CKV_AWS_24'] %}
                                🔓 <strong>Network Exposure:</strong> Open ports allow unauthorized access. Brute-force attacks can start within minutes of discovery.
                                {% elif 'mfa' in finding.check_name|lower or 'password' in finding.check_name|lower %}
                                🔑 <strong>Account Takeover Risk:</strong> Without MFA or strong passwords, a single phished credential compromises your entire AWS account.
                                {% elif 'logging' in finding.check_name|lower or 'cloudtrail' in finding.check_name|lower %}
                                👁️ <strong>Blind Spot:</strong> Without logging, you won't know when an attack happens. Incident response becomes impossible.
                                {% elif 'backup' in finding.check_name|lower or 'versioning' in finding.check_name|lower %}
                                💾 <strong>Data Loss Risk:</strong> Without versioning/backups, accidental deletion or ransomware means permanent data loss.
                                {% else %}
                                ⚡ <strong>Security Gap:</strong> This configuration violates security best practices and may fail compliance audits.
                                {% endif %}
                            </p>

                            <div class="mt-3 flex items-center flex-wrap gap-2 text-sm text-gray-600">
                                <code class="bg-gray-100 px-2 py-1 rounded">{{ finding.check_id }}</code>
                                <span class="text-gray-400">•</span>
                                <span>{{ finding.resource }}</span>
                            </div>

                            <!-- Quick CTA -->
                            <div class="mt-3 no-print">
                                <a href="#finding-{{ loop.index }}" class="text-red-600 hover:text-red-800 text-sm font-medium">
                                    View details & fix →
                                </a>
                                <span class="mx-2 text-gray-300">|</span>
                                <a href="mailto:hello@comply.sh?subject=Help%20fixing%20{{ finding.check_id }}"
                                   class="text-indigo-600 hover:text-indigo-800 text-sm font-medium">
                                    Get help fixing this →
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>

            {% if high_severity|length > 3 %}
            <div class="mt-4 text-center text-gray-500">
                + {{ high_severity|length - 3 }} more high/critical issues below
            </div>
            {% endif %}
        </section>
        {% endif %}

        <!-- SOC2 Control Mapping -->
        {% if soc2_summary %}
        <section class="mb-10">
            <h2 class="text-2xl font-bold mb-6 text-gray-800">📋 SOC2 Control Mapping</h2>
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Control</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Category</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Issues</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for control, info in soc2_summary.items() %}
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ control }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ info.category }}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 py-1 text-xs font-medium bg-red-100 text-red-800 rounded-full">{{ info.count }} issue{% if info.count != 1 %}s{% endif %}</span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 py-1 text-xs font-medium bg-yellow-100 text-yellow-800 rounded-full">Needs Review</span>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </section>
        {% endif %}

        <!-- All Findings -->
        <section class="mb-10 page-break">
            <h2 class="text-2xl font-bold mb-6 text-gray-800">🔍 All Findings ({{ all_findings|length }})</h2>

            <div class="space-y-4">
                {% for enriched in all_findings %}
                {% set finding = enriched.finding %}
                <div id="finding-{{ loop.index }}" class="bg-white rounded-xl shadow-lg overflow-hidden border-l-4
                    {% if finding.severity == 'CRITICAL' %}border-purple-500
                    {% elif finding.severity == 'HIGH' %}border-red-500
                    {% elif finding.severity == 'MEDIUM' %}border-yellow-500
                    {% else %}border-blue-500{% endif %}">

                    <details class="group" {% if loop.index <= 3 and finding.severity in ['CRITICAL', 'HIGH'] %}open{% endif %}>
                        <summary class="px-6 py-4 flex items-center justify-between hover:bg-gray-50">
                            <div class="flex items-center space-x-4">
                                <span class="px-2 py-1 text-xs font-bold rounded border {{ finding.severity | severity_badge }}">
                                    {{ finding.severity }}
                                </span>
                                <div>
                                    <span class="font-mono text-sm font-bold text-gray-700">{{ finding.check_id }}</span>
                                    <span class="mx-2 text-gray-400">|</span>
                                    <span class="text-gray-900">{{ finding.check_name }}</span>
                                </div>
                            </div>
                            <div class="text-sm text-gray-500">
                                {{ finding.resource }}
                            </div>
                        </summary>

                        <div class="px-6 py-4 border-t border-gray-100 bg-gray-50">
                            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                <!-- Details -->
                                <div>
                                    <h4 class="font-medium text-gray-900 mb-3">Details</h4>
                                    <dl class="space-y-2 text-sm">
                                        <div class="flex">
                                            <dt class="w-24 text-gray-500">Resource:</dt>
                                            <dd class="font-mono text-gray-700">{{ finding.resource }}</dd>
                                        </div>
                                        <div class="flex">
                                            <dt class="w-24 text-gray-500">File:</dt>
                                            <dd class="font-mono text-gray-700">{{ finding.file_path }}</dd>
                                        </div>
                                        <div class="flex">
                                            <dt class="w-24 text-gray-500">Lines:</dt>
                                            <dd class="font-mono text-gray-700">{{ finding.file_line_range[0] }}-{{ finding.file_line_range[1] }}</dd>
                                        </div>
                                        {% if enriched.soc2_control %}
                                        <div class="flex">
                                            <dt class="w-24 text-gray-500">SOC2:</dt>
                                            <dd class="text-gray-700">{{ enriched.soc2_control }} ({{ enriched.soc2_category }})</dd>
                                        </div>
                                        {% endif %}
                                        {% if finding.guideline %}
                                        <div class="flex">
                                            <dt class="w-24 text-gray-500">Guide:</dt>
                                            <dd><a href="{{ finding.guideline }}" target="_blank" class="text-indigo-600 hover:text-indigo-800 underline">Documentation ↗</a></dd>
                                        </div>
                                        {% endif %}
                                    </dl>
                                </div>

                                <!-- Code Snippet -->
                                {% if enriched.code_snippet %}
                                <div>
                                    <h4 class="font-medium text-gray-900 mb-3">Affected Code</h4>
                                    <pre class="code-block bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs">{{ enriched.code_snippet }}</pre>
                                </div>
                                {% endif %}
                            </div>

                            <!-- Fix Suggestion -->
                            {% if enriched.fix_suggestion %}
                            <div class="mt-6">
                                <h4 class="font-medium text-gray-900 mb-3">💡 Suggested Fix</h4>
                                <div class="relative">
                                    <pre class="code-block bg-green-900 text-green-100 p-4 rounded-lg overflow-x-auto text-xs">{{ enriched.fix_suggestion }}</pre>
                                    <button onclick="copyToClipboard(this)" class="no-print absolute top-2 right-2 px-3 py-1 bg-green-700 hover:bg-green-600 text-white text-xs rounded transition">
                                        Copy
                                    </button>
                                </div>
                            </div>

                            <!-- Inline CTA for fix help -->
                            {% if finding.severity in ['CRITICAL', 'HIGH'] %}
                            <div class="mt-4 pt-4 border-t border-gray-200 bg-indigo-50 -mx-6 -mb-4 px-6 py-3 no-print">
                                <div class="flex items-center justify-between flex-wrap gap-2">
                                    <span class="text-sm text-indigo-700">
                                        💡 Need help implementing this fix correctly?
                                    </span>
                                    <a href="mailto:hello@comply.sh?subject=Help%20with%20{{ finding.check_id }}%20fix"
                                       class="text-sm font-bold text-indigo-600 hover:text-indigo-800">
                                        Ask an expert →
                                    </a>
                                </div>
                            </div>
                            {% endif %}
                            {% endif %}
                        </div>
                    </details>
                </div>
                {% endfor %}
            </div>
        </section>

        <!-- Bottom CTA Section -->
        {% if failed > 0 %}
        <section class="bg-gradient-to-r from-indigo-600 via-purple-600 to-indigo-700 rounded-2xl shadow-xl p-10 text-white text-center mb-8 no-print">
            <div class="max-w-2xl mx-auto">
                <h2 class="text-3xl font-bold mb-4">Need Help Fixing These Issues?</h2>
                <p class="text-indigo-100 mb-6 text-lg">
                    We specialize in SOC2 AWS remediation. Our team can implement all these fixes
                    using Infrastructure-as-Code, ensuring your environment stays compliant.
                </p>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
                    <div class="bg-white/10 rounded-lg p-4">
                        <div class="text-2xl mb-2">⚡</div>
                        <div class="font-bold">Fast</div>
                        <div class="text-sm text-indigo-200">48-hour turnaround</div>
                    </div>
                    <div class="bg-white/10 rounded-lg p-4">
                        <div class="text-2xl mb-2">🔒</div>
                        <div class="font-bold">Secure</div>
                        <div class="text-sm text-indigo-200">IaC-based, auditable</div>
                    </div>
                    <div class="bg-white/10 rounded-lg p-4">
                        <div class="text-2xl mb-2">✓</div>
                        <div class="font-bold">Guaranteed</div>
                        <div class="text-sm text-indigo-200">Pass your SOC2 audit</div>
                    </div>
                </div>

                <div class="flex flex-col sm:flex-row gap-4 justify-center">
                    <a href="mailto:hello@comply.sh?subject=SOC2%20Remediation%20Inquiry"
                       class="inline-block px-8 py-4 bg-white text-indigo-600 font-bold rounded-xl hover:bg-indigo-50 transition text-lg shadow-lg">
                        ✉️ hello@comply.sh
                    </a>
                </div>
            </div>
        </section>
        {% endif %}
    </main>

    <!-- Footer -->
    <footer class="bg-gray-800 text-gray-300 py-8">
        <div class="container mx-auto px-6 text-center text-sm">
            <p>Generated by <strong>RepliMap</strong> Security Audit</p>
            <p class="mt-2 text-gray-500">
                Powered by <a href="https://www.checkov.io/" target="_blank" class="text-indigo-400 hover:text-indigo-300">Checkov</a> security scanner
            </p>
            <p class="mt-4 text-gray-600">{{ generated_at }}</p>
        </div>
    </footer>

    <script>
        // Copy to clipboard function
        function copyToClipboard(button) {
            const pre = button.parentElement.querySelector('pre');
            const text = pre.textContent;
            navigator.clipboard.writeText(text).then(() => {
                const originalText = button.textContent;
                button.textContent = 'Copied!';
                button.classList.add('bg-green-500');
                setTimeout(() => {
                    button.textContent = originalText;
                    button.classList.remove('bg-green-500');
                }, 2000);
            });
        }

        // Expand all findings on print
        window.addEventListener('beforeprint', () => {
            document.querySelectorAll('details').forEach(d => d.open = true);
        });

        // Chart.js Donut Chart
        document.addEventListener('DOMContentLoaded', function() {
            const ctx = document.getElementById('severityChart').getContext('2d');
            const criticalCount = {{ critical_count }};
            const highCount = {{ high_count }};
            const mediumCount = {{ medium_count }};
            const lowCount = {{ low_count }};
            const passedCount = {{ passed }};

            // Only show chart if there's data
            if (criticalCount + highCount + mediumCount + lowCount + passedCount > 0) {
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: ['Critical', 'High', 'Medium', 'Low', 'Passed'],
                        datasets: [{
                            data: [criticalCount, highCount, mediumCount, lowCount, passedCount],
                            backgroundColor: [
                                '#7c3aed',  // Purple - Critical
                                '#ef4444',  // Red - High
                                '#f59e0b',  // Yellow - Medium
                                '#3b82f6',  // Blue - Low
                                '#22c55e'   // Green - Passed
                            ],
                            borderWidth: 0,
                            hoverOffset: 4
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        cutout: '65%',
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>
