"""Mail-V2 legacy wrappers — wrap each existing build_*_html() in V2 shell.

The original step-5 had 24+ render functions, each emitting standalone
HTML with their own styles. V2 keeps all the information by wrapping
each output in a consistent V2 `section()` container with stripe +
palette. The block-level styling normalizes; the inner data tables/
lists keep their legacy markup so we don't lose detail.

Each wrapper is defensive: missing data, import errors, or empty
HTML → return "" so the section disappears rather than crashing.
"""

from __future__ import annotations

import logging

from ._style import section

logger = logging.getLogger(__name__)


def _safe_wrap(label: str, anchor: str, html: str,
               *, sev: str = "info") -> str:
    if not html or not html.strip():
        return ""
    return section(label, html, sev=sev, anchor=anchor)


# ── Tier 1 (Sales-critical) ──────────────────────────────────────

def render_executive_summary(state: dict) -> str:
    """P82 GF-1-Pager + P1 Exec-Summary combined as 'Executive Summary'."""
    parts: list[str] = []
    req = state.get("req")
    try:
        from compliance.services.gf_one_pager import build_gf_one_pager_html
        html = build_gf_one_pager_html(
            site_name=state.get("site_name") or "",
            scorecard=state.get("scorecard") or {},
            previous_scorecard=state.get("prev_scorecard"),
            banner_result=state.get("banner_result"),
            library_mismatch_findings=state.get("mismatches") or [],
            scan_context=getattr(req, "scan_context", None) if req else None,
            audit_quality_findings=state.get("audit_quality_findings") or [],
        )
        if html and html.strip():
            parts.append(html)
    except Exception as e:
        logger.warning("gf_one_pager wrapper: %s", e)
    try:
        from compliance.api.agent_doc_check_exec_summary import (
            build_exec_summary_html,
        )
        html = build_exec_summary_html(
            scorecard=state.get("scorecard") or {},
            previous_scorecard=state.get("prev_scorecard"),
            cmp_vendors=state.get("cmp_vendors") or [],
            redundancy_report=state.get("redundancy_report"),
            site_name=state.get("site_name") or "",
        )
        if html and html.strip():
            parts.append(html)
    except Exception as e:
        logger.warning("exec_summary wrapper: %s", e)
    return _safe_wrap("💼 Executive Summary", "exec",
                       "".join(parts), sev="info")


def render_banner_screenshot(state: dict) -> str:
    """P85 — Banner-Screenshot as visual proof."""
    try:
        from compliance.services.banner_screenshot_block import (
            build_banner_screenshot_html,
        )
        html = build_banner_screenshot_html(state.get("banner_result"))
        return _safe_wrap("📸 Banner-Screenshot", "banner-shot",
                           html, sev="info")
    except Exception as e:
        logger.warning("banner_screenshot wrapper: %s", e)
        return ""


def render_vvt(state: dict) -> str:
    """VVT-Tabelle nach Art. 30 DSGVO — Verarbeitungstätigkeiten."""
    try:
        from compliance.api.agent_doc_check_extras import (
            build_vvt_table_html,
        )
        html = build_vvt_table_html(state.get("cmp_vendors") or [])
        return _safe_wrap("📋 VVT — Verarbeitungstätigkeiten (Art. 30 DSGVO)",
                           "vvt", html, sev="info")
    except Exception as e:
        logger.warning("vvt wrapper: %s", e)
        return ""


def render_redundancy(state: dict) -> str:
    """O4 — Vendor-Redundanz + EU-Alternativen + Cost-Savings."""
    try:
        from compliance.api.agent_doc_check_redundancy import (
            build_redundancy_html,
        )
        html = build_redundancy_html(state.get("redundancy_report"))
        return _safe_wrap("💰 Optimierungspotenzial (Redundanz / EU-Alt.)",
                           "redundancy", html, sev="warn")
    except Exception as e:
        logger.warning("redundancy wrapper: %s", e)
        return ""


