"""B9 + B10 wiring — Multi-Entity-Impressum + Drittland-Mechanismus.

Runs after B6/B7/B8. Adds Findings into `state["extra_findings"]`
and re-renders the extra-block HTML.
"""

from __future__ import annotations

import html
import logging

from compliance.services.ai_retention_granularity_check import (
    check_ai_retention_granularity,
)
from compliance.services.impressum_multi_entity_check import (
    check_multi_entity_impressum,
)
from compliance.services.transfer_mechanism_check import (
    check_transfer_mechanism,
)

logger = logging.getLogger(__name__)


def run_b9b10(state: dict) -> None:
    extras = state.get("extra_findings") or []
    new: list[dict] = []
    new.extend(check_multi_entity_impressum(state))
    new.extend(check_transfer_mechanism(state))
    new.extend(check_ai_retention_granularity(state))
    if not new:
        return
    extras.extend(new)
    state["extra_findings"] = extras
    state["extra_findings_html"] = _render(extras)
    logger.info("B9/B10 added %d findings (total extra=%d)",
                len(new), len(extras))


def _render(findings: list[dict]) -> str:
    cards = []
    for f in findings:
        sev = (f.get("severity") or "").upper()
        color = "#dc2626" if sev == "HIGH" else (
            "#f59e0b" if sev == "MEDIUM" else "#64748b"
        )
        meta = ""
        if f.get("entities_missing"):
            meta = ("<div style='font-size:12px;color:#475569;margin-top:6px;'>"
                    f"<em>Fehlt bei: "
                    f"{html.escape(', '.join(f['entities_missing']))}</em>"
                    "</div>")
        elif f.get("vendor"):
            meta = ("<div style='font-size:12px;color:#475569;margin-top:6px;'>"
                    f"<em>Vendor: {html.escape(f['vendor'])} "
                    f"({html.escape(f.get('country','?'))})</em>"
                    "</div>")
        elif f.get("doc_date"):
            meta = ("<div style='font-size:12px;color:#475569;margin-top:6px;'>"
                    f"<em>Stand: {html.escape(f['doc_date'])} "
                    f"({f.get('age_years','?')} J. alt)</em>"
                    "</div>")
        elif f.get("detected_provider"):
            meta = ("<div style='font-size:12px;color:#475569;margin-top:6px;'>"
                    f"<em>Erkannter Provider: "
                    f"{html.escape(f['detected_provider'])}</em>"
                    "</div>")
        elif f.get("evidence_dse"):
            meta = ("<div style='font-size:12px;color:#475569;margin-top:6px;'>"
                    f"<em>In DSE: {html.escape(', '.join(f['evidence_dse']))}</em>"
                    "</div>")
        cards.append(
            f"<div style='margin:12px 0;padding:14px;background:#fff;"
            f"border-left:3px solid {color};border-radius:4px;'>"
            f"<div style='font-weight:600;color:{color};font-size:14px;'>"
            f"{sev} · {html.escape(f.get('check_id') or '')}</div>"
            f"<div style='font-size:14px;margin-top:4px;'>"
            f"<strong>{html.escape(f.get('title') or '')}</strong></div>"
            f"<div style='font-size:12px;color:#64748b;margin-top:2px;'>"
            f"{html.escape(f.get('norm') or '')}</div>"
            f"{meta}"
            f"<div style='font-size:13px;margin-top:8px;background:#dcfce7;"
            f"padding:8px 10px;border-radius:4px;'>"
            f"<strong>→ Empfehlung:</strong> "
            f"{html.escape(f.get('action') or '')}</div>"
            "</div>"
        )
    return (
        "<div style='margin:24px 0;padding:16px;border-left:4px solid #f59e0b;"
        "background:#fffbeb;border-radius:4px;'>"
        "<h2 style='margin:0 0 8px;color:#92400e;font-size:16px;'>"
        "📌 Zusätzliche Cross-Doc-Befunde"
        "</h2>"
        + "".join(cards) +
        "</div>"
    )
