"""Phase D-3-Top — Top-of-mail HTML blocks.

Covers (in the original Step 5 of `_run_compliance_check`):
  - Summary / Scanned-URLs / Provider-list / Banner-deep / VVT HTML
  - MC-scorecard aggregation (all_mc_checks + scorecard) + trend lookup
  - P106 mc_audit_type split (internal_checks vs. verifiable_fails)
  - Profile HTML / Redundancy HTML
  - P1 Executive Summary
  - P18 Critical Findings block
  - P10 Cookie-Policy-Architecture detection
"""

from __future__ import annotations

import logging

from ._helpers import _build_profile_html, _company_name_from_url, _extract_domain

logger = logging.getLogger(__name__)


async def run_phase_d3_top(state: dict) -> None:
    """Top-of-mail HTML blocks. Mutates state in place."""
    req = state["req"]
    results = state["results"]
    doc_entries = state["doc_entries"]
    doc_texts = state["doc_texts"]
    banner_result = state["banner_result"]
    vvt_entries = state["vvt_entries"]
    cmp_vendors = state["cmp_vendors"]
    profile = state["profile"]
    redundancy_report = state.get("redundancy_report")

    from ..agent_doc_check_banner import build_banner_deep_html
    from ..agent_doc_check_critical import build_critical_findings_html
    from ..agent_doc_check_exec_summary import build_exec_summary_html
    from ..agent_doc_check_extras import build_vvt_table_html
    from ..agent_doc_check_redundancy import build_redundancy_html
    from ..agent_doc_check_report import (
        build_html_report,
        build_management_summary,
        build_provider_list_html,
        build_scanned_urls_html,
    )
    from ..agent_doc_check_scorecard import build_scorecard_html
    from compliance.services.mc_scorecard import build_scorecard

    summary_html = build_management_summary(results)
    scanned_html = build_scanned_urls_html(doc_entries)
    providers_html = build_provider_list_html(banner_result, vvt_entries)
    # P18: Deep-Block mit Phases + Quality-Score + Per-Category-Tracker
    banner_deep_html = build_banner_deep_html(banner_result)
    vvt_html = build_vvt_table_html(cmp_vendors)

    # MC scorecard aggregated across ALL docs (DSGVO/TDDDG/BGB/...)
    all_mc_checks: list[dict] = []
    fails_by_doc: dict[str, list[dict]] = {}
    for r in results:
        for c in r.checks:
            if c.id.startswith("mc-"):
                rec = {
                    "id": c.id, "label": c.label, "passed": c.passed,
                    "severity": c.severity, "skipped": c.skipped,
                    "regulation": c.regulation,
                    "hint": getattr(c, "hint", "") or "",
                }
                all_mc_checks.append(rec)
                if (not c.passed and not c.skipped
                        and (c.severity or "").upper() in ("CRITICAL", "HIGH")):
                    fails_by_doc.setdefault(r.doc_type, []).append(rec)
    # P106 — Audit-Type-Klassifizierung pro MC
    mc_split: dict = {"internal_checks": [], "verifiable_fails": all_mc_checks}
    try:
        from compliance.services.mc_audit_type import (
            annotate_mc_results, split_by_audit_type,
        )
        annotate_mc_results(all_mc_checks)
        mc_split = split_by_audit_type(all_mc_checks)
        fails_by_doc = {}
        for r in mc_split.get("verifiable_fails") or []:
            fails_by_doc.setdefault("dse", []).append(r)
    except Exception as e:
        logger.warning("P106 mc_audit_type skipped: %s", e)
    scorecard = build_scorecard(all_mc_checks) if all_mc_checks else {}

    # Trend: load previous scorecard for the same tenant + domain
    prev_scorecard: dict | None = None
    if scorecard:
        try:
            from compliance.services.compliance_audit_log import (
                list_runs_for_tenant,
            )
            tenant_id_for_trend = req.recipient or ""
            base_domain_for_trend = _extract_domain(doc_entries) or ""
            prev_runs = list_runs_for_tenant(
                tenant_id_for_trend,
                base_domain=base_domain_for_trend,
                limit=1,
            )
            if prev_runs:
                prev_scorecard = prev_runs[0].get("scorecard")
        except Exception as e:
            logger.debug("trend lookup skipped: %s", e)
    scorecard_html = (
        build_scorecard_html(scorecard, previous_scorecard=prev_scorecard)
        if scorecard else ""
    )

    report_html = build_html_report(results, None, doc_texts)
    profile_html = _build_profile_html(profile)

    # O4: Vendor-Redundanz / EU-Alternativen + Cost-Savings-Block
    redundancy_html = build_redundancy_html(redundancy_report)

    # P1: Executive-Summary
    url_company_for_exec = _company_name_from_url(doc_entries)
    domain_for_exec = _extract_domain(doc_entries)
    site_name_for_exec = url_company_for_exec or domain_for_exec or ""
    exec_summary_html = build_exec_summary_html(
        scorecard=scorecard,
        previous_scorecard=prev_scorecard,
        cmp_vendors=cmp_vendors,
        redundancy_report=redundancy_report,
        site_name=site_name_for_exec,
    )

    # P18: Critical-Findings-Block
    critical_html = ""
    try:
        critical_html = build_critical_findings_html(
            banner_result=banner_result,
            scorecard=scorecard,
            results=results,
        )
    except Exception as e:
        logger.warning("Critical-findings block skipped: %s", e)

    # P10: Cookie-Policy-Architecture-Detection (BMW-Pattern erkennen)
    cookie_arch_html = ""
    try:
        from compliance.services.cookie_policy_architecture import (
            build_architecture_html,
            detect_architecture,
        )
        cookie_doc_url = ""
        cookie_doc_text = doc_texts.get("cookie", "")
        cookie_cmp_payloads: list[dict] = []
        for e in doc_entries:
            if (e.get("doc_type") or "").lower() in ("cookie", "cookie_policy"):
                cookie_doc_url = e.get("url", "")
                cookie_cmp_payloads = e.get("cmp_payloads") or []
                break
        # P17-A: Fallback wenn Cookie-Doc via P15 deduped wurde
        if not cookie_doc_text:
            dse_text = doc_texts.get("dse", "")
            if dse_text and any(w in dse_text.lower() for w in
                                 ("cookie", "tracking", "google analytics",
                                  "consent")):
                cookie_doc_text = dse_text
                dse_entry = next((e for e in doc_entries
                                  if e.get("doc_type") == "dse"), {})
                cookie_doc_url = dse_entry.get("url", "")
                cookie_cmp_payloads = dse_entry.get("cmp_payloads") or []
                logger.info("P17-A: cookie-arch fallback auf DSE")
        if cookie_doc_text:
            arch = detect_architecture(
                doc_url=cookie_doc_url,
                doc_text=cookie_doc_text,
                cmp_payloads=cookie_cmp_payloads,
                homepage_cmp_payloads=state.get("cookie_payloads") or [],
            )
            cookie_arch_html = build_architecture_html(arch)
            logger.info("cookie-arch: layer=%s versioned=%s risk=%s",
                        arch["layer_separation"], arch["versioned"],
                        arch["risk_label"])
    except Exception as e:
        logger.warning("cookie-architecture detection failed: %s", e)

    state["scorecard"] = scorecard
    state["prev_scorecard"] = prev_scorecard
    state["mc_split"] = mc_split
    state["fails_by_doc"] = fails_by_doc
    state["site_name_for_exec"] = site_name_for_exec
    state["domain_for_exec"] = domain_for_exec
    state["html_blocks"] = {
        "summary_html": summary_html,
        "scanned_html": scanned_html,
        "providers_html": providers_html,
        "banner_deep_html": banner_deep_html,
        "vvt_html": vvt_html,
        "scorecard_html": scorecard_html,
        "report_html": report_html,
        "profile_html": profile_html,
        "redundancy_html": redundancy_html,
        "exec_summary_html": exec_summary_html,
        "critical_html": critical_html,
        "cookie_arch_html": cookie_arch_html,
    }