def render_diff(state: dict) -> str:
    """P84 — Diff-Mode: Veränderung seit letztem Lauf."""
    try:
        from compliance.services.run_diff import (
            build_diff_block_html, compute_diff,
        )
        from database import SessionLocal
        db = SessionLocal()
        try:
            diff = compute_diff(
                db, state["check_id"], state.get("domain_for_exec") or "",
                state.get("banner_result"), state.get("scorecard"),
            )
            html = build_diff_block_html(diff) if diff else ""
        finally:
            db.close()
        return _safe_wrap("📊 Veränderung seit letztem Lauf",
                           "diff", html, sev="info")
    except Exception as e:
        logger.warning("diff wrapper: %s", e)
        return ""


def render_scope_disclaimer(state: dict) -> str:
    """P62 — Was wir prüfen, was wir nicht prüfen können."""
    try:
        from compliance.api.scope_disclaimer import build_scope_disclaimer_html
        html = build_scope_disclaimer_html()
        return _safe_wrap("🔍 Prüfumfang & Methodische Hinweise",
                           "scope", html, sev="info")
    except Exception as e:
        logger.warning("scope_disclaimer wrapper: %s", e)
        return ""


# ── Tier 2 (Audit-detail) ─────────────────────────────────────────

def render_banner_deep(state: dict) -> str:
    """Banner-Deep: Phases + Quality-Score + Per-Category-Tracker."""
    try:
        from compliance.api.agent_doc_check_banner import (
            build_banner_deep_html,
        )
        html = build_banner_deep_html(state.get("banner_result"))
        return _safe_wrap("🍪 Banner-Tiefenanalyse (Phasen + Kategorien)",
                           "banner-deep", html, sev="info")
    except Exception as e:
        logger.warning("banner_deep wrapper: %s", e)
        return ""


def render_cookie_audit(state: dict) -> str:
    """Cookie 3-Quellen-Audit (deklariert ↔ Browser ↔ Library)."""
    try:
        from compliance.services.cookie_compliance_audit import (
            build_cookie_audit_block_html,
        )
        html = build_cookie_audit_block_html(state.get("cookie_audit") or {})
        return _safe_wrap("🔬 Cookie-Audit (3-Quellen-Vergleich)",
                           "cookie-audit", html, sev="warn")
    except Exception as e:
        logger.warning("cookie_audit wrapper: %s", e)
        return ""


def render_solutions(state: dict) -> str:
    """P73 — LLM-Lösungsvorschläge pro HIGH-Fail."""
    try:
        from compliance.services.mc_solution_generator import (
            build_solutions_block_html,
        )
        html = build_solutions_block_html(state.get("mc_solutions") or [])
        return _safe_wrap("🎯 LLM-Lösungsvorschläge (P73)",
                           "solutions", html, sev="info")
    except Exception as e:
        logger.warning("solutions wrapper: %s", e)
        return ""


def render_cookie_architecture(state: dict) -> str:
    """P10 — Cookie-Policy-Architecture (BMW-Pattern, layered separation)."""
    try:
        from compliance.services.cookie_policy_architecture import (
            build_architecture_html,
        )
        html = build_architecture_html(state.get("cookie_architecture") or {})
        return _safe_wrap("🏗 Cookie-Policy-Architektur",
                           "cookie-arch", html, sev="info")
    except Exception as e:
        logger.warning("cookie_architecture wrapper: %s", e)
        return ""


def render_library_mismatch(state: dict) -> str:
    """P102 — Cookie-Klassifikations-Pruefung gegen Library."""
    try:
        from compliance.services.cookie_library_mismatch import (
            build_mismatch_block_html,
        )
        html = build_mismatch_block_html(state.get("mismatches") or [])
        return _safe_wrap("⚖️ Cookie-Klassifikation gegen Library (P102)",
                           "lib-mismatch", html, sev="warn")
    except Exception as e:
        logger.warning("library_mismatch wrapper: %s", e)
        return ""


