"""Phase F — Build response + persist snapshot/audit-log/unified-findings.

Covers (in the original `_run_compliance_check`):
  - Step 7   Build response dict, mark job as completed
  - P80      Persist raw scan data so we can replay the audit pipeline
             without re-crawling (7min → 5sec test cycle)
  - SQLite audit log (compliance.api/audit endpoints + trend view A6)
  - P5       Unified findings (MC + Pflichtangaben + Vendor + Redundanz
             in one searchable table behind /agent/findings/<id>)
"""

from __future__ import annotations

import logging
from datetime import datetime, timezone

from ._constants import _compliance_check_jobs
from ._helpers import _result_to_dict

logger = logging.getLogger(__name__)


def run_phase_f(state: dict) -> None:
    """Build response + persist. Mutates state in place."""
    check_id = state["check_id"]
    req = state["req"]
    results = state["results"]
    profile = state["profile"]
    profile_dict = state["profile_dict"]
    extracted_profile = state["extracted_profile"]
    banner_result = state["banner_result"]
    tcf_vendors = state["tcf_vendors"]
    vvt_entries = state["vvt_entries"]
    cmp_vendors = state["cmp_vendors"]
    cookie_audit = state["cookie_audit"]
    total_findings = state["total_findings"]
    email_result = state["email_result"]
    doc_entries = state["doc_entries"]
    doc_texts = state["doc_texts"]
    redundancy_report = state.get("redundancy_report")
    scorecard = state["scorecard"]
    site_name = state.get("site_name", "")
    domain = state.get("domain", "")
    doc_count = state.get("doc_count", 0)

    response = {
        "check_id": check_id,
        "results": [_result_to_dict(r) for r in results],
        "business_profile": profile_dict,
        "extracted_profile": extracted_profile,
        # P18: vollen consent-tester-Output durchreichen statt nur 4 Felder.
        # phases (before/after-accept/reject) + banner_checks.violations +
        # category_tests werden vom Renderer + Critical-Findings-Block genutzt.
        "banner_result": ({
            "detected": banner_result.get("banner_detected", False),
            "provider": banner_result.get("banner_provider", ""),
            "violations": len((banner_result.get("banner_checks") or {})
                              .get("violations", [])),
            "tcf_vendor_count": len(tcf_vendors),
            "completeness_pct": banner_result.get("completeness_pct"),
            "correctness_pct": banner_result.get("correctness_pct"),
            "phases": banner_result.get("phases", {}),
            "banner_checks": banner_result.get("banner_checks", {}),
            "category_tests": banner_result.get("category_tests", []),
            "structured_checks": banner_result.get("structured_checks", []),
            "summary": banner_result.get("summary", {}),
        } if banner_result else None),
        "tcf_vendors": vvt_entries if tcf_vendors else [],
        "cmp_vendors": cmp_vendors,
        "cookie_audit": cookie_audit if cookie_audit else None,
        "total_documents": len(results),
        "total_findings": total_findings,
        "email_status": email_result.get("status", "failed"),
        "checked_at": datetime.now(timezone.utc).isoformat(),
        # P125: B-Wiring-Output (B1, B3-B17) ins API-Response-Payload.
        # Bisher landeten diese nur im Audit-Mail-HTML — externe Aufrufer
        # (Admin-UI) sahen sie nicht. Schema additiv; legacy clients
        # ignorieren unbekannte Felder.
        "extra_findings": state.get("extra_findings") or [],
        "audit_walk": state.get("audit_walk") or None,
        "html_blocks": {
            "widerruf_reach": state.get("widerruf_reach_html", ""),
            "retention_conflict": state.get("retention_conflict_html", ""),
            "ai_legal_basis": state.get("ai_legal_basis_html", ""),
            "url_slug_drift": state.get("url_slug_drift_html", ""),
            "chatbot_cookie": state.get("chatbot_cookie_html", ""),
            "audit_walk": state.get("audit_walk_html", ""),
            "browser_matrix": state.get("browser_matrix_html", ""),
            "vendor_consistency": state.get("vendor_consistency_html", ""),
            "ai_act": state.get("ai_act_html", ""),
            "impressum_agent": state.get("impressum_agent_html", ""),
            "cookie_coherence": state.get("cookie_coherence_html", ""),
            "legacy_urls": state.get("legacy_url_html", ""),
        },
        "legacy_url_inventory": state.get("legacy_url_inventory") or None,
        # Strukturierter v3-AgentOutput pro Thema (impressum, …) für die
        # standardisierten Ergebnis-Tabs im Frontend. Additiv; legacy
        # clients ignorieren unbekannte Felder.
        "agent_outputs": state.get("agent_outputs") or {},
    }

    _compliance_check_jobs[check_id]["status"] = "completed"
    _compliance_check_jobs[check_id]["result"] = response
    _compliance_check_jobs[check_id]["progress"] = "Fertig"
    _compliance_check_jobs[check_id]["progress_pct"] = 100

    # P80: persist raw scan data so we can replay audit pipeline
    # without re-crawling (7min -> 5sec test cycle).
    try:
        from database import SessionLocal
        from compliance.services.check_snapshot import save_snapshot
        snap_db = SessionLocal()
        try:
            save_snapshot(
                snap_db,
                check_id=check_id,
                doc_entries=doc_entries,
                banner_result=banner_result,
                profile=profile,
                cmp_vendors=cmp_vendors,
                scan_context=req.scan_context,  # P79
                site_label=site_name,
                notes=f"recipient={req.recipient}",
            )
        finally:
            snap_db.close()
    except Exception as snap_err:
        logger.warning("P80 snapshot save skipped: %s", snap_err)

    # Persist to sidecar SQLite audit log — enables /audit endpoints
    # (A5 admin tab) and trend view (A6). Best-effort; failures here
    # do not affect the user-facing response.
    try:
        from compliance.services.compliance_audit_log import record_check_run
        from compliance.services.mc_scorecard import full_audit_records
        audit_rows: list[dict] = []
        for r in results:
            doc_mc = [c for c in r.checks if c.id.startswith("mc-")]
            audit_rows.extend(full_audit_records(
                [{"id": c.id, "label": c.label, "passed": c.passed,
                  "severity": c.severity, "skipped": c.skipped,
                  "regulation": c.regulation, "matched_text": c.matched_text,
                  "hint": c.hint, "level": c.level}
                 for c in doc_mc],
                check_id=check_id,
                doc_type=r.doc_type,
            ))
        record_check_run(
            check_id=check_id,
            tenant_id=req.recipient or "",
            site_name=site_name,
            base_domain=domain or "",
            doc_count=doc_count,
            scorecard=scorecard,
            vvt_summary={
                "total": len(cmp_vendors),
                "internal": sum(1 for v in cmp_vendors
                                if (v.get("recipient_type") or "").upper()
                                in ("INTERNAL", "GROUP_COMPANY")),
                "external": sum(1 for v in cmp_vendors
                                if (v.get("recipient_type") or "").upper()
                                in ("PROCESSOR", "CONTROLLER")),
            },
            mc_records=audit_rows,
        )
        from compliance.services.compliance_audit_log import record_check_payload
        record_check_payload(
            check_id=check_id,
            vendors=cmp_vendors,
            profile=extracted_profile,
            banner=banner_result,
        )
        # Unified findings (P5): bundle MC + Pflichtangaben + Vendor +
        # Redundanz in one searchable table behind /agent/findings/<id>.
        try:
            from compliance.services.unified_findings_collector import collect
            from compliance.services.unified_findings_store import record_findings
            unified = collect(
                check_id=check_id,
                results=results,
                cmp_vendors=cmp_vendors,
                redundancy_report=redundancy_report,
                doc_texts=doc_texts,
            )
            record_findings(check_id, unified)
        except Exception as e:
            logger.warning("Unified findings collect failed: %s", e)
    except Exception as e:
        logger.warning("Audit persistence skipped: %s", e)

    state["response"] = response
