"""AI Agent report truth and alert actionability review snapshot."""

from __future__ import annotations

import json
import re
from pathlib import Path
from typing import Any

from src.services.snapshot_paths import (
    default_evaluations_dir,
    default_security_dir,
    resolve_repo_root,
)

_DEFAULT_EVALUATIONS_DIR = default_evaluations_dir(Path(__file__))
_DEFAULT_SECURITY_DIR = default_security_dir(Path(__file__))
_SNAPSHOT_PATTERN = "ai_agent_report_truth_actionability_review_*.json"
_TELEGRAM_EGRESS_GUARD_SNAPSHOT = "telegram-notification-egress-no-new-bypass-guard.snapshot.json"
_SCHEMA_VERSION = "ai_agent_report_truth_actionability_review_v1"
_GUARDED_BOT_METHODS = (
    "sendMessage",
    "sendDocument",
    "sendPhoto",
    "sendMediaGroup",
    "editMessageText",
    "sendAnimation",
    "sendVideo",
    "sendAudio",
    "sendVoice",
)
_BOT_ENDPOINT_RE = re.compile(
    r"api\.telegram\.org/bot.*?/(?P<method>"
    + "|".join(re.escape(method) for method in _GUARDED_BOT_METHODS)
    + r")\b",
    re.IGNORECASE,
)
_SECRET_INTERPOLATION_RE = re.compile(r"\$\{\{\s*secrets\.[^}]+\}\}")
_BOT_TOKEN_URL_RE = re.compile(
    r"api\.telegram\.org/bot.*?/(?P<method>"
    + "|".join(re.escape(method) for method in _GUARDED_BOT_METHODS)
    + r")\b",
    re.IGNORECASE,
)
_TELEGRAM_EGRESS_SCAN_SUFFIXES = {".py", ".sh", ".js", ".yml", ".yaml"}


def load_latest_ai_agent_report_truth_actionability_review(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed report truth and actionability review."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(
            f"no AI Agent report truth actionability review snapshots found in {directory}"
        )

    latest = candidates[-1]
    with latest.open(encoding="utf-8") as handle:
        payload = json.load(handle)

    if not isinstance(payload, dict):
        raise ValueError(f"{latest}: expected JSON object")
    _require_schema(payload, str(latest))
    _require_runtime_boundaries(payload, str(latest))
    _require_findings(payload, str(latest))
    _require_source_and_actionability_gates(payload, str(latest))
    _require_telegram_routing(payload, str(latest))
    _require_rollup_consistency(payload, str(latest))
    return _with_live_telegram_egress_guard(payload)


