"""B4 wiring — Cross-Doc Vendor-Consistency check + HTML block.

Activated after B1+B3 in the orchestrator. The check itself is
deterministic (no LLM); it scans DSE + cookie texts for known
service providers per service type and flags every mismatch.

The mail renderer reads `state["vendor_consistency_findings"]` and
`state["vendor_consistency_html"]` directly — no further wiring.
"""

from __future__ import annotations

import html
import logging

from compliance.services.vendor_consistency_check import (
    check_vendor_consistency,
)

logger = logging.getLogger(__name__)


def run_b4(state: dict) -> None:
    findings = check_vendor_consistency(state)
    state["vendor_consistency_findings"] = findings
    if not findings:
        return
    state["vendor_consistency_html"] = _render(findings)
    logger.info(
        "B4 Vendor-Consistency: %d findings (HIGH=%d, MEDIUM=%d)",
        len(findings),
        sum(1 for f in findings if (f.get("severity") or "") == "HIGH"),
        sum(1 for f in findings if (f.get("severity") or "") == "MEDIUM"),
    )


def _render(findings: list[dict]) -> str:
    rows = []
    for f in findings:
        sev = (f.get("severity") or "").upper()
        color = "#dc2626" if sev == "HIGH" else "#f59e0b"
        dse = ", ".join(f.get("dse_providers") or []) or "<em>–</em>"
        cookie = ", ".join(f.get("cookie_providers") or []) or "<em>–</em>"
        rows.append(
            "<tr>"
            f"<td style='padding:6px 10px;border-bottom:1px solid #e5e7eb;'>"
            f"{html.escape((f.get('service_type') or '').replace('_',' ').title())}"
            "</td>"
            f"<td style='padding:6px 10px;border-bottom:1px solid #e5e7eb;'>"
            f"{dse}</td>"
            f"<td style='padding:6px 10px;border-bottom:1px solid #e5e7eb;'>"
            f"{cookie}</td>"
            f"<td style='padding:6px 10px;border-bottom:1px solid #e5e7eb;"
            f"color:{color};font-weight:600;'>"
            f"{sev} {html.escape(f.get('severity_reason') or '')}</td>"
            "</tr>"
        )
    return (
        "<div style='margin:24px 0;padding:16px;border-left:4px solid #dc2626;"
        "background:#fff1f2;border-radius:4px;'>"
        "<h2 style='margin:0 0 8px;color:#991b1b;font-size:16px;'>"
        "VENDOR-CONSISTENCY-001 — Vendor-Konsistenz DSE ↔ Cookies</h2>"
        "<p style='margin:0 0 8px;font-size:14px;color:#3f3f46;'>"
        f"<strong>{len(findings)}</strong> Provider-Widersprüche zwischen "
        "Datenschutzerklärung und Cookie-Seite. Beispiel Elli: "
        "DSE = Vertex AI für Chatbot, Cookies-Seite = Iadvize.</p>"
        "<table style='width:100%;border-collapse:collapse;font-size:13px;"
        "margin-top:8px;background:#fff;'>"
        "<thead><tr style='background:#f1f5f9;'>"
        "<th style='text-align:left;padding:6px 10px;'>Service-Typ</th>"
        "<th style='text-align:left;padding:6px 10px;'>In DSE</th>"
        "<th style='text-align:left;padding:6px 10px;'>Auf Cookies-Seite</th>"
        "<th style='text-align:left;padding:6px 10px;'>Severity</th>"
        "</tr></thead>"
        f"<tbody>{''.join(rows)}</tbody>"
        "</table>"
        "</div>"
    )
