"""Phase D-2b — LLM Plausibility Re-Eval over all MC findings.

Runs AFTER vendor finalize and BEFORE D3 HTML blocks. Stamps the
`llm_title` / `llm_severity` / `llm_recommendation` / `llm_drop`
fields onto every FAIL CheckItem. The V2 mail renderer reads these
fields automatically — no further wiring needed.

Opt-out via env var `PLAUSIBILITY_DISABLED=true` (e.g. for CI runs
where the LLM endpoint isn't reachable).
"""

from __future__ import annotations

import logging
import os

from ._helpers import _update

logger = logging.getLogger(__name__)


async def run_phase_d2b(state: dict) -> None:
    """Run the plausibility re-eval over state["results"]. Mutates checks."""
    if os.environ.get("PLAUSIBILITY_DISABLED", "false").lower() in (
        "true", "1", "yes",
    ):
        logger.info("plausibility-check disabled by env")
        return
    check_id = state["check_id"]
    results = state.get("results") or []
    doc_texts = state.get("doc_texts") or {}
    if not results:
        return
    _update(check_id, "LLM-Plausibilitäts-Check über alle Findings...", 94)
    try:
        from compliance.services.finding_plausibility_check import (
            verify_plausibility,
        )
        await verify_plausibility(results, doc_texts)
    except Exception as e:
        logger.warning("plausibility-phase failed (continuing): %s", e)