def _with_live_telegram_egress_guard(payload: dict[str, Any]) -> dict[str, Any]:
    """Attach current Telegram direct-egress guard evidence for UI/API readback."""
    updated = json.loads(json.dumps(payload, ensure_ascii=False))
    guard = _load_telegram_egress_guard_snapshot()
    live_calls = _scan_current_direct_telegram_endpoints(resolve_repo_root(Path(__file__)))
    summary = guard.get("summary") if isinstance(guard.get("summary"), dict) else {}
    live_files = sorted({str(item.get("path")) for item in live_calls if item.get("path")})
    new_bypass_count = int(summary.get("new_bypass_count") or 0)
    surface_counts = _telegram_direct_surface_counts(live_calls)
    receipt_missing_count = sum(
        1 for item in live_calls if item.get("receipt_state") != "awooop_outbound_receipt_recorded"
    )
    ai_route_missing_count = sum(
        1 for item in live_calls if item.get("ai_controlled_route_state") != "ai_controlled_gateway_route_ready"
    )
    ai_agent_next_action = (
        "create_controlled_migration_work_items_for_direct_bot_api_routes_with_db_receipt_"
        "verifier_and_km_playbook_writeback"
        if live_calls
        else "bind_gateway_alert_cards_to_learning_writeback_receipts"
    )

    updated["telegram_egress_guard"] = {
        "schema_version": "telegram_notification_egress_no_new_bypass_guard_v1",
        "status": guard.get("status", "unknown"),
        "mode": "repo_source_scan_no_secret_value_no_telegram_send",
        "source_snapshot": _TELEGRAM_EGRESS_GUARD_SNAPSHOT,
        "guarded_roots": guard.get("guarded_roots", []),
        "guarded_bot_methods": list(_GUARDED_BOT_METHODS),
        "summary": {
            **summary,
            "live_direct_bot_api_call_count": len(live_calls),
            "live_direct_bot_api_file_count": len(live_files),
            "live_scan_matches_committed_guard_count": (
                len(live_calls) == int(summary.get("current_direct_bot_api_call_count") or -1)
            ),
            "gitea_workflow_direct_bot_api_call_count": surface_counts.get(
                "gitea_workflow_direct_bot_api", 0
            ),
            "ops_script_direct_bot_api_call_count": surface_counts.get(
                "ops_script_direct_bot_api", 0
            ),
            "ci_script_direct_bot_api_call_count": surface_counts.get("ci_script_direct_bot_api", 0),
            "api_direct_bot_api_call_count": surface_counts.get("api_direct_bot_api", 0),
            "direct_bot_api_awooop_db_receipt_count": len(live_calls) - receipt_missing_count,
            "direct_bot_api_awooop_db_receipt_missing_count": receipt_missing_count,
            "direct_bot_api_ai_controlled_route_count": len(live_calls) - ai_route_missing_count,
            "direct_bot_api_ai_controlled_route_missing_count": ai_route_missing_count,
        },
        "telegram_receipt_coverage": {
            "coverage_status": "partial_gateway_receipts_direct_routes_missing"
            if live_calls
            else "complete_no_direct_routes_detected",
            "gateway_alert_notification_db_receipt_enabled": True,
            "gateway_alert_notification_receipt_source": "TelegramGateway.send_alert_notification",
            "direct_bot_api_total_count": len(live_calls),
            "direct_bot_api_awooop_db_receipt_count": len(live_calls) - receipt_missing_count,
            "direct_bot_api_awooop_db_receipt_missing_count": receipt_missing_count,
            "direct_bot_api_ai_controlled_route_count": len(live_calls) - ai_route_missing_count,
            "direct_bot_api_ai_controlled_route_missing_count": ai_route_missing_count,
            "all_direct_routes_have_awooop_db_receipt": receipt_missing_count == 0,
            "all_direct_routes_have_ai_controlled_route": ai_route_missing_count == 0,
            "all_telegram_alerts_have_db_or_log_receipts": receipt_missing_count == 0,
            "all_telegram_alerts_ai_controlled": ai_route_missing_count == 0,
            "evidence_persistence_states": sorted(
                {
                    str(item.get("evidence_persistence_state"))
                    for item in live_calls
                    if item.get("evidence_persistence_state")
                }
            ),
            "ai_agent_next_action": ai_agent_next_action,
        },
        "current_direct_bot_api_calls": live_calls,
        "ai_agent_interpretation": {
            "no_new_bypass": new_bypass_count == 0,
            "existing_direct_routes_need_migration": len(live_calls) > 0,
            "db_receipt_required": True,
            "ai_controlled_route_required": True,
            "all_direct_routes_have_awooop_db_receipt": receipt_missing_count == 0,
            "all_direct_routes_have_ai_controlled_route": ai_route_missing_count == 0,
            "manual_default_outcome_allowed": False,
            "next_action": (
                "migrate_direct_bot_api_calls_to_awoooi_api_or_telegram_gateway_receipts"
                if live_calls
                else "bind_gateway_alert_cards_to_learning_writeback_receipts"
            ),
        },
    }

    routes = list(updated.get("telegram_route_findings") or [])
    existing_route_ids = {str(item.get("route_id")) for item in routes if isinstance(item, dict)}
    for item in live_calls:
        route = _telegram_direct_call_route_finding(item)
        if route["route_id"] in existing_route_ids:
            continue
        routes.append(route)
        existing_route_ids.add(route["route_id"])
    updated["telegram_route_findings"] = routes
    _sync_telegram_route_rollups(updated)
    return updated


def _load_telegram_egress_guard_snapshot() -> dict[str, Any]:
    path = _DEFAULT_SECURITY_DIR / _TELEGRAM_EGRESS_GUARD_SNAPSHOT
    if not path.exists():
        return {}
    with path.open(encoding="utf-8") as handle:
        payload = json.load(handle)
    return payload if isinstance(payload, dict) else {}


