"""B6 / B7 / B8 wiring — DPO-cross-doc, doc-staleness, CMP-fingerprint.

Three small, deterministic checks added after B5. Each writes one or
more findings into `state["extra_findings"]` and a tiny HTML block
into `state["extra_findings_html"]` that the V2 renderer concatenates
between B5 (AI-Act) and the legacy section block.
"""

from __future__ import annotations

import html
import logging

from compliance.services.cmp_fingerprint_check import check_cmp_fingerprint
from compliance.services.cross_doc_dpo_check import check_dpo_cross_doc
from compliance.services.doc_staleness_check import check_staleness

logger = logging.getLogger(__name__)


def run_b6b7b8(state: dict) -> None:
    findings: list[dict] = []

    dpo = check_dpo_cross_doc(state)
    if dpo:
        findings.append(dpo)

    stale = check_staleness(state)
    findings.extend(stale)

    cmp = check_cmp_fingerprint(state)
    if cmp:
        findings.append(cmp)

    state["extra_findings"] = findings
    if findings:
        state["extra_findings_html"] = _render(findings)
        logger.info(
            "B6/B7/B8 extra: %d findings (DPO=%d, staleness=%d, CMP=%d)",
            len(findings), 1 if dpo else 0, len(stale), 1 if cmp else 0,
        )


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"
        )
        evidence_html = ""
        if f.get("evidence_dse"):
            evidence_html = (
                "<div style='font-size:12px;color:#475569;margin-top:6px;'>"
                f"<em>In DSE: {html.escape(', '.join(f['evidence_dse']))}</em>"
                "</div>"
            )
        if f.get("doc_date"):
            evidence_html = (
                "<div style='font-size:12px;color:#475569;margin-top:6px;'>"
                f"<em>Stand: {html.escape(f['doc_date'])} "
                f"({f.get('age_years','?')} Jahre alt, Cap "
                f"{f.get('threshold_years','?')} Jahre)</em>"
                "</div>"
            )
        if f.get("detected_provider"):
            evidence_html = (
                "<div style='font-size:12px;color:#475569;margin-top:6px;'>"
                f"<em>Erkannter Provider: "
                f"{html.escape(f['detected_provider'])}</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"{evidence_html}"
            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 (DPO / Staleness / CMP-Fingerprint)"
        "</h2>"
        + "".join(cards) +
        "</div>"
    )
