"""Thin orchestrator — runs the 6 phases of the compliance check.

The original `_run_compliance_check` was a 1620-line monolith. It is
now decomposed into six phases (A=resolve, B=profile+check,
C=banner+extract, D=report-build [D1 raw vendors, D2 finalize,
D3-top/mid/bot blocks], E=email, F=persist), each in its own module.

State flows through a single mutable `dict` (see `_state.new_state`).
This intentionally trades type safety for additive flexibility: the
report-building phase routinely adds new optional keys for each new
HTML block, and a typed dataclass would freeze the schema before the
new blocks could land.
"""

from __future__ import annotations

import logging

from ._agent_outputs import run_agent_outputs
from ._b1_wiring import run_b1
from ._b3_wiring import run_b3
from ._b4_wiring import run_b4
from ._b5_wiring import run_b5
from ._b6b7b8_wiring import run_b6b7b8
from ._b9b10_wiring import run_b9b10
from ._b12_wiring import run_b12
from ._b13_wiring import run_b13
from ._b14_wiring import run_b14
from ._b15_wiring import run_b15
from ._b16_wiring import run_b16
from ._b17_wiring import run_b17
from ._b18_wiring import run_b18
from ._b19_wiring import run_b19
from ._b20_wiring import run_b20
from ._b22_wiring import run_b22
from ._constants import _compliance_check_jobs
from ._sse import emit
from ._phase_a_resolve import run_phase_a
from ._phase_b_profile_check import run_phase_b
from ._phase_c_banner import run_phase_c
from ._phase_c2_browser_matrix import run_phase_c2
from ._phase_d1_vendors_raw import run_phase_d1
from ._phase_d2_vendors_finalize import run_phase_d2
from ._phase_d2b_plausibility import run_phase_d2b
from ._phase_d3_blocks_bot import run_phase_d3_bot
from ._phase_d3_blocks_mid import run_phase_d3_mid
from ._phase_d3_blocks_top import run_phase_d3_top
from ._phase_e_email import run_phase_e
from ._phase_f_persist import run_phase_f
from ._state import new_state
from compliance.services.chatbot_policy_discovery import (
    enrich_dse_with_chatbot_policies,
)

logger = logging.getLogger(__name__)


async def run_compliance_check(check_id: str, req) -> None:
    """Background task: check all documents with business-profile context."""
    state = new_state(check_id, req)
    try:
        # Phase A: TDM gate + Step 1 (resolve / discover / split / dedup)
        continue_run = await run_phase_a(state)
        if not continue_run:
            return  # TDM denied — job already marked skipped_tdm
        # DSE-Enrichment: Sub-Chatbot-Policies anhängen (Westfield-iAdvize,
        # vergleichbare Pattern). Best-effort, läuft VOR Phase B damit
        # die enrichte DSE in alle per-doc-checks fließt.
        try:
            await enrich_dse_with_chatbot_policies(state)
        except Exception as e:
            logger.warning("chatbot-policy enrichment skipped: %s", e)
        # Phase B: Step 2 (profile detect) + Step 3 (per-doc checks)
        await run_phase_b(state)
        # Strukturierter v3-AgentOutput pro Thema — früh (Impressum-Text +
        # Profil liegen vor) → SSE topic-Event, Tab erscheint progressiv,
        # während Banner/Vendor/B-Wirings noch laufen. Additiv zu B18.
        await run_agent_outputs(state)
        # Phase C: Step 3b-d (banner + cross-check + TCF) + Step 4
        await run_phase_c(state)
        # Phase C-2: optional browser-matrix scan (env BROWSER_MATRIX=true)
        await run_phase_c2(state)
        # Phase D-1/D-2: Step 5 vendor extraction + finalize
        await run_phase_d1(state)
        await run_phase_d2(state)
        # D-2b: LLM Plausibility Re-Eval — stamps llm_* on all FAIL checks
        await run_phase_d2b(state)
        # B1 + B3: cross-cutting checks that need the finalized vendor
        # list + DSI text. Render their own HTML blocks consumed by
        # phase D-3 bot's full_html composition.
        await run_b1(state)
        run_b3(state)
        run_b4(state)  # Cross-doc vendor-consistency (Elli Vertex↔Iadvize)
        run_b5(state)  # AI-Act Art. 50 transparency
        run_b6b7b8(state)  # DPO-cross-doc + Doc-Staleness + CMP-fingerprint
        run_b9b10(state)  # Multi-Entity-Impressum + Drittland-Mechanismus
        run_b12(state)  # Chatbot-Cookie-Klassifikation (B11 ist in B9B10)
        run_b13(state)  # Widerrufsbelehrung-Reachability (B2C-Pflicht)
        run_b14(state)  # Widersprüchliche Speicherdauer im selben Doc
        run_b15(state)  # AI-Act Rechtsgrundlage (LLM-Vendor auf lit. f)
        run_b16(state)  # Footer-Label-vs-URL-Slug-Drift
        await run_b17(state)  # Audit-Walk-Video (Beweis-Aufzeichnung)
        await run_b18(state)  # Impressum-Specialist-Agent (Pattern+LLM)
        run_b19(state)  # Cookie-Coherence (Salesforce-as-essential)
        await run_b20(state)  # Legacy-URL-Discovery (Sitemap+Wayback)
        run_b22(state)  # Cross-Domain-Legal-Doc-Hosting (Elli/LogPay)
        # Phase D-3 top/mid/bot: Step 5 HTML blocks
        await run_phase_d3_top(state)
        await run_phase_d3_mid(state)
        await run_phase_d3_bot(state)
        # Phase E: Step 6 send mail (with A1 ZIP attachment)
        run_phase_e(state)
        # Phase F: Step 7 persist + audit log + unified findings
        run_phase_f(state)
        emit(check_id, {"type": "complete", "status": "completed"})
    except Exception as e:
        logger.error("Compliance check %s failed: %s",
                     check_id, e, exc_info=True)
        _compliance_check_jobs[check_id]["status"] = "failed"
        _compliance_check_jobs[check_id]["error"] = str(e)[:500]
        emit(check_id, {"type": "error", "error": str(e)[:300]})