def _telegram_egress_scan_roots(root: Path) -> list[Path]:
    guard = _load_telegram_egress_guard_snapshot()
    roots = guard.get("guarded_roots") if isinstance(guard.get("guarded_roots"), list) else []
    if not roots:
        roots = [".gitea/workflows", "scripts/ops", "scripts/ci", "apps/api/src"]
    return [root / str(path) for path in roots]


def _sanitize_telegram_egress_excerpt(line: str) -> str:
    excerpt = line.strip()
    excerpt = _SECRET_INTERPOLATION_RE.sub("${{ secrets.<redacted> }}", excerpt)
    excerpt = _BOT_TOKEN_URL_RE.sub(
        lambda match: f"api.telegram.org/bot<redacted>/{match.group('method')}",
        excerpt,
    )
    return excerpt[:180]


def _telegram_direct_surface_kind(relative_path: str) -> str:
    if relative_path.startswith(".gitea/workflows/"):
        return "gitea_workflow_direct_bot_api"
    if relative_path.startswith("scripts/ops/"):
        return "ops_script_direct_bot_api"
    if relative_path.startswith("scripts/ci/"):
        return "ci_script_direct_bot_api"
    if relative_path.startswith("apps/api/src/"):
        return "api_direct_bot_api"
    return "unknown_direct_bot_api"


def _telegram_direct_persistence_state(surface_kind: str) -> str:
    if surface_kind == "gitea_workflow_direct_bot_api":
        return "gitea_actions_log_only_no_awooop_db_receipt"
    if surface_kind == "ops_script_direct_bot_api":
        return "host_script_stdout_only_no_awooop_db_receipt"
    if surface_kind == "ci_script_direct_bot_api":
        return "ci_script_log_only_no_awooop_db_receipt"
    if surface_kind == "api_direct_bot_api":
        return "api_direct_send_no_awooop_outbound_receipt_contract"
    return "direct_send_no_awooop_outbound_receipt_contract"


def _telegram_direct_surface_counts(calls: list[dict[str, Any]]) -> dict[str, int]:
    counts: dict[str, int] = {}
    for item in calls:
        surface_kind = str(item.get("surface_kind") or "unknown_direct_bot_api")
        counts[surface_kind] = counts.get(surface_kind, 0) + 1
    return counts


def _scan_current_direct_telegram_endpoints(root: Path) -> list[dict[str, Any]]:
    findings: list[dict[str, Any]] = []
    for scan_root in _telegram_egress_scan_roots(root):
        if not scan_root.exists():
            continue
        for path in sorted(scan_root.rglob("*")):
            if not path.is_file() or path.suffix not in _TELEGRAM_EGRESS_SCAN_SUFFIXES:
                continue
            relative_path = path.relative_to(root).as_posix()
            text = path.read_text(encoding="utf-8", errors="replace")
            for line_number, line in enumerate(text.splitlines(), start=1):
                for match in _BOT_ENDPOINT_RE.finditer(line):
                    surface_kind = _telegram_direct_surface_kind(relative_path)
                    findings.append(
                        {
                            "path": relative_path,
                            "line": line_number,
                            "method": match.group("method"),
                            "surface_kind": surface_kind,
                            "sanitized_excerpt": _sanitize_telegram_egress_excerpt(line),
                            "receipt_state": "missing_awooop_outbound_receipt_contract",
                            "evidence_persistence_state": _telegram_direct_persistence_state(
                                surface_kind
                            ),
                            "ai_controlled_route_state": "missing_ai_controlled_gateway_route",
                        }
                    )
    return findings


def _telegram_direct_call_route_finding(item: dict[str, Any]) -> dict[str, str]:
    path = str(item.get("path") or "unknown")
    line = int(item.get("line") or 0)
    method = str(item.get("method") or "sendMessage")
    surface_kind = str(item.get("surface_kind") or "unknown_direct_bot_api")
    route_key = re.sub(r"[^a-z0-9]+", "_", f"{path}_{line}_{method}".lower()).strip("_")
    return {
        "route_id": f"telegram_direct_bot_api_{route_key}",
        "display_name": f"Direct Bot API {method} · {path}:{line}",
        "source": f"{path}:{line}",
        "current_state": "direct_send_path_present",
        "target_state": "gateway_db_receipt_required",
        "risk": (
            f"{surface_kind} 不保證寫入 awooop_outbound_message 或 AI controlled route；"
            f"sanitized excerpt: {item.get('sanitized_excerpt', '')}"
        ),
        "required_fix": (
            "改走 AWOOI API / TelegramGateway，或在送出前後建立 redacted DB receipt、"
            "AI controlled route metadata、verifier 與 rollback evidence。"
        ),
        "blocked_runtime_action": "direct_telegram_bot_api_without_awooop_receipt",
    }


