"""Vendor-Karten-Renderer für die Audit-Mail.

Statt 740 Cookie-Rows aggregieren wir nach VENDOR. Pro Vendor eine
Karte mit:
  - Vendor-Name + Sitzland (deklariert + KB)
  - Kategorie deklariert vs KB
  - Cookie-Count + Issue-Count
  - 1-2 Beispiel-Cookies (mit auffälligster Lifetime)
  - Top-Issue-Typen als Tags

Sortiert nach Issue-Severity. Top 30 in der Mail, Rest in CSV.

Die volle 740-Cookies-Tabelle bleibt im CSV-Anhang (cookies-full.csv).
"""

from __future__ import annotations

from collections import defaultdict
from html import escape as h

from ._cookie_inventory import _country_third


def _build_vendor_summary(cmp_vendors: list[dict],
                            coherence_findings: list[dict]) -> list[dict]:
    """Aggregate cookies by vendor, score by issue severity."""
    by_vendor: dict[str, dict] = {}
    # Findings index per vendor
    findings_per_vendor: dict[str, list[dict]] = defaultdict(list)
    for f in coherence_findings:
        v = (f.get("vendor") or "").lower()
        if v:
            findings_per_vendor[v].append(f)

    for v in cmp_vendors:
        name = (v.get("name") or "").strip() or "Unbekannt"
        key = name.lower()
        entry = by_vendor.setdefault(key, {
            "name": name,
            "country": (v.get("country") or "").strip(),
            "category": (v.get("category") or "").strip(),
            "cookies": [],
        })
        for c in (v.get("cookies") or []):
            entry["cookies"].append(c)

    out: list[dict] = []
    sev_score = {"HIGH": 3, "MEDIUM": 2, "LOW": 1, "INFO": 0}
    for key, e in by_vendor.items():
        fs = findings_per_vendor.get(key, [])
        score = sum(sev_score.get((f.get("severity") or "").upper(), 0)
                     for f in fs)
        # Pick up to 2 example cookies: prefer those WITH findings
        finding_cookies = {f.get("cookie_name") for f in fs
                            if f.get("cookie_name")}
        examples = [c for c in e["cookies"]
                    if (c.get("name") or "") in finding_cookies][:2]
        if len(examples) < 2:
            for c in e["cookies"]:
                if len(examples) >= 2:
                    break
                if c not in examples:
                    examples.append(c)
        # Issue-types as tags
        issue_types = sorted({
            (f.get("check_id") or "").split("-")[-1]
            for f in fs
            if f.get("check_id")
        })
        out.append({
            "name": e["name"],
            "country": e["country"],
            "category": e["category"],
            "cookie_count": len(e["cookies"]),
            "issue_count": len(fs),
            "issue_score": score,
            "issue_types": issue_types,
            "examples": examples,
        })

    # Sort: issue_score DESC, then cookie_count DESC
    out.sort(key=lambda r: (-r["issue_score"], -r["cookie_count"]))
    return out