def render_banner_consistency(state: dict) -> str:
    """P92/P94 — Banner-Konsistenz / CMP-Health."""
    try:
        from compliance.services.banner_consistency_checks import (
            build_consistency_block_html,
        )
        html = build_consistency_block_html(
            state.get("consistency_findings") or [])
        return _safe_wrap("🧩 Banner-Konsistenz + CMP-Health",
                           "banner-consistency", html, sev="warn")
    except Exception as e:
        logger.warning("banner_consistency wrapper: %s", e)
        return ""


def render_signals(state: dict) -> str:
    """P35/P77/P78 — Save-Label, Cookies-in-DSE, JC-Klausel."""
    try:
        from compliance.services.doc_text_signals import (
            build_signals_block_html,
        )
        html = build_signals_block_html(state.get("signal_findings") or [])
        return _safe_wrap("🚩 Doc-Text-Signale (P35/P77/P78)",
                           "signals", html, sev="info")
    except Exception as e:
        logger.warning("signals wrapper: %s", e)
        return ""


def render_scorecard_regulation(state: dict) -> str:
    """MC-Scorecard per Regulation (DSGVO/TDDDG/BGB-Split)."""
    try:
        from compliance.api.agent_doc_check_scorecard import (
            build_scorecard_html,
        )
        html = build_scorecard_html(
            state.get("scorecard") or {},
            previous_scorecard=state.get("prev_scorecard"),
        )
        return _safe_wrap("📊 Compliance-Scorecard pro Regulation",
                           "scorecard", html, sev="info")
    except Exception as e:
        logger.warning("scorecard wrapper: %s", e)
        return ""


def render_profile_html(state: dict) -> str:
    """Erkanntes Geschäftsmodell."""
    try:
        from compliance.api.agent_doc_check_report import build_profile_html
        html = build_profile_html(state.get("profile"))
        return _safe_wrap("🏢 Erkanntes Geschäftsmodell",
                           "profile", html, sev="info")
    except Exception as e:
        logger.warning("profile wrapper: %s", e)
        return ""


def render_input_warnings(state: dict) -> str:
    """Doc-Input-Warnings: User Text in falsches Feld gepastet."""
    try:
        from compliance.services.doc_input_warnings import (
            build_warnings_block_html,
        )
        warns = state.get("input_warnings") or []
        html = build_warnings_block_html(warns) if warns else ""
        return _safe_wrap("⚠️ Eingabe-Warnungen",
                           "input-warn", html, sev="warn")
    except Exception as e:
        logger.warning("input_warnings wrapper: %s", e)
        return ""


# ── Tier 3 (Cookie-deep + advisory) ───────────────────────────────

def render_entropy(state: dict) -> str:
    """P103 — Cookie-Value-Entropy."""
    try:
        from compliance.services.cookie_value_entropy import (
            build_entropy_block_html,
        )
        html = build_entropy_block_html(state.get("entropy_findings") or [])
        return _safe_wrap("🎲 Cookie-Entropy-Anomalien (P103)",
                           "entropy", html, sev="info")
    except Exception as e:
        logger.warning("entropy wrapper: %s", e)
        return ""


def render_network_trace(state: dict) -> str:
    """P104 — Network-Tracing."""
    try:
        from compliance.services.cookie_network_tracer import (
            build_network_trace_block_html,
        )
        html = build_network_trace_block_html(
            state.get("network_findings") or [])
        return _safe_wrap("🌐 Network-Tracing (P104)",
                           "network", html, sev="info")
    except Exception as e:
        logger.warning("network_trace wrapper: %s", e)
        return ""


def render_tcf_authority(state: dict) -> str:
    """P105 — IAB TCF Authority Cross-Reference."""
    try:
        from compliance.services.tcf_vendor_authority import (
            build_tcf_authority_block_html,
        )
        html = build_tcf_authority_block_html(
            state.get("tcf_authority_findings") or [])
        return _safe_wrap("🆔 IAB TCF Vendor Authority (P105)",
                           "tcf-auth", html, sev="info")
    except Exception as e:
        logger.warning("tcf_authority wrapper: %s", e)
        return ""