def _sync_telegram_route_rollups(payload: dict[str, Any]) -> None:
    rollups = payload.setdefault("rollups", {})
    routes = payload.get("telegram_route_findings") or []
    findings = payload.get("zero_signal_findings") or []
    actions = payload.get("operator_actions") or []
    boundaries = payload.get("approval_boundaries") or {}
    blocked = {
        *(item.get("blocked_runtime_action") for item in findings if isinstance(item, dict)),
        *(item.get("blocked_runtime_action") for item in routes if isinstance(item, dict)),
        *(item.get("blocked_runtime_action") for item in actions if isinstance(item, dict)),
        *boundaries.keys(),
    }
    blocked.discard(None)
    rollups["telegram_route_finding_count"] = len(routes)
    rollups["legacy_or_direct_route_count"] = sum(
        1
        for item in routes
        if isinstance(item, dict)
        and item.get("current_state")
        in {"direct_send_path_present", "legacy_chat_env_referenced", "multiple_bot_tokens_present"}
    )
    rollups["blocked_runtime_action_count"] = len(blocked)


def _require_schema(payload: dict[str, Any], label: str) -> None:
    if payload.get("schema_version") != _SCHEMA_VERSION:
        raise ValueError(f"{label}: expected schema_version={_SCHEMA_VERSION}")
    status = payload.get("program_status") or {}
    if status.get("read_only_mode") is not True:
        raise ValueError(f"{label}: program_status.read_only_mode must be true")
    if status.get("runtime_authority") != "report_truth_actionability_review_only_no_report_send_or_runtime_fix":
        raise ValueError(f"{label}: runtime_authority must remain report-truth review only")
    if status.get("current_task_id") != "P2-403K" or status.get("next_task_id") != "P2-403L":
        raise ValueError(f"{label}: current/next task must remain P2-403K -> P2-403L")


def _require_runtime_boundaries(payload: dict[str, Any], label: str) -> None:
    truth = payload.get("report_truth") or {}
    if truth.get("all_zero_weekly_report_is_actionable_anomaly") is not True:
        raise ValueError(f"{label}: all-zero weekly report must remain actionable anomaly")
    for flag in (
        "freshness_gate_implemented",
        "source_confidence_gate_implemented",
        "actionability_score_implemented",
    ):
        if truth.get(flag) is not True:
            raise ValueError(f"{label}: {flag} must be true for P2-403K read-only gates")

    for flag in (
        "ai_agent_runtime_control_allowed",
        "telegram_report_send_allowed",
        "cronjob_change_allowed",
    ):
        if truth.get(flag) is not False:
            raise ValueError(f"{label}: {flag} must remain false until runtime gate")

    boundaries = payload.get("approval_boundaries") or {}
    enabled = sorted(key for key, value in boundaries.items() if value is not False)
    if enabled:
        raise ValueError(f"{label}: approval boundaries must remain false: {enabled}")


def _require_findings(payload: dict[str, Any], label: str) -> None:
    findings = payload.get("zero_signal_findings") or []
    finding_ids = {item.get("finding_id") for item in findings}
    required = {
        "weekly_stats_failure_becomes_zero",
        "weekly_k3s_uptime_hardcoded",
        "git_stats_failure_becomes_zero",
        "monthly_report_contract_missing",
        "heartbeat_noise_not_actionability_scored",
    }
    missing = sorted(required - finding_ids)
    if missing:
        raise ValueError(f"{label}: missing report truth findings: {missing}")

    cadences = payload.get("report_cadence_contracts") or []
    cadence_ids = {item.get("cadence_id") for item in cadences}
    for cadence_id in ("daily_report", "weekly_report", "monthly_report"):
        if cadence_id not in cadence_ids:
            raise ValueError(f"{label}: missing cadence contract {cadence_id}")

    lanes = payload.get("alert_actionability_lanes") or []
    lane_ids = {item.get("lane_id") for item in lanes}
    for lane_id in ("action_required_alert", "stale_source_alert", "heartbeat_noise", "report_truth_failure"):
        if lane_id not in lane_ids:
            raise ValueError(f"{label}: missing actionability lane {lane_id}")