def render_vendor_cards(cmp_vendors: list[dict],
                          coherence_findings: list[dict],
                          top_n: int = 30) -> str:
    summary = _build_vendor_summary(cmp_vendors, coherence_findings)
    if not summary:
        return ""

    total_vendors = len(summary)
    total_cookies = sum(s["cookie_count"] for s in summary)
    total_issues = sum(s["issue_count"] for s in summary)
    cards = []
    for s in summary[:top_n]:
        sev_color = ("#dc2626" if s["issue_score"] >= 6 else
                      "#f59e0b" if s["issue_score"] >= 2 else "#64748b")
        country_disp = s["country"] or "—"
        country_tag = ""
        if s["country"]:
            _disp, is_third, _adq = _country_third(s["country"])
            if is_third:
                country_tag = (
                    " <span style='font-size:10px;color:#dc2626;"
                    "font-weight:700;'>[Drittland]</span>"
                )
        issue_chips = "".join(
            f"<span style='display:inline-block;background:#fee2e2;"
            f"color:#7f1d1d;font-size:10px;padding:1px 6px;border-radius:999px;"
            f"margin-right:3px;'>{h(t)}</span>"
            for t in s["issue_types"][:4]
        )
        examples_html = ""
        for c in s["examples"]:
            cname = c.get("name") or "?"
            lifetime = (c.get("duration") or c.get("persistence")
                        or c.get("expiry") or "—")
            examples_html += (
                f"<div style='font-size:11px;color:#475569;"
                f"font-family:monospace;'>"
                f"• <code>{h(cname)}</code> "
                f"<span style='color:#94a3b8;'>(Lifetime: {h(str(lifetime))})</span>"
                "</div>"
            )

        cards.append(
            f"<div style='margin:10px 0;padding:12px;background:#fff;"
            f"border-left:3px solid {sev_color};border-radius:4px;'>"
            f"<div style='display:flex;justify-content:space-between;"
            f"align-items:baseline;'>"
            f"<div><strong style='font-size:14px;'>{h(s['name'])}</strong>"
            f" <span style='font-size:11px;color:#64748b;'>"
            f"{country_disp}{country_tag}</span></div>"
            f"<div style='font-size:11px;color:#475569;'>"
            f"{s['cookie_count']} Cookies · "
            f"<strong style='color:{sev_color};'>{s['issue_count']}</strong> "
            f"Issues</div>"
            f"</div>"
            f"<div style='margin-top:4px;'>{issue_chips}</div>"
            f"<div style='margin-top:6px;'>{examples_html}</div>"
            "</div>"
        )

    rest_note = ""
    if len(summary) > top_n:
        rest_note = (
            f"<p style='font-size:12px;color:#64748b;margin-top:8px;'>"
            f"<em>… und {len(summary)-top_n} weitere Vendoren — "
            f"vollständige Liste in <code>cookies-full-*.csv</code> "
            f"im ZIP-Anhang.</em></p>"
        )

    return (
        "<div style='margin:24px 0;padding:16px;border-left:4px solid #0f766e;"
        "background:#f0fdfa;border-radius:4px;'>"
        "<h2 style='margin:0 0 8px;color:#134e4a;font-size:16px;'>"
        f"🏷️ Vendor-Übersicht ({total_vendors} Vendoren · "
        f"{total_cookies} Cookies · {total_issues} Issues)"
        "</h2>"
        "<p style='margin:0 0 8px;font-size:12px;color:#475569;'>"
        "Sortiert nach Issue-Severity. Pro Vendor: 1-2 Beispielcookies + "
        "Issue-Tags. Volle Cookie×Finding-Matrix in CSV."
        "</p>"
        + "".join(cards) + rest_note + "</div>"
    )


def render_info_box_rechtsrahmen() -> str:
    """Generic legal-frame info box. Always shown in V2 mail header."""
    return (
        "<div style='margin:16px 0;padding:14px;border:1px solid #e2e8f0;"
        "background:#f8fafc;border-radius:4px;font-size:12px;"
        "color:#475569;line-height:1.5;'>"
        "<strong style='color:#1e293b;'>Rechtsrahmen dieser Analyse</strong>"
        "<ul style='margin:6px 0 0 18px;padding:0;'>"
        "<li><strong>DSGVO Art. 13 Abs. 1 lit. c</strong> — konkrete "
        "Zweckangabe pro Cookie / Verarbeitung.</li>"
        "<li><strong>§ 25 Abs. 1 TDDDG</strong> — Einwilligung für jeden "
        "nicht-technisch-erforderlichen Cookie.</li>"
        "<li><strong>DSGVO Art. 5 Abs. 1 lit. c</strong> — Datenminimierung "
        "(Lifetime + Reichweite).</li>"
        "<li><strong>§ 5 UWG</strong> — irreführende geschäftliche Handlung "
        "(falsche Kategorisierung als 'erforderlich').</li>"
        "<li><strong>§ 30/130 OWiG</strong> — persönliche Verantwortung "
        "der Geschäftsführung.</li>"
        "</ul>"
        "</div>"
    )
