"""HTML report generator for security audit results."""

import html
from datetime import datetime
from typing import Any

from superclaw.reporting.base import ReportGenerator


class HTMLReportGenerator(ReportGenerator):
    """Generates standalone HTML security audit reports."""

    def generate(self, results: dict[str, Any], output: str) -> None:
        """Generate an HTML report from audit results.

        Args:
            results: The audit results dictionary containing findings.
            output: The output file path for the generated report.
        """
        self._ensure_parent_dir(output)

        html_content = self._build_html(results)

        with open(output, "w", encoding="utf-8") as f:
            f.write(html_content)

    def _build_html(self, results: dict[str, Any]) -> str:
        """Build the complete HTML document."""
        summary = self._extract_summary(results)
        findings_html = self._build_findings_table(results)
        scenarios_html = self._build_scenarios_table(results)

        return f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Security Audit Report - Superclaw</title>
    <style>
{self._get_css()}
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>🔒 Security Audit Report</h1>
            <p class="subtitle">Generated by Superclaw</p>
            <p class="timestamp">Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
        </header>

        <section class="summary">
            <h2>Summary</h2>
            <div class="summary-grid">
                <div class="summary-card total">
                    <span class="count">{summary["total"]}</span>
                    <span class="label">Total Tests</span>
                </div>
                <div class="summary-card passed">
                    <span class="count">{summary["passed"]}</span>
                    <span class="label">Passed</span>
                </div>
                <div class="summary-card failed">
                    <span class="count">{summary["failed"]}</span>
                    <span class="label">Failed</span>
                </div>
                <div class="summary-card skipped">
                    <span class="count">{summary["skipped"]}</span>
                    <span class="label">Skipped</span>
                </div>
            </div>

            <div class="severity-breakdown">
                <h3>Severity Breakdown</h3>
                <div class="severity-grid">
                    <div class="severity-item critical">
                        <span class="severity-count">{summary["severity"]["critical"]}</span>
                        <span class="severity-label">Critical</span>
                    </div>
                    <div class="severity-item high">
                        <span class="severity-count">{summary["severity"]["high"]}</span>
                        <span class="severity-label">High</span>
                    </div>
                    <div class="severity-item medium">
                        <span class="severity-count">{summary["severity"]["medium"]}</span>
                        <span class="severity-label">Medium</span>
                    </div>
                    <div class="severity-item low">
                        <span class="severity-count">{summary["severity"]["low"]}</span>
                        <span class="severity-label">Low</span>
                    </div>
                </div>
            </div>
        </section>

        <section class="findings">
            <h2>Detailed Findings</h2>
            {findings_html}
        </section>

        <section class="scenarios">
            <h2>Scenario Results</h2>
            {scenarios_html}
        </section>

        <footer>
            <p>
                Report generated by <strong>Superclaw</strong> - AI Agent Security Auditing
                Framework
            </p>
        </footer>
    </div>