def _require_source_and_actionability_gates(payload: dict[str, Any], label: str) -> None:
    freshness = payload.get("source_freshness_gates") or []
    freshness_ids = {item.get("gate_id") for item in freshness}
    required_freshness = {
        "stats_api_incident_rollup",
        "k3s_metrics_rollup",
        "gitea_activity_rollup",
        "ai_cost_ledger",
        "telegram_delivery_receipt",
        "heartbeat_watchdog",
    }
    missing_freshness = sorted(required_freshness - freshness_ids)
    if missing_freshness:
        raise ValueError(f"{label}: missing source freshness gates: {missing_freshness}")
    for item in freshness:
        if item.get("work_item_required") is not True:
            raise ValueError(f"{label}: source freshness gate {item.get('gate_id')} must require a work item")
        for field in ("freshness_state", "last_success_at", "required_ttl", "ai_next_action", "owner_agent"):
            if not item.get(field):
                raise ValueError(f"{label}: source freshness gate {item.get('gate_id')} missing {field}")

    confidence = payload.get("source_confidence_gates") or []
    confidence_ids = {item.get("confidence_id") for item in confidence}
    required_confidence = {
        "alerts_count_confidence",
        "ai_performance_confidence",
        "k3s_health_confidence",
        "development_activity_confidence",
        "ai_cost_confidence",
    }
    missing_confidence = sorted(required_confidence - confidence_ids)
    if missing_confidence:
        raise ValueError(f"{label}: missing source confidence gates: {missing_confidence}")
    for item in confidence:
        if item.get("confidence") != "low":
            raise ValueError(f"{label}: source confidence gate {item.get('confidence_id')} must remain low until live source readback")
        if item.get("blocked_green_badge") is not True:
            raise ValueError(f"{label}: source confidence gate {item.get('confidence_id')} must block green badge")

    scores = payload.get("report_actionability_scores") or []
    score_ids = {item.get("report_id") for item in scores}
    required_scores = {"daily_report", "weekly_report", "monthly_report", "heartbeat_digest"}
    missing_scores = sorted(required_scores - score_ids)
    if missing_scores:
        raise ValueError(f"{label}: missing report actionability scores: {missing_scores}")
    weekly = next((item for item in scores if item.get("report_id") == "weekly_report"), None)
    if not weekly or weekly.get("score", 0) < 80 or weekly.get("lane") != "action_required_source_gap":
        raise ValueError(f"{label}: weekly report must remain action-required source gap with score >= 80")

    work_items = payload.get("zero_signal_work_items") or []
    work_item_ids = {item.get("work_item_id") for item in work_items}
    required_work_items = {
        "report-source-gap:stats_api",
        "report-source-gap:k3s_metrics",
        "report-source-gap:gitea_activity",
        "report-source-gap:ai_cost_ledger",
        "report-source-gap:telegram_delivery",
    }
    missing_work_items = sorted(required_work_items - work_item_ids)
    if missing_work_items:
        raise ValueError(f"{label}: missing zero signal work items: {missing_work_items}")
    for item in work_items:
        if item.get("status") != "draft_required":
            raise ValueError(f"{label}: zero signal work item {item.get('work_item_id')} must remain draft_required")
        if not item.get("required_assets"):
            raise ValueError(f"{label}: zero signal work item {item.get('work_item_id')} missing required assets")


