#!/usr/bin/env python3
"""
CHRONOS Demo Visualization - Before/After Security Comparison
Generates visual reports showing improvement after remediation
"""

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


class DemoMetrics:
    """Calculate and display demo metrics"""
    
    def __init__(self):
        self.before = self._get_before_metrics()
        self.after = self._get_after_metrics()
    
    def _get_before_metrics(self) -> Dict:
        """Metrics before remediation"""
        return {
            'vulnerabilities': {
                'total': 17,
                'critical': 11,
                'high': 6,
                'medium': 0,
                'low': 0
            },
            'cryptography': {
                'algorithms': {
                    'DES': {'status': 'broken', 'severity': 'critical'},
                    'RC4': {'status': 'broken', 'severity': 'critical'},
                    'MD5': {'status': 'broken', 'severity': 'critical'},
                    'SHA1': {'status': 'deprecated', 'severity': 'high'},
                    'TLS_1_0': {'status': 'deprecated', 'severity': 'critical'},
                    'TLS_1_1': {'status': 'deprecated', 'severity': 'high'},
                },
                'key_sizes': {
                    'RSA': 512,
                    'DES': 64,
                    'JWT_Secret': 32,
                    'AES': None
                }
            },
            'secrets': {
                'hardcoded': 8,
                'in_config': 6,
                'in_logs': 4,
                'exposed_endpoints': 3
            },
            'authentication': {
                'endpoints_protected': 2,
                'endpoints_total': 12,
                'protection_rate': 16.7
            },
            'compliance': {
                'pqc_ready': False,
                'fips_compliant': False,
                'gdpr_ready': False,
                'pci_dss_ready': False
            },
            'tls': {
                'min_version': '1.0',
                'max_version': '1.2',
                'preferred_version': 'TLS 1.0',
                'modern_ciphers': 0
            },
            'risk_score': 9.2
        }
    
    def _get_after_metrics(self) -> Dict:
        """Metrics after remediation"""
        return {
            'vulnerabilities': {
                'total': 2,
                'critical': 0,
                'high': 2,
                'medium': 0,
                'low': 0
            },
            'cryptography': {
                'algorithms': {
                    'AES-256-GCM': {'status': 'secure', 'severity': 'none'},
                    'ChaCha20': {'status': 'secure', 'severity': 'none'},
                    'SHA-256': {'status': 'secure', 'severity': 'none'},
                    'SHA-512': {'status': 'secure', 'severity': 'none'},
                    'TLS_1_3': {'status': 'modern', 'severity': 'none'},
                    'ML-KEM': {'status': 'pqc_ready', 'severity': 'none'},
                },
                'key_sizes': {
                    'RSA': 4096,
                    'ECDSA': 256,
                    'JWT_Secret': 256,
                    'AES': 256
                }
            },
            'secrets': {
                'hardcoded': 0,
                'in_config': 0,
                'in_logs': 0,
                'exposed_endpoints': 0
            },
            'authentication': {
                'endpoints_protected': 12,
                'endpoints_total': 12,
                'protection_rate': 100.0
            },
            'compliance': {
                'pqc_ready': True,
                'fips_compliant': True,
                'gdpr_ready': True,
                'pci_dss_ready': True
            },
            'tls': {
                'min_version': '1.2',
                'max_version': '1.3',
                'preferred_version': 'TLS 1.3',
                'modern_ciphers': 8
            },
            'risk_score': 1.8
        }
    
    def generate_text_report(self) -> str:
        """Generate text-based before/after report"""
        report = []
        report.append("\n" + "=" * 100)
        report.append("CHRONOS DEMO - BEFORE/AFTER SECURITY COMPARISON".center(100))
        report.append("=" * 100)
        
        # Vulnerability Summary
        report.append("\n" + "VULNERABILITY SUMMARY".center(100))
        report.append("-" * 100)
        report.append(f"{'Metric':<30} {'BEFORE':<30} {'AFTER':<30} {'Improvement':<10}")
        report.append("-" * 100)
        
        before_total = self.before['vulnerabilities']['total']
        after_total = self.after['vulnerabilities']['total']
        improvement = ((before_total - after_total) / before_total * 100)
        report.append(f"{'Total Vulnerabilities':<30} {before_total:<30} {after_total:<30} {improvement:.1f}%")
        
        before_critical = self.before['vulnerabilities']['critical']
        after_critical = self.after['vulnerabilities']['critical']
        report.append(f"{'CRITICAL Issues':<30} {before_critical:<30} {after_critical:<30} {100 if before_critical > 0 else 0}%")
        
        before_high = self.before['vulnerabilities']['high']
        after_high = self.after['vulnerabilities']['high']
        improvement = ((before_high - after_high) / before_high * 100) if before_high > 0 else 0
        report.append(f"{'HIGH Issues':<30} {before_high:<30} {after_high:<30} {improvement:.1f}%")
        
        # Cryptography Status
        report.append("\n" + "CRYPTOGRAPHY ASSESSMENT".center(100))
        report.append("-" * 100)
        
        before_broken = sum(1 for algo in self.before['cryptography']['algorithms'].values() 
                           if algo['status'] == 'broken')
        after_broken = sum(1 for algo in self.after['cryptography']['algorithms'].values() 
                          if algo['status'] == 'broken')
        
        report.append(f"{'Broken Algorithms in Use':<30} {before_broken:<30} {after_broken:<30} {'Eliminated' if after_broken == 0 else 'In Progress'}")
        
        # Key Sizes
        report.append("\n" + "CRYPTOGRAPHIC KEY SIZES".center(100))
        report.append("-" * 100)
        
        report.append(f"{'Algorithm':<20} {'BEFORE':<25} {'AFTER':<25} {'Status':<25}")
        report.append("-" * 100)
        
        for algo in ['RSA', 'ECDSA', 'JWT_Secret', 'AES']:
            before_size = self.before['cryptography']['key_sizes'].get(algo, 'N/A')
            after_size = self.after['cryptography']['key_sizes'].get(algo, 'N/A')
            
            if before_size != 'N/A' and after_size != 'N/A':
                if before_size < after_size:
                    status = "✓ Improved"
                else:
                    status = "→ Sufficient"
            else:
                status = "✓ Implemented"
            
            report.append(f"{algo:<20} {str(before_size):<25} {str(after_size):<25} {status:<25}")
        
        # Secrets Management
        report.append("\n" + "SECRETS MANAGEMENT".center(100))
        report.append("-" * 100)
        report.append(f"{'Issue Type':<30} {'BEFORE':<30} {'AFTER':<30} {'Resolution':<10}")
        report.append("-" * 100)
        
        for issue_type in ['hardcoded', 'in_config', 'in_logs', 'exposed_endpoints']:
            before_count = self.before['secrets'][issue_type]
            after_count = self.after['secrets'][issue_type]
            resolution = "✓ Fixed" if after_count == 0 else "In Progress"
            
            report.append(f"{issue_type.replace('_', ' ').title():<30} {before_count:<30} {after_count:<30} {resolution:<10}")
        
        # Authentication & Authorization
        report.append("\n" + "AUTHENTICATION & AUTHORIZATION".center(100))
        report.append("-" * 100)
        
        before_auth = self.before['authentication']
        after_auth = self.after['authentication']
        
        report.append(f"{'Protected Endpoints':<30} {before_auth['endpoints_protected']}/{before_auth['endpoints_total']:<25} {after_auth['endpoints_protected']}/{after_auth['endpoints_total']:<25} 100% Secured")
        report.append(f"{'Protection Rate':<30} {before_auth['protection_rate']:.1f}%{'':<25} {after_auth['protection_rate']:.1f}%{'':<25}")
        
        # Compliance Status
        report.append("\n" + "COMPLIANCE FRAMEWORK STATUS".center(100))
        report.append("-" * 100)
        report.append(f"{'Framework':<30} {'BEFORE':<30} {'AFTER':<30} {'Achieved':<10}")
        report.append("-" * 100)
        
        for framework in ['pqc_ready', 'fips_compliant', 'gdpr_ready', 'pci_dss_ready']:
            before_status = "✗ No" if not self.before['compliance'][framework] else "✓ Yes"
            after_status = "✓ Yes" if self.after['compliance'][framework] else "✗ No"
            achieved = "✓" if self.after['compliance'][framework] else "In Progress"
            
            framework_name = framework.replace('_', ' ').upper()
            report.append(f"{framework_name:<30} {before_status:<30} {after_status:<30} {achieved:<10}")
        
        # TLS Configuration
        report.append("\n" + "TLS/SSL CONFIGURATION".center(100))
        report.append("-" * 100)
        report.append(f"{'Setting':<30} {'BEFORE':<30} {'AFTER':<30} {'Status':<10}")
        report.append("-" * 100)
        
        before_tls = self.before['tls']
        after_tls = self.after['tls']
        
        report.append(f"{'Minimum TLS Version':<30} {before_tls['min_version']:<30} {after_tls['min_version']:<30} ✓ Upgraded")
        report.append(f"{'Maximum TLS Version':<30} {before_tls['max_version']:<30} {after_tls['max_version']:<30} ✓ Current")
        report.append(f"{'Modern Ciphers':<30} {before_tls['modern_ciphers']:<30} {after_tls['modern_ciphers']:<30} ✓ Enabled")
        
        # Overall Risk Score
        report.append("\n" + "OVERALL RISK ASSESSMENT".center(100))
        report.append("=" * 100)
        
        before_risk = self.before['risk_score']
        after_risk = self.after['risk_score']
        improvement = ((before_risk - after_risk) / before_risk * 100)
        
        report.append(f"{'RISK SCORE':<30} {before_risk:.1f}/10.0{'':<20} {after_risk:.1f}/10.0{'':<20}")
        report.append(f"{'STATUS':<30} CRITICAL{'':<25} ACCEPTABLE{'':<20}")
        report.append(f"{'IMPROVEMENT':<30} -{improvement:.1f}%{'':<52}")
        
        report.append("\n" + "=" * 100)
        report.append("RECOMMENDATIONS".center(100))
        report.append("=" * 100)
        
        recommendations = [
            "1. Implement continuous security monitoring and scanning",
            "2. Establish quarterly security audits and penetration testing",
            "3. Deploy post-quantum cryptography for sensitive data",
            "4. Maintain certificate transparency and monitoring",
            "5. Regular security training for development team",
            "6. Implement zero-trust security model",
            "7. Establish incident response procedures",
            "8. Regular key rotation and management policies"
        ]
        
        for rec in recommendations:
            report.append(f"  {rec}")
        
        report.append("\n" + "=" * 100 + "\n")
        
        return "\n".join(report)
    
    def generate_html_report(self, output_file: Path = None) -> str:
        """Generate HTML report with charts"""
        if output_file is None:
            output_file = Path(__file__).parent.parent / "demo" / "before_after_report.html"
        
        html = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CHRONOS Demo - Before/After Report</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 20px;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            padding: 40px;
        }}
        h1 {{
            text-align: center;
            color: #667eea;
            margin-bottom: 10px;
        }}
        .subtitle {{
            text-align: center;
            color: #666;
            margin-bottom: 40px;
            font-size: 14px;
        }}
        .metric-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }}
        .metric-card {{
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 20px;
            border-radius: 5px;
        }}
        .metric-card.before {{
            border-left-color: #ff6b6b;
        }}
        .metric-card.after {{
            border-left-color: #51cf66;
        }}
        .metric-label {{
            font-size: 12px;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 10px;
        }}
        .metric-value {{
            font-size: 32px;
            font-weight: bold;
            color: #333;
        }}
        .metric-improvement {{
            font-size: 14px;
            margin-top: 10px;
            color: #51cf66;
        }}
        .chart-container {{
            position: relative;
            height: 400px;
            margin: 40px 0;
            background: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
        }}
        .comparison-table {{
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }}
        .comparison-table th {{
            background: #667eea;
            color: white;
            padding: 12px;
            text-align: left;
        }}
        .comparison-table td {{
            padding: 12px;
            border-bottom: 1px solid #ddd;
        }}
        .comparison-table tr:hover {{
            background: #f8f9fa;
        }}
        .status-critical {{
            color: #ff6b6b;
            font-weight: bold;
        }}
        .status-high {{
            color: #ffa94d;
            font-weight: bold;
        }}
        .status-good {{
            color: #51cf66;
            font-weight: bold;
        }}
        .risk-score {{
            text-align: center;
            padding: 40px;
            border-radius: 10px;
            margin: 40px 0;
        }}
        .risk-score.before {{
            background: rgba(255, 107, 107, 0.1);
            border: 2px solid #ff6b6b;
        }}
        .risk-score.after {{
            background: rgba(81, 207, 102, 0.1);
            border: 2px solid #51cf66;
        }}
        .risk-score h3 {{
            margin: 0;
            color: #333;
        }}
        .risk-number {{
            font-size: 48px;
            font-weight: bold;
            margin: 20px 0;
        }}
        .risk-score.before .risk-number {{
            color: #ff6b6b;
        }}
        .risk-score.after .risk-number {{
            color: #51cf66;
        }}
        .recommendation {{
            background: #e7f5ff;
            border-left: 4px solid #667eea;
            padding: 15px;
            margin: 10px 0;
            border-radius: 3px;
        }}
        footer {{
            text-align: center;
            color: #999;
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
            font-size: 12px;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 CHRONOS Security Demo</h1>
        <p class="subtitle">Before & After Vulnerability Remediation Report</p>
        <p class="subtitle">Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        
        <h2>Executive Summary</h2>
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 30px 0;">
            <div class="risk-score before">
                <h3>BEFORE Remediation</h3>
                <div class="risk-number">{self.before['risk_score']:.1f}</div>
                <p>Risk Score (out of 10)</p>
                <p style="color: #ff6b6b; font-weight: bold;">STATUS: CRITICAL</p>
            </div>
            <div class="risk-score after">
                <h3>AFTER Remediation</h3>
                <div class="risk-number">{self.after['risk_score']:.1f}</div>
                <p>Risk Score (out of 10)</p>
                <p style="color: #51cf66; font-weight: bold;">STATUS: ACCEPTABLE</p>
            </div>
        </div>
        
        <h2>Vulnerability Comparison</h2>
        <table class="comparison-table">
            <thead>
                <tr>
                    <th>Severity Level</th>
                    <th>Before</th>
                    <th>After</th>
                    <th>Improvement</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><span class="status-critical">CRITICAL</span></td>
                    <td>{self.before['vulnerabilities']['critical']}</td>
                    <td>{self.after['vulnerabilities']['critical']}</td>
                    <td style="color: #51cf66; font-weight: bold;">100% Resolved</td>
                </tr>
                <tr>
                    <td><span class="status-high">HIGH</span></td>
                    <td>{self.before['vulnerabilities']['high']}</td>
                    <td>{self.after['vulnerabilities']['high']}</td>
                    <td style="color: #ffa94d; font-weight: bold;">67% Resolved</td>
                </tr>
                <tr>
                    <td><span class="status-good">TOTAL VULNS</span></td>
                    <td>{self.before['vulnerabilities']['total']}</td>
                    <td>{self.after['vulnerabilities']['total']}</td>
                    <td style="color: #51cf66; font-weight: bold;">88% Improvement</td>
                </tr>
            </tbody>
        </table>
        
        <div class="chart-container">
            <canvas id="vulnerabilityChart"></canvas>
        </div>
        
        <h2>Cryptographic Security Assessment</h2>
        <table class="comparison-table">
            <thead>
                <tr>
                    <th>Metric</th>
                    <th>Before</th>
                    <th>After</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Broken Algorithms</td>
                    <td><span class="status-critical">6</span></td>
                    <td><span class="status-good">0</span></td>
                </tr>
                <tr>
                    <td>Minimum RSA Key Size</td>
                    <td><span class="status-critical">512 bits</span></td>
                    <td><span class="status-good">4096 bits</span></td>
                </tr>
                <tr>
                    <td>TLS Version</td>
                    <td><span class="status-critical">1.0 (Deprecated)</span></td>
                    <td><span class="status-good">1.3 (Current)</span></td>
                </tr>
                <tr>
                    <td>Post-Quantum Ready</td>
                    <td><span class="status-critical">No</span></td>
                    <td><span class="status-good">Yes (ML-KEM)</span></td>
                </tr>
            </tbody>
        </table>
        
        <h2>Secrets Management</h2>
        <table class="comparison-table">
            <thead>
                <tr>
                    <th>Issue</th>
                    <th>Before</th>
                    <th>After</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Hardcoded Secrets</td>
                    <td><span class="status-critical">8</span></td>
                    <td><span class="status-good">0</span></td>
                </tr>
                <tr>
                    <td>Secrets in Logs</td>
                    <td><span class="status-critical">4</span></td>
                    <td><span class="status-good">0</span></td>
                </tr>
                <tr>
                    <td>Exposed Endpoints</td>
                    <td><span class="status-critical">3</span></td>
                    <td><span class="status-good">0</span></td>
                </tr>
            </tbody>
        </table>
        
        <h2>Compliance Status</h2>
        <div class="metric-grid">
            <div class="metric-card">
                <div class="metric-label">PQC Ready</div>
                <div class="metric-value"><span class="status-critical">✗</span></div>
                <div style="margin-top: 10px;">Before: Not Implemented</div>
                <div style="margin-top: 10px; color: #51cf66;">After: ✓ Implemented</div>
            </div>
            <div class="metric-card">
                <div class="metric-label">FIPS Compliant</div>
                <div class="metric-value"><span class="status-critical">✗</span></div>
                <div style="margin-top: 10px;">Before: Non-Compliant</div>
                <div style="margin-top: 10px; color: #51cf66;">After: ✓ Compliant</div>
            </div>
            <div class="metric-card">
                <div class="metric-label">GDPR Ready</div>
                <div class="metric-value"><span class="status-critical">✗</span></div>
                <div style="margin-top: 10px;">Before: Not Ready</div>
                <div style="margin-top: 10px; color: #51cf66;">After: ✓ Ready</div>
            </div>
            <div class="metric-card">
                <div class="metric-label">PCI-DSS Ready</div>
                <div class="metric-value"><span class="status-critical">✗</span></div>
                <div style="margin-top: 10px;">Before: Not Ready</div>
                <div style="margin-top: 10px; color: #51cf66;">After: ✓ Ready</div>
            </div>
        </div>
        
        <h2>Key Recommendations</h2>
        <div class="recommendation">
            <strong>1. Implement Continuous Security Monitoring</strong><br>
            Deploy automated security scanning in your CI/CD pipeline to catch vulnerabilities early.
        </div>
        <div class="recommendation">
            <strong>2. Establish Post-Quantum Cryptography Program</strong><br>
            Begin migration to ML-KEM and ML-DSA for future-proof security.
        </div>
        <div class="recommendation">
            <strong>3. Regular Security Audits</strong><br>
            Conduct quarterly security assessments and penetration testing.
        </div>
        <div class="recommendation">
            <strong>4. Secrets Management</strong><br>
            Implement Vault or similar for centralized credential management.
        </div>
        <div class="recommendation">
            <strong>5. Security Training</strong><br>
            Regular training for development teams on secure coding practices.
        </div>
        <div class="recommendation">
            <strong>6. Zero-Trust Architecture</strong><br>
            Implement zero-trust security model for all infrastructure.
        </div>
        
        <footer>
            <p>CHRONOS Demo Report | Quantum-Safe Cryptography Detection & Analysis</p>
            <p>For more information visit: <a href="https://chronos-security.io">https://chronos-security.io</a></p>
        </footer>
    </div>
    
    <script>
        const ctx = document.getElementById('vulnerabilityChart').getContext('2d');
        const chart = new Chart(ctx, {{
            type: 'bar',
            data: {{
                labels: ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'],
                datasets: [
                    {{
                        label: 'Before Remediation',
                        data: [{self.before['vulnerabilities']['critical']}, {self.before['vulnerabilities']['high']}, {self.before['vulnerabilities']['medium']}, {self.before['vulnerabilities']['low']}],
                        backgroundColor: '#ff6b6b',
                        borderColor: '#ff5252',
                        borderWidth: 1
                    }},
                    {{
                        label: 'After Remediation',
                        data: [{self.after['vulnerabilities']['critical']}, {self.after['vulnerabilities']['high']}, {self.after['vulnerabilities']['medium']}, {self.after['vulnerabilities']['low']}],
                        backgroundColor: '#51cf66',
                        borderColor: '#37b24d',
                        borderWidth: 1
                    }}
                ]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: false,
                plugins: {{
                    legend: {{
                        position: 'top',
                    }},
                    title: {{
                        display: true,
                        text: 'Vulnerability Severity Distribution'
                    }}
                }},
                scales: {{
                    y: {{
                        beginAtZero: true
                    }}
                }}
            }}
        }});
    </script>
</body>
</html>"""
        
        with open(output_file, 'w') as f:
            f.write(html)
        
        return str(output_file)


def main():
    """Main entry point"""
    metrics = DemoMetrics()
    
    # Generate text report
    text_report = metrics.generate_text_report()
    print(text_report)
    
    # Save text report
    text_file = Path(__file__).parent.parent / "demo" / "before_after_comparison.txt"
    with open(text_file, 'w') as f:
        f.write(text_report)
    print(f"✓ Text report saved to: {text_file}\n")
    
    # Generate HTML report
    html_file = metrics.generate_html_report()
    print(f"✓ HTML report saved to: {html_file}\n")
    
    # Summary statistics
    print("\n" + "=" * 100)
    print("SUMMARY STATISTICS".center(100))
    print("=" * 100)
    print(f"Vulnerability Reduction: {((metrics.before['vulnerabilities']['total'] - metrics.after['vulnerabilities']['total']) / metrics.before['vulnerabilities']['total'] * 100):.1f}%")
    print(f"Critical Issues Eliminated: {metrics.before['vulnerabilities']['critical'] - metrics.after['vulnerabilities']['critical']}/{metrics.before['vulnerabilities']['critical']}")
    print(f"Cryptographic Improvements: {sum(1 for algo in metrics.after['cryptography']['algorithms'].values() if algo['status'] in ['secure', 'modern', 'pqc_ready'])}/{len(metrics.after['cryptography']['algorithms'])}")
    print(f"Compliance Frameworks Achieved: {sum(1 for val in metrics.after['compliance'].values() if val)}/{len(metrics.after['compliance'])}")
    print(f"Risk Score Improvement: {((metrics.before['risk_score'] - metrics.after['risk_score']) / metrics.before['risk_score'] * 100):.1f}%")
    print("=" * 100 + "\n")


if __name__ == "__main__":
    main()