</body>
</html>"""

    def _get_css(self) -> str:
        """Return the CSS styles for the report."""
        return """
        :root {
            --primary: #2563eb;
            --success: #16a34a;
            --danger: #dc2626;
            --warning: #d97706;
            --info: #0891b2;
            --critical: #7c2d12;
            --high: #dc2626;
            --medium: #d97706;
            --low: #2563eb;
            --bg: #f8fafc;
            --card-bg: #ffffff;
            --text: #1e293b;
            --text-muted: #64748b;
            --border: #e2e8f0;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
                'Helvetica Neue', Arial, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        header {
            text-align: center;
            margin-bottom: 3rem;
            padding-bottom: 2rem;
            border-bottom: 2px solid var(--border);
        }

        header h1 {
            font-size: 2.5rem;
            color: var(--primary);
            margin-bottom: 0.5rem;
        }

        .subtitle {
            font-size: 1.2rem;
            color: var(--text-muted);
        }

        .timestamp {
            font-size: 0.9rem;
            color: var(--text-muted);
            margin-top: 0.5rem;
        }

        section {
            margin-bottom: 3rem;
        }

        h2 {
            font-size: 1.5rem;
            margin-bottom: 1.5rem;
            color: var(--text);
        }

        h3 {
            font-size: 1.2rem;
            margin-bottom: 1rem;
            color: var(--text);
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .summary-card {
            background: var(--card-bg);
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid var(--border);
        }

        .summary-card .count {
            display: block;
            font-size: 2.5rem;
            font-weight: 700;
        }

        .summary-card .label {
            display: block;
            font-size: 0.9rem;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .summary-card.passed .count { color: var(--success); }
        .summary-card.failed .count { color: var(--danger); }
        .summary-card.total .count { color: var(--primary); }
        .summary-card.skipped .count { color: var(--text-muted); }

        .severity-breakdown {
            background: var(--card-bg);
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid var(--border);
        }

        .severity-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 1rem;
        }

        .severity-item {
            text-align: center;
            padding: 1rem;
            border-radius: 8px;
        }

        .severity-item.critical { background: #fef2f2; }
        .severity-item.high { background: #fef2f2; }
        .severity-item.medium { background: #fffbeb; }
        .severity-item.low { background: #eff6ff; }

        .severity-count {
            display: block;
            font-size: 1.5rem;
            font-weight: 700;
        }

        .severity-item.critical .severity-count { color: var(--critical); }
        .severity-item.high .severity-count { color: var(--high); }
        .severity-item.medium .severity-count { color: var(--medium); }
        .severity-item.low .severity-count { color: var(--low); }

        .severity-label {
            font-size: 0.85rem;
            color: var(--text-muted);
        }

        .findings-table {
            width: 100%;
            border-collapse: collapse;
            background: var(--card-bg);
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .findings-table th,
        .findings-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid var(--border);
        }

        .findings-table th {
            background: #f1f5f9;
            font-weight: 600;
            color: var(--text);
            text-transform: uppercase;
            font-size: 0.8rem;
            letter-spacing: 0.05em;
        }

        .findings-table tr:last-child td {
            border-bottom: none;
        }

        .findings-table tr:hover {
            background: #f8fafc;
        }

        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-passed { background: #dcfce7; color: var(--success); }
        .status-failed { background: #fee2e2; color: var(--danger); }
        .status-skipped { background: #f1f5f9; color: var(--text-muted); }

        .severity-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .severity-critical { background: #fecaca; color: var(--critical); }
        .severity-high { background: #fee2e2; color: var(--high); }
        .severity-medium { background: #fef3c7; color: var(--medium); }
        .severity-low { background: #dbeafe; color: var(--low); }

        .evidence {
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 0.85rem;
            background: #f8fafc;
            padding: 0.5rem;
            border-radius: 4px;
            max-width: 400px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .no-findings {
            text-align: center;
            padding: 3rem;
            color: var(--text-muted);
            background: var(--card-bg);
            border-radius: 12px;
            border: 1px solid var(--border);
        }

        footer {
            text-align: center;
            padding-top: 2rem;
            border-top: 1px solid var(--border);
            color: var(--text-muted);
            font-size: 0.9rem;
        }

        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }

            header h1 {
                font-size: 1.75rem;
            }

            .findings-table {
                display: block;
                overflow-x: auto;
            }
        }
        """

    def _extract_summary(self, results: dict[str, Any]) -> dict[str, Any]:
        """Extract summary statistics from results."""
        findings = results.get("findings", results.get("results", []))

        if not isinstance(findings, list):
            findings = []

        passed = sum(1 for f in findings if f.get("status") == "passed")
        failed = sum(1 for f in findings if f.get("status") == "failed")
        skipped = sum(1 for f in findings if f.get("status") == "skipped")

        severity_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0}
        for f in findings:
            if f.get("status") == "failed":
                severity = f.get("severity", "medium").lower()
                if severity in severity_counts:
                    severity_counts[severity] += 1

        return {
            "total": len(findings),
            "passed": passed,
            "failed": failed,
            "skipped": skipped,
            "severity": severity_counts,
        }

    def _build_findings_table(self, results: dict[str, Any]) -> str:
        """Build the findings table HTML."""
        findings = results.get("findings", results.get("results", []))

        if not isinstance(findings, list) or not findings:
            return '<div class="no-findings">No findings to display</div>'

        rows = []
        for finding in findings:
            behavior = html.escape(str(finding.get("behavior", "N/A")))
            status = finding.get("status", "unknown")
            severity = finding.get("severity", "medium").lower()
            evidence = html.escape(str(finding.get("evidence", "")))[:200]
            mitigation = html.escape(str(finding.get("mitigation", "")))[:200]

            status_class = f"status-{status}"
            severity_class = f"severity-{severity}"

            rows.append(f"""
            <tr>
                <td>{behavior}</td>
                <td><span class="status-badge {status_class}">{status}</span></td>
                <td><span class="severity-badge {severity_class}">{severity}</span></td>
                <td><div class="evidence">{evidence if evidence else "-"}</div></td>
                <td><div class="evidence">{mitigation if mitigation else "-"}</div></td>
            </tr>""")

        return f"""
        <table class="findings-table">
            <thead>
                <tr>
                    <th>Behavior</th>
                    <th>Status</th>
                    <th>Severity</th>
                    <th>Evidence</th>
                    <th>Mitigation</th>
                </tr>
            </thead>
            <tbody>
                {"".join(rows)}
            </tbody>
        </table>"""

    def _build_scenarios_table(self, results: dict[str, Any]) -> str:
        """Build the scenarios table HTML."""
        scenarios = results.get("scenarios", [])

        if not isinstance(scenarios, list) or not scenarios:
            return '<div class="no-findings">No scenario results to display</div>'

        rows = []
        for scenario in scenarios:
            scenario_id = html.escape(str(scenario.get("id", "N/A")))
            behavior = html.escape(str(scenario.get("behavior", "N/A")))
            status = "passed" if scenario.get("passed") else "failed"
            score = scenario.get("score", 0.0)
            response_preview = html.escape(str(scenario.get("response_preview", "")))[:200]

            evidence_items = []
            behavior_results = scenario.get("behavior_results", {})
            if isinstance(behavior_results, dict):
                for result in behavior_results.values():
                    evidence = result.get("evidence", [])
                    if isinstance(evidence, list):
                        evidence_items.extend(str(item) for item in evidence)
                    elif evidence:
                        evidence_items.append(str(evidence))

            evidence_text = html.escape("; ".join(evidence_items))[:200]

            status_class = f"status-{status}"

            rows.append(f"""
            <tr>
                <td>{scenario_id}</td>
                <td>{behavior}</td>
                <td><span class="status-badge {status_class}">{status}</span></td>
                <td>{score:.2f}</td>
                <td><div class="evidence">{evidence_text if evidence_text else "-"}</div></td>
                <td><div class="evidence">{response_preview if response_preview else "-"}</div></td>
            </tr>""")

        return f"""
        <table class="findings-table">
            <thead>
                <tr>
                    <th>Scenario ID</th>
                    <th>Behavior</th>
                    <th>Status</th>
                    <th>Score</th>
                    <th>Evidence</th>
                    <th>Response Preview</th>
                </tr>
            </thead>
            <tbody>
                {"".join(rows)}
            </tbody>
        </table>"""
