"""Executive Summary für die V2-Audit-Mail.

Sitzt ganz oben in der Mail. Reviewer sieht in ≤ 15 Zeilen:
  - Compliance-Score (gross + farbig)
  - Top-3-Findings nach Severity
  - Cookie-Statistik (deklariert / Browser / Drittland)
  - Saving-Indikation (1 Zahl)
  - Verteilung der Findings-Typen

Alles danach (B-Blocks, Per-Doc, Per-Theme) wird in
`<details><summary>` kollabiert ausgespielt.
"""

from __future__ import annotations

from collections import Counter
from html import escape as h


def _scorecard_html(state: dict) -> str:
    sc = state.get("scorecard") or {}
    score = sc.get("compliance_pct")
    if score is None:
        score = sc.get("completeness_pct", 0)
    score_int = int(score) if score is not None else 0
    color = ("#15803d" if score_int >= 80
             else "#f59e0b" if score_int >= 50 else "#dc2626")
    label = ("GUT" if score_int >= 80
             else "VERBESSERUNGSBEDARF" if score_int >= 50 else "KRITISCH")
    return (
        f"<div style='text-align:center;padding:14px 20px;"
        f"background:#fff;border-radius:6px;min-width:140px;'>"
        f"<div style='font-size:11px;color:#64748b;text-transform:uppercase;"
        f"letter-spacing:1px;'>Compliance-Score</div>"
        f"<div style='font-size:42px;font-weight:700;color:{color};"
        f"line-height:1;margin:6px 0;'>{score_int}%</div>"
        f"<div style='font-size:11px;color:{color};font-weight:600;'>"
        f"{label}</div></div>"
    )


def _findings_top_severity_html(state: dict, top_n: int = 3) -> str:
    extras = state.get("extra_findings") or []
    # Filter to HIGH/MEDIUM, take top_n
    high_med = [
        f for f in extras
        if (f.get("severity") or "").upper() in ("HIGH", "MEDIUM")
    ]
    high_med.sort(
        key=lambda f: 0 if (f.get("severity") or "").upper() == "HIGH" else 1,
    )
    if not high_med:
        return (
            "<p style='font-size:13px;color:#64748b;margin:0;'>"
            "<em>Keine HIGH/MEDIUM Findings — siehe Detail-Sektionen "
            "für Hinweise.</em></p>"
        )
    rows = []
    for f in high_med[:top_n]:
        sev = (f.get("severity") or "").upper()
        color = "#dc2626" if sev == "HIGH" else "#f59e0b"
        title = (f.get("title") or "")[:120]
        norm = (f.get("norm") or "")[:80]
        rows.append(
            f"<div style='display:flex;gap:10px;padding:8px 10px;"
            f"background:#fff;border-left:3px solid {color};"
            f"margin-bottom:6px;border-radius:3px;'>"
            f"<div style='font-size:11px;font-weight:700;color:{color};"
            f"min-width:60px;'>{sev}</div>"
            f"<div><div style='font-size:13px;font-weight:600;color:#1e293b;'>"
            f"{h(title)}</div>"
            f"<div style='font-size:11px;color:#64748b;margin-top:2px;'>"
            f"{h(norm)}</div></div></div>"
        )
    return "".join(rows)


