"""Self-contained HTML report with inline CSS and SVG charts."""

from __future__ import annotations

import html
from datetime import datetime, timezone

from butterfence import __version__
from butterfence.scoring import ScoreResult


def _grade_color(grade: str) -> str:
    return {"A": "#22c55e", "B": "#eab308", "C": "#f97316", "F": "#ef4444"}.get(
        grade, "#6b7280"
    )


def _severity_color(severity: str) -> str:
    return {
        "critical": "#ef4444",
        "high": "#f97316",
        "medium": "#eab308",
        "low": "#6b7280",
    }.get(severity, "#6b7280")


def generate_html_report(score_result: ScoreResult, audit_results: list[dict]) -> str:
    """Generate a self-contained HTML safety report."""
    now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    grade_color = _grade_color(score_result.grade)

    passed = sum(1 for r in audit_results if r.get("passed", False))
    failed = len(audit_results) - passed

    # Escape score fields for safe HTML insertion
    grade_esc = html.escape(score_result.grade)
    grade_label_esc = html.escape(score_result.grade_label)

    # Build scenario rows
    rows = []
    for r in audit_results:
        is_passed = r.get("passed", False)
        status = '<span style="color:#22c55e">PASS</span>' if is_passed else '<span style="color:#ef4444">FAIL</span>'
        sev_color = _severity_color(r.get("severity", "high"))
        rows.append(
            f"<tr><td>{status}</td><td>{html.escape(str(r.get('id','')))}</td>"
            f"<td>{html.escape(str(r.get('name','')))}</td><td>{html.escape(str(r.get('category','')))}</td>"
            f'<td><span style="color:{sev_color}">{html.escape(str(r.get("severity","")))}</span></td>'
            f"<td>{html.escape(str(r.get('actual_decision','')))}</td></tr>"
        )
    rows_html = "\n".join(rows)

    # Build category bars
    cat_bars = []
    for cat, stats in score_result.category_coverage.items():
        total = stats["total"]
        p = stats["passed"]
        pct = (p / total * 100) if total else 0
        cat_esc = html.escape(str(cat))
        cat_bars.append(
            f'<div style="margin-bottom:8px"><span style="display:inline-block;width:200px">{cat_esc}</span>'
            f'<div style="display:inline-block;width:200px;height:16px;background:#374151;border-radius:4px">'
            f'<div style="width:{pct}%;height:100%;background:#22c55e;border-radius:4px"></div>'
            f"</div> {p}/{total}</div>"
        )
    cat_html = "\n".join(cat_bars)

    # Build recommendations
    recs_html = "\n".join(f"<li>{html.escape(str(rec))}</li>" for rec in score_result.recommendations)

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ButterFence Safety Report</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
       background: #0f172a; color: #e2e8f0; padding: 24px; line-height: 1.6; }}
.container {{ max-width: 960px; margin: 0 auto; }}
h1 {{ font-size: 28px; margin-bottom: 8px; }}
h2 {{ font-size: 20px; margin: 24px 0 12px; border-bottom: 1px solid #334155; padding-bottom: 8px; }}
.score-card {{ display: flex; align-items: center; gap: 24px; padding: 24px;
              background: #1e293b; border-radius: 12px; margin: 16px 0; }}
.score-number {{ font-size: 48px; font-weight: bold; }}
.grade {{ font-size: 36px; font-weight: bold; padding: 8px 16px; border-radius: 8px; }}
.meta {{ color: #94a3b8; font-size: 14px; }}
table {{ width: 100%; border-collapse: collapse; margin: 12px 0; }}
th, td {{ padding: 8px 12px; text-align: left; border-bottom: 1px solid #334155; }}
th {{ background: #1e293b; font-weight: 600; }}
tr:hover {{ background: #1e293b; }}
ul {{ padding-left: 20px; }}
li {{ margin-bottom: 4px; }}
</style>
</head>
<body>
<div class="container">
<h1>ButterFence Safety Report</h1>
<p class="meta">Generated: {now} | Version: {__version__}</p>

<div class="score-card">
  <div class="score-number" style="color:{grade_color}">{score_result.total_score}/{score_result.max_score}</div>
  <div class="grade" style="background:{grade_color};color:#0f172a">{grade_esc}</div>
  <div>
    <div style="font-size:18px">{grade_label_esc}</div>
    <div class="meta">{passed} passed, {failed} failed / {len(audit_results)} total</div>
  </div>
</div>

<h2>Scenario Results</h2>
<table>
<tr><th>Status</th><th>ID</th><th>Name</th><th>Category</th><th>Severity</th><th>Decision</th></tr>
{rows_html}
</table>

<h2>Category Coverage</h2>
{cat_html}

<h2>Recommendations</h2>
<ul>
{recs_html}
</ul>

<p class="meta" style="margin-top:32px;text-align:center">Generated by ButterFence v{__version__}</p>
</div>
</body>
</html>"""
