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

class ReportGenerator:
    def __init__(self):
        self.report_data = {}

    def generate_report(self, vulnerabilities: List[Dict], output_format: str = 'json') -> str:
        self.report_data = {
            'generated_at': datetime.now().isoformat(),
            'total_vulnerabilities': len(vulnerabilities),
            'vulnerabilities': self._process_vulnerabilities(vulnerabilities)
        }

        if output_format == 'json':
            return self._generate_json_report()
        elif output_format == 'html':
            return self._generate_html_report()
        else:
            raise ValueError(f"Unsupported output format: {output_format}")

    def _process_vulnerabilities(self, vulnerabilities: List[Dict]) -> List[Dict]:
        processed = []
        for vuln in vulnerabilities:
            processed.append({
                'cve_id': vuln['cve']['CVE_data_meta']['ID'],
                'description': vuln['cve']['description']['description_data'][0]['value'],
                'cvss_score': vuln['impact']['baseMetricV3']['cvssV3']['baseScore'],
                'risk_score': vuln.get('risk_score', 'N/A'),
                'affected_packages': self._get_affected_packages(vuln),
                'mitigation': self._suggest_mitigation(vuln)
            })
        return processed

    def _get_affected_packages(self, vulnerability: Dict) -> List[str]:
        affected = []
        for node in vulnerability['configurations']['nodes']:
            for cpe in node.get('cpe_match', []):
                if cpe.get('vulnerable', False):
                    affected.append(cpe['cpe23Uri'].split(':')[4])
        return list(set(affected))

    def _suggest_mitigation(self, vulnerability: Dict) -> str:
        # This is a simplified mitigation suggestion.
        # In a real-world scenario, you'd want to provide more detailed and specific advice.
        return "Update the affected packages to their latest versions and apply any available security patches."

    def _generate_json_report(self) -> str:
        return json.dumps(self.report_data, indent=2)

    def _generate_html_report(self) -> str:
        html = f"""
        <html>
        <head>
            <title>Vulnerability Report</title>
            <style>
                body {{ font-family: Arial, sans-serif; }}
                table {{ border-collapse: collapse; width: 100%; }}
                th, td {{ border: 1px solid #ddd; padding: 8px; }}
                tr:nth-child(even) {{ background-color: #f2f2f2; }}
                th {{ padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #4CAF50; color: white; }}
            </style>
        </head>
        <body>
            <h1>Vulnerability Report</h1>
            <p>Generated at: {self.report_data['generated_at']}</p>
            <p>Total Vulnerabilities: {self.report_data['total_vulnerabilities']}</p>
            <table>
                <tr>
                    <th>CVE ID</th>
                    <th>Description</th>
                    <th>CVSS Score</th>
                    <th>Risk Score</th>
                    <th>Affected Packages</th>
                    <th>Mitigation</th>
                </tr>
        """

        for vuln in self.report_data['vulnerabilities']:
            html += f"""
                <tr>
                    <td>{vuln['cve_id']}</td>
                    <td>{vuln['description']}</td>
                    <td>{vuln['cvss_score']}</td>
                    <td>{vuln['risk_score']}</td>
                    <td>{', '.join(vuln['affected_packages'])}</td>
                    <td>{vuln['mitigation']}</td>
                </tr>
            """

        html += """
            </table>
        </body>
        </html>
        """

        return html