def _cookie_stats_html(state: dict) -> str:
    cmp_vendors = state.get("cmp_vendors") or []
    declared = sum(len(v.get("cookies") or []) for v in cmp_vendors)
    banner = state.get("banner_result") or {}
    in_browser = len(banner.get("cookies_detailed") or [])
    third_country = sum(
        1 for v in cmp_vendors
        if (v.get("country") or "").upper() not in ("DE", "AT", "BE", "FR",
            "NL", "IT", "ES", "IE", "DK", "FI", "SE", "PT", "PL", "CZ",
            "CH", "NO", "LI", "IS", "")
    )
    return (
        f"<div style='display:flex;gap:8px;flex-wrap:wrap;'>"
        f"<div style='flex:1;min-width:80px;text-align:center;padding:8px;"
        f"background:#fff;border-radius:4px;'>"
        f"<div style='font-size:22px;font-weight:700;color:#1e293b;'>"
        f"{declared}</div>"
        f"<div style='font-size:10px;color:#64748b;text-transform:uppercase;'>"
        f"Cookies deklariert</div></div>"
        f"<div style='flex:1;min-width:80px;text-align:center;padding:8px;"
        f"background:#fff;border-radius:4px;'>"
        f"<div style='font-size:22px;font-weight:700;color:#1e293b;'>"
        f"{in_browser}</div>"
        f"<div style='font-size:10px;color:#64748b;text-transform:uppercase;'>"
        f"Im Browser gesetzt</div></div>"
        f"<div style='flex:1;min-width:80px;text-align:center;padding:8px;"
        f"background:#fff;border-radius:4px;'>"
        f"<div style='font-size:22px;font-weight:700;color:"
        f"{'#dc2626' if third_country > 0 else '#64748b'};'>"
        f"{third_country}</div>"
        f"<div style='font-size:10px;color:#64748b;text-transform:uppercase;'>"
        f"Vendoren Drittland</div></div>"
        f"</div>"
    )


def _findings_distribution_html(state: dict) -> str:
    extras = state.get("extra_findings") or []
    if not extras:
        return ""
    by_sev = Counter(
        (f.get("severity") or "").upper() for f in extras
    )
    parts = []
    for sev, color in (("HIGH", "#dc2626"), ("MEDIUM", "#f59e0b"),
                        ("LOW", "#64748b"), ("INFO", "#94a3b8")):
        n = by_sev.get(sev, 0)
        if n > 0:
            parts.append(
                f"<span style='font-size:11px;color:{color};"
                f"font-weight:600;'>{n} {sev}</span>"
            )
    return " · ".join(parts)


def render_executive_summary(state: dict) -> str:
    """Top-of-mail TL;DR. Should fit on 1 screen."""
    return (
        "<div style='margin:0 0 16px;padding:18px 20px;"
        "background:linear-gradient(135deg,#f1f5f9,#e2e8f0);"
        "border-radius:8px;border-left:5px solid #0f766e;'>"
        "<h2 style='margin:0 0 12px;color:#1e293b;font-size:18px;'>"
        "📊 Executive Summary"
        "</h2>"
        "<div style='display:flex;gap:14px;align-items:stretch;"
        "margin-bottom:14px;flex-wrap:wrap;'>"
        + _scorecard_html(state) +
        f"<div style='flex:1;min-width:240px;'>"
        f"<div style='font-size:11px;color:#64748b;font-weight:600;"
        f"text-transform:uppercase;margin-bottom:6px;letter-spacing:1px;'>"
        f"Top Befunde · {_findings_distribution_html(state)}"
        f"</div>"
        + _findings_top_severity_html(state, top_n=3) +
        "</div>"
        "</div>"
        + _cookie_stats_html(state) +
        "<p style='margin:12px 0 0;font-size:11px;color:#64748b;"
        "text-align:right;'>"
        "<em>Details siehe Akkordeons unten — alle Sektionen "
        "klappbar.</em></p>"
        "</div>"
    )


def collapsible(title: str, body: str, *, open_default: bool = False) -> str:
    """Wrap any HTML block in a <details>/<summary> accordion."""
    if not body:
        return ""
    open_attr = " open" if open_default else ""
    return (
        f"<details{open_attr} style='margin:12px 0;border:1px solid #e2e8f0;"
        f"border-radius:6px;padding:0;background:#fff;'>"
        f"<summary style='cursor:pointer;padding:12px 16px;"
        f"font-weight:600;color:#1e293b;font-size:14px;"
        f"background:#f8fafc;border-radius:6px 6px 0 0;'>{h(title)}</summary>"
        f"<div style='padding:8px 16px 16px;'>{body}</div>"
        "</details>"
    )
