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

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from src.services.snapshot_paths import default_evaluations_dir

_DEFAULT_EVALUATIONS_DIR = default_evaluations_dir(Path(__file__))
_SNAPSHOT_PATTERN = "ai_agent_report_truth_actionability_review_*.json"
_SCHEMA_VERSION = "ai_agent_report_truth_actionability_review_v1"


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_telegram_routing(payload, str(latest))
    _require_rollup_consistency(payload, str(latest))
    return payload


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-403J" or status.get("next_task_id") != "P2-403K":
        raise ValueError(f"{label}: current/next task must remain P2-403J -> P2-403K")


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",
        "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_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 []
    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),
        "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")