def render_jc_avv(state: dict) -> str:
    """P71 — JC-vs-AVV Entscheidungsbaum."""
    try:
        from compliance.services.jc_avv_decision import (
            build_jc_avv_decision_html,
        )
        html = build_jc_avv_decision_html(
            (state.get("doc_texts") or {}).get("dse"))
        return _safe_wrap("⚖️ Joint Controller vs. AVV — Entscheidung (P71)",
                           "jc-avv", html, sev="info")
    except Exception as e:
        logger.warning("jc_avv wrapper: %s", e)
        return ""


def render_industry_context(state: dict) -> str:
    """P6/53/55 — Branchen-Kontext + Site-History."""
    try:
        from compliance.services.industry_library import (
            build_industry_context_block_html,
        )
        ind = None
        req = state.get("req")
        if req and getattr(req, "scan_context", None):
            ind = req.scan_context.get("industry")
        html = build_industry_context_block_html(
            ind, state.get("site_profile"))
        return _safe_wrap("🏭 Branchen-Kontext + Historie",
                           "industry", html, sev="info")
    except Exception as e:
        logger.warning("industry_context wrapper: %s", e)
        return ""


def render_benchmark(state: dict) -> str:
    """P86 — Branchen-Benchmark."""
    try:
        from compliance.services.industry_benchmark import (
            build_benchmark_html,
        )
        html = build_benchmark_html(state.get("benchmark") or {})
        return _safe_wrap("📈 Branchen-Benchmark (P86)",
                           "bench", html, sev="info")
    except Exception as e:
        logger.warning("benchmark wrapper: %s", e)
        return ""


def render_scanned_urls(state: dict) -> str:
    """Quellen-Transparenz: welche URLs wurden gecrawlt."""
    try:
        from compliance.api.agent_doc_check_report import (
            build_scanned_urls_html,
        )
        html = build_scanned_urls_html(state.get("doc_entries") or [])
        return _safe_wrap("🔗 Geprüfte URLs (Quellen-Transparenz)",
                           "scanned-urls", html, sev="info")
    except Exception as e:
        logger.warning("scanned_urls wrapper: %s", e)
        return ""


def render_management_summary(state: dict) -> str:
    """Konkrete Aufgaben für die Geschäftsführung."""
    try:
        from compliance.api.agent_doc_check_report import (
            build_management_summary,
        )
        html = build_management_summary(state.get("results") or [])
        return _safe_wrap("📝 Management-Zusammenfassung",
                           "mgmt", html, sev="info")
    except Exception as e:
        logger.warning("management_summary wrapper: %s", e)
        return ""


# ── Render the whole legacy block region ────────────────────────

def render_all_legacy(state: dict) -> str:
    """Render every legacy block in the canonical order."""
    return "".join([
        # Tier 1 (Sales)
        render_executive_summary(state),
        render_diff(state),
        render_solutions(state),
        render_redundancy(state),
        render_vvt(state),
        render_banner_screenshot(state),
        # Tier 2 (Audit-detail)
        render_scorecard_regulation(state),
        render_banner_deep(state),
        render_banner_consistency(state),
        render_cookie_audit(state),
        render_cookie_architecture(state),
        render_library_mismatch(state),
        render_signals(state),
        render_profile_html(state),
        render_input_warnings(state),
        # Tier 3 (advisory)
        render_entropy(state),
        render_network_trace(state),
        render_tcf_authority(state),
        render_jc_avv(state),
        render_industry_context(state),
        render_benchmark(state),
        render_scanned_urls(state),
        render_management_summary(state),
        # Scope-Disclaimer last — footer-ish
        render_scope_disclaimer(state),
    ])
