"""
Email rendering for the Master-Control scorecard + top-fails summary.

With all 1874 MCs now evaluated per run (#30 cap removed), the report
must summarise rather than dump everything. This module produces:

  - build_scorecard_html(scorecard) — compact regulation-by-regulation
    table at the top of the email
  - build_top_fails_html(fails)     — top-N severe MC fails as a small
    cards block underneath
"""

from __future__ import annotations


def build_scorecard_html(
    scorecard: dict,
    previous_scorecard: dict | None = None,
) -> str:
    """Render the MC scorecard as an HTML table.

    Expects the dict returned by mc_scorecard.build_scorecard. When
    `previous_scorecard` is passed (the run right before this one for
    the same tenant + domain), each row shows a delta indicator
    ('+12%', '-3%') so the DSB sees direction-of-travel at a glance.
    """
    if not scorecard:
        return ""
    rows = scorecard.get("by_regulation") or []
    totals = scorecard.get("totals") or {}
    if not rows:
        return ""

    prev_by_reg: dict[str, int] = {}
    prev_total_pct: int | None = None
    if previous_scorecard:
        prev_total_pct = int((previous_scorecard.get("totals") or {}).get("pct") or 0)
        for r in (previous_scorecard.get("by_regulation") or []):
            prev_by_reg[r.get("regulation", "")] = int(r.get("pct", 0))

    overall_pct = int(totals.get("pct", 0))
    overall_color = ("#16a34a" if overall_pct >= 80 else
                     "#d97706" if overall_pct >= 50 else "#dc2626")
    trend_str = _delta_badge(overall_pct, prev_total_pct) if prev_total_pct is not None else ""

    head = (
        '<div id="mc-scorecard" style="font-family:-apple-system,BlinkMacSystemFont,sans-serif;'
        'max-width:700px;margin:0 auto 16px;padding:12px 16px;'
        'background:#f0f9ff;border:1px solid #bae6fd;border-radius:8px">'
        '<h3 style="margin:0 0 6px;font-size:14px;color:#0369a1">'
        'MC-Scorecard (Pflichtangaben aus Master-Controls)</h3>'
        f'<p style="margin:0 0 10px;font-size:11px;color:#475569">'
        f'<strong style="color:{overall_color};font-size:13px">{overall_pct}%</strong>{trend_str} '
        f'gesamt &middot; {totals.get("passed", 0)} bestanden, '
        f'{totals.get("failed", 0)} nicht bestanden '
        f'({totals.get("total", 0)} MCs ausgewertet, '
        f'{totals.get("skipped", 0)} nicht anwendbar).</p>'
    )

    body = [
        '<table style="width:100%;border-collapse:collapse;font-size:11px">'
        '<thead><tr style="background:#dbeafe;color:#1e40af;text-align:left">'
        '<th style="padding:5px 8px">Regulation</th>'
        '<th style="padding:5px 8px;text-align:center">Bestanden</th>'
        '<th style="padding:5px 8px;text-align:center">Fail</th>'
        '<th style="padding:5px 8px;text-align:center">HIGH</th>'
        '<th style="padding:5px 8px;text-align:center">MEDIUM</th>'
        '<th style="padding:5px 8px;text-align:right">Score</th>'
        '</tr></thead><tbody>'
    ]
    for r in rows:
        pct = int(r.get("pct", 0))
        color = ("#16a34a" if pct >= 80 else
                 "#d97706" if pct >= 50 else "#dc2626")
        sev = r.get("severity") or {}
        prev = prev_by_reg.get(r["regulation"])
        trend = _delta_badge(pct, prev)
        body.append(
            f'<tr style="border-top:1px solid #bfdbfe">'
            f'<td style="padding:5px 8px;color:#1e293b">{r["regulation"]}</td>'
            f'<td style="padding:5px 8px;text-align:center;color:#16a34a">'
            f'{r["passed"]}</td>'
            f'<td style="padding:5px 8px;text-align:center;color:#dc2626">'
            f'{r["failed"]}</td>'
            f'<td style="padding:5px 8px;text-align:center;color:#dc2626">'
            f'{sev.get("HIGH", 0) + sev.get("CRITICAL", 0)}</td>'
            f'<td style="padding:5px 8px;text-align:center;color:#d97706">'
            f'{sev.get("MEDIUM", 0)}</td>'
            f'<td style="padding:5px 8px;text-align:right;font-weight:600;'
            f'color:{color}">{pct}%{trend}</td>'
            f'</tr>'
        )
    body.append('</tbody></table></div>')
    return head + "".join(body)


def _delta_badge(current: int, previous: int | None) -> str:
    """Render a small ±N% badge next to a percentage when previous is known."""
    if previous is None or previous == current:
        return ""
    delta = current - previous
    if delta > 0:
        color, sign = "#16a34a", "+"
    else:
        color, sign = "#dc2626", ""
    return (f' <span style="font-size:10px;color:{color};font-weight:500">'
            f'({sign}{delta}%)</span>')


def build_top_fails_html(fails: list[dict], doc_label: str) -> str:
    """Render top-N severe MC fails as a compact card list per document."""
    if not fails:
        return ""
    out = [
        '<div style="margin:10px 0 8px;padding:10px 12px;'
        'background:#fef2f2;border-left:3px solid #fca5a5;border-radius:4px">'
        f'<strong style="font-size:12px;color:#991b1b">'
        f'Top-Auffaelligkeiten in {doc_label} ({len(fails)})</strong>'
        '<ul style="margin:6px 0 0 18px;padding:0;font-size:11px;'
        'color:#7f1d1d">'
    ]
    for f in fails:
        sev = f.get("severity") or "MEDIUM"
        reg = f.get("regulation") or ""
        reg_str = f' <span style="color:#94a3b8">[{reg}]</span>' if reg else ""
        label = f.get("label") or "Unnamed"
        hint = (f.get("hint") or "")[:200]
        out.append(
            f'<li style="margin-bottom:4px">'
            f'<span style="color:#dc2626;font-weight:600">{sev}</span>'
            f'{reg_str} &mdash; {label}'
            + (f'<div style="font-size:10px;color:#94a3b8;margin-top:1px">'
               f'{hint}</div>' if hint else "")
            + '</li>'
        )
    out.append('</ul></div>')
    return "".join(out)