def _require_telegram_routing(payload: dict[str, Any], label: str) -> None:
    routing = payload.get("telegram_routing_consolidation") or {}
    if routing.get("canonical_room_name") != "AwoooI SRE 戰情室":
        raise ValueError(f"{label}: canonical Telegram room must remain AwoooI SRE 戰情室")
    if routing.get("canonical_room_env") != "SRE_GROUP_CHAT_ID":
        raise ValueError(f"{label}: canonical Telegram room env must remain SRE_GROUP_CHAT_ID")
    required_false = (
        "other_bot_or_group_alerts_allowed",
        "direct_telegram_api_send_allowed",
        "secret_value_read_allowed",
        "route_change_allowed",
    )
    for flag in required_false:
        if routing.get(flag) is not False:
            raise ValueError(f"{label}: telegram routing flag {flag} must remain false until approved migration")
    if routing.get("product_alerts_must_route_to_canonical_room") is not True:
        raise ValueError(f"{label}: product alerts must target canonical SRE war room")

    routes = payload.get("telegram_route_findings") or []
    route_ids = {item.get("route_id") for item in routes}
    required_routes = {
        "gitea_cd_direct_telegram",
        "gitea_code_review_direct_telegram",
        "multi_bot_secret_injection",
        "legacy_alert_chat_env",
    }
    missing = sorted(required_routes - route_ids)
    if missing:
        raise ValueError(f"{label}: missing Telegram route findings: {missing}")


def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    rollups = payload.get("rollups") or {}
    findings = payload.get("zero_signal_findings") or []
    cadences = payload.get("report_cadence_contracts") or []
    lanes = payload.get("alert_actionability_lanes") or []
    routes = payload.get("telegram_route_findings") or []
    actions = payload.get("operator_actions") or []
    freshness = payload.get("source_freshness_gates") or []
    confidence = payload.get("source_confidence_gates") or []
    scores = payload.get("report_actionability_scores") or []
    work_items = payload.get("zero_signal_work_items") or []
    blocked = {
        *(item.get("blocked_runtime_action") for item in findings),
        *(item.get("blocked_runtime_action") for item in routes),
        *(item.get("blocked_runtime_action") for item in actions),
        *(payload.get("approval_boundaries") or {}).keys(),
    }
    blocked.discard(None)
    expected_counts = {
        "zero_signal_finding_count": len(findings),
        "source_freshness_gate_count": len(freshness),
        "stale_or_untrusted_source_count": sum(
            1 for item in freshness if item.get("freshness_state") != "report_only_when_fresh"
        ),
        "source_confidence_gate_count": len(confidence),
        "low_confidence_gate_count": sum(1 for item in confidence if item.get("confidence") == "low"),
        "report_actionability_score_count": len(scores),
        "actionability_score_ready_count": sum(1 for item in scores if isinstance(item.get("score"), int) and item.get("score") > 0),
        "zero_signal_work_item_count": len(work_items),
        "work_item_required_count": sum(1 for item in freshness if item.get("work_item_required") is True),
        "critical_finding_count": sum(1 for item in findings if item.get("severity") == "critical"),
        "high_finding_count": sum(1 for item in findings if item.get("severity") == "high"),
        "cadence_contract_count": len(cadences),
        "missing_cadence_contract_count": sum(1 for item in cadences if item.get("status") == "missing_contract"),
        "actionability_lane_count": len(lanes),
        "telegram_route_finding_count": len(routes),
        "legacy_or_direct_route_count": sum(
            1
            for item in routes
            if item.get("current_state") in {"direct_send_path_present", "legacy_chat_env_referenced", "multiple_bot_tokens_present"}
        ),
        "operator_action_count": len(actions),
        "blocked_runtime_action_count": len(blocked),
    }
    mismatched = {
        key: {"expected": expected, "actual": rollups.get(key)}
        for key, expected in expected_counts.items()
        if rollups.get(key) != expected
    }
    if mismatched:
        raise ValueError(f"{label}: rollup counts must match payload sections: {mismatched}")

    approval_required = sorted(
        action.get("action_id")
        for action in actions
        if action.get("status") == "approval_required"
    )
    if sorted(rollups.get("approval_required_action_ids") or []) != approval_required:
        raise ValueError(f"{label}: approval_required_action_ids mismatch")
    if rollups.get("all_zero_weekly_report_confidence") != "low_trust_actionable_anomaly":
        raise ValueError(f"{label}: all-zero weekly report confidence must stay low trust")
    weekly = next((item for item in scores if item.get("report_id") == "weekly_report"), {})
    if rollups.get("all_zero_weekly_report_actionability_score") != weekly.get("score"):
        raise ValueError(f"{label}: all-zero weekly report actionability score mismatch")
