"""
AI Agent failure receipt no-send replay snapshot.

Loads the latest committed P2-116 no-send replay package. This module validates
committed evidence only; it never sends Telegram messages, writes Gateway queues,
calls Bot API, writes reviewer queues, writes result captures, reads canonical
runtime targets, reads secrets, or performs destructive operations.
"""

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_failure_receipt_no_send_replay_*.json"
_SCHEMA_VERSION = "ai_agent_failure_receipt_no_send_replay_v1"
_RUNTIME_AUTHORITY = "failure_receipt_no_send_replay_only_no_queue_or_send"
_TARGET_ROUTE = "awoooi_sre_war_room"


def load_latest_ai_agent_failure_receipt_no_send_replay(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed failure receipt no-send replay package."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(f"no AI Agent failure receipt no-send replay 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")

    label = str(latest)
    _require_schema(payload, label)
    _require_prior(payload, label)
    _require_truth(payload, label)
    _require_replay_fixtures(payload, label)
    _require_route_locks(payload, label)
    _require_verifier_checks(payload, label)
    _require_blocked_sends(payload, label)
    _require_actions(payload, label)
    _require_display_redaction(payload, label)
    _require_no_forbidden_display_terms(payload, label)
    _require_rollup_consistency(payload, label)
    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 {}
    expected = {
        "current_priority": "P2",
        "current_task_id": "P2-116",
        "next_task_id": "P2-117",
        "read_only_mode": True,
        "runtime_authority": _RUNTIME_AUTHORITY,
        "overall_completion_percent": 100,
    }
    mismatches = _mismatches(status, expected)
    if mismatches:
        raise ValueError(f"{label}: program_status mismatch: {mismatches}")
    if not status.get("status_note"):
        raise ValueError(f"{label}: program_status.status_note is required")


def _require_prior(payload: dict[str, Any], label: str) -> None:
    prior = payload.get("prior_owner_acceptance") or {}
    expected = {
        "schema_version": "ai_agent_canonical_runtime_readback_owner_acceptance_v1",
        "owner_approval_packet_count": 5,
        "acceptance_record_template_count": 4,
        "fixture_promotion_review_count": 4,
        "no_write_verifier_plan_count": 5,
        "blocked_promotion_count": 5,
        "operator_action_count": 5,
        "owner_approval_received_count": 0,
        "owner_acceptance_record_write_count": 0,
        "canonical_runtime_target_read_count": 0,
        "failure_receipt_send_count": 0,
        "gateway_queue_write_count": 0,
        "telegram_send_count": 0,
        "result_capture_write_count": 0,
    }
    mismatches = _mismatches(prior, expected)
    if mismatches:
        raise ValueError(f"{label}: prior_owner_acceptance mismatch: {mismatches}")
    if not prior.get("readiness_note"):
        raise ValueError(f"{label}: prior_owner_acceptance.readiness_note is required")


def _require_truth(payload: dict[str, Any], label: str) -> None:
    truth = payload.get("replay_truth") or {}
    required_true = {
        "p2_115_owner_acceptance_loaded",
        "no_send_replay_package_ready",
        "failure_receipt_fixture_ready",
        "route_lock_fixture_ready",
        "redaction_fixture_ready",
        "operator_handoff_ready",
        "no_send_verifier_required",
    }
    missing = sorted(field for field in required_true if truth.get(field) is not True)
    if missing:
        raise ValueError(f"{label}: replay ready flags must remain true: {missing}")
    if truth.get("owner_approval_received") is not False:
        raise ValueError(f"{label}: owner approval must remain false before replay send")

    required_false = {
        "canonical_runtime_target_read_enabled",
        "live_query_enabled",
        "failure_receipt_send_enabled",
        "gateway_queue_write_enabled",
        "telegram_send_enabled",
        "bot_api_call_enabled",
        "report_receipt_write_enabled",
        "reviewer_queue_write_enabled",
        "result_capture_write_enabled",
        "learning_write_enabled",
        "playbook_trust_write_enabled",
        "production_write_enabled",
        "secret_read_enabled",
        "destructive_operation_enabled",
    }
    unsafe = sorted(field for field in required_false if truth.get(field) is not False)
    if unsafe:
        raise ValueError(f"{label}: live read/send/write flags must remain false: {unsafe}")

    zero_counts = {
        "owner_approval_received_count",
        "canonical_runtime_target_read_count",
        "live_query_count",
        "failure_receipt_send_count",
        "gateway_queue_write_count",
        "telegram_send_count",
        "bot_api_call_count",
        "report_receipt_write_count",
        "reviewer_queue_write_count",
        "result_capture_write_count",
        "learning_write_count",
        "playbook_trust_write_count",
        "production_write_count",
    }
    non_zero = sorted(field for field in zero_counts if truth.get(field) != 0)
    if non_zero:
        raise ValueError(f"{label}: replay live counters must remain zero: {non_zero}")
    if not truth.get("truth_note"):
        raise ValueError(f"{label}: replay_truth.truth_note is required")


def _require_replay_fixtures(payload: dict[str, Any], label: str) -> None:
    fixtures = payload.get("no_send_replay_fixtures") or []
    required = {
        "telegram_failure_receipt_action_required",
        "telegram_failure_receipt_no_action",
        "telegram_failure_receipt_verifier_degraded",
        "telegram_failure_receipt_route_locked",
        "telegram_failure_receipt_result_capture_pending",
    }
    fixture_ids = {fixture.get("fixture_id") for fixture in fixtures}
    if fixture_ids != required:
        raise ValueError(f"{label}: no-send replay fixtures must match {sorted(required)}")
    for fixture in fixtures:
        fixture_id = fixture.get("fixture_id")
        if fixture.get("target_channel") != _TARGET_ROUTE:
            raise ValueError(f"{label}: fixture {fixture_id} must target {_TARGET_ROUTE}")
        if fixture.get("send_enabled") is not False:
            raise ValueError(f"{label}: fixture {fixture_id} must not enable send")
        if fixture.get("status") not in {"ready_for_owner_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: fixture {fixture_id} status is invalid")
        if not fixture.get("payload_outline") or not fixture.get("incident_stage"):
            raise ValueError(f"{label}: fixture {fixture_id} must include payload outline and incident stage")
        if not _is_redacted_sha256(fixture.get("evidence_hash")):
            raise ValueError(f"{label}: fixture {fixture_id} must expose redacted evidence_hash")


def _require_route_locks(payload: dict[str, Any], label: str) -> None:
    checks = payload.get("route_lock_checks") or []
    required = {
        "sre_war_room_single_route",
        "legacy_bot_route_block",
        "operator_console_pairing",
        "route_lock_owner_acceptance",
    }
    check_ids = {check.get("check_id") for check in checks}
    if check_ids != required:
        raise ValueError(f"{label}: route lock checks must match {sorted(required)}")
    for check in checks:
        check_id = check.get("check_id")
        if check.get("target_route") != _TARGET_ROUTE:
            raise ValueError(f"{label}: route lock {check_id} must target {_TARGET_ROUTE}")
        if check.get("queue_write_enabled") is not False:
            raise ValueError(f"{label}: route lock {check_id} must not enable queue write")
        if check.get("deprecated_route_count") != 0:
            raise ValueError(f"{label}: route lock {check_id} deprecated_route_count must remain 0")
        if check.get("status") not in {"ready", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: route lock {check_id} status is invalid")
        if not _is_redacted_sha256(check.get("evidence_hash")):
            raise ValueError(f"{label}: route lock {check_id} must expose redacted evidence_hash")


def _require_verifier_checks(payload: dict[str, Any], label: str) -> None:
    checks = payload.get("replay_verifier_checks") or []
    required = {
        "no_send_counter_verifier",
        "no_gateway_queue_write_verifier",
        "no_bot_api_call_verifier",
        "safe_payload_redaction_verifier",
        "manual_action_presence_verifier",
    }
    verifier_ids = {check.get("verifier_id") for check in checks}
    if verifier_ids != required:
        raise ValueError(f"{label}: replay verifier checks must match {sorted(required)}")
    for check in checks:
        verifier_id = check.get("verifier_id")
        if check.get("live_execution_enabled") is not False:
            raise ValueError(f"{label}: verifier {verifier_id} must not enable live execution")
        if check.get("owner_agent") not in {"openclaw", "hermes", "nemotron"}:
            raise ValueError(f"{label}: verifier {verifier_id} owner_agent is invalid")
        if not check.get("verifies") or not check.get("failure_if_missing"):
            raise ValueError(f"{label}: verifier {verifier_id} must include verifies and failure text")
        if not _is_redacted_sha256(check.get("evidence_hash")):
            raise ValueError(f"{label}: verifier {verifier_id} must expose redacted evidence_hash")


def _require_blocked_sends(payload: dict[str, Any], label: str) -> None:
    blockers = payload.get("blocked_sends") or []
    required = {
        "owner_acceptance_missing",
        "gateway_queue_not_authorized",
        "bot_api_not_authorized",
        "receipt_write_not_authorized",
        "result_capture_not_authorized",
    }
    blocker_ids = {blocker.get("blocker_id") for blocker in blockers}
    if blocker_ids != required:
        raise ValueError(f"{label}: blocked sends must match {sorted(required)}")
    for blocker in blockers:
        blocker_id = blocker.get("blocker_id")
        if blocker.get("severity") not in {"high", "critical"}:
            raise ValueError(f"{label}: blocker {blocker_id} severity is invalid")
        if blocker.get("status") not in {"approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: blocker {blocker_id} status is invalid")
        if not blocker.get("blocked_action") or not blocker.get("blocked_until"):
            raise ValueError(f"{label}: blocker {blocker_id} blocked action/until is required")
        if not _is_redacted_sha256(blocker.get("evidence_hash")):
            raise ValueError(f"{label}: blocker {blocker_id} must expose redacted evidence_hash")


def _require_actions(payload: dict[str, Any], label: str) -> None:
    actions = payload.get("operator_actions") or []
    required = {
        "review_failure_receipt_fixtures",
        "verify_sre_war_room_route_lock",
        "check_redaction_contract",
        "prepare_manual_handoff",
        "promote_to_p2_117",
    }
    action_ids = {action.get("action_id") for action in actions}
    if action_ids != required:
        raise ValueError(f"{label}: operator actions must match {sorted(required)}")
    for action in actions:
        action_id = action.get("action_id")
        if action.get("runtime_send_allowed") is not False:
            raise ValueError(f"{label}: action {action_id} must not allow runtime send")
        if action.get("owner_agent") not in {"openclaw", "hermes", "nemotron"}:
            raise ValueError(f"{label}: action {action_id} owner_agent is invalid")
        if not action.get("operator_instruction"):
            raise ValueError(f"{label}: action {action_id} operator_instruction is required")


def _require_display_redaction(payload: dict[str, Any], label: str) -> None:
    contract = payload.get("display_redaction_contract") or {}
    if contract.get("redaction_required") is not True:
        raise ValueError(f"{label}: display redaction must be required")
    false_fields = {
        "raw_prompt_display_allowed",
        "private_reasoning_display_allowed",
        "secret_value_display_allowed",
        "raw_runtime_payload_display_allowed",
        "internal_collaboration_content_display_allowed",
    }
    unsafe = sorted(field for field in false_fields if contract.get(field) is not False)
    if unsafe:
        raise ValueError(f"{label}: display redaction flags must remain false: {unsafe}")
    if not contract.get("frontend_display_policy"):
        raise ValueError(f"{label}: frontend_display_policy is required")


def _require_no_forbidden_display_terms(payload: dict[str, Any], label: str) -> None:
    serialized = json.dumps(payload, ensure_ascii=False).lower()
    forbidden = {
        "work_window_transcript",
        "session_id",
        "browser_context",
        "authorization_header",
        "raw telegram payload",
        "private reasoning",
        "raw prompt",
        "chain-of-thought",
    }
    hits = sorted(term for term in forbidden if term in serialized)
    if hits:
        raise ValueError(f"{label}: forbidden display terms leaked: {hits}")


def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    rollups = payload.get("rollups") or {}
    expected_counts = {
        "no_send_replay_fixture_count": len(payload.get("no_send_replay_fixtures") or []),
        "route_lock_check_count": len(payload.get("route_lock_checks") or []),
        "replay_verifier_check_count": len(payload.get("replay_verifier_checks") or []),
        "blocked_send_count": len(payload.get("blocked_sends") or []),
        "operator_action_count": len(payload.get("operator_actions") or []),
        "approval_required_fixture_count": sum(
            1
            for fixture in payload.get("no_send_replay_fixtures") or []
            if fixture.get("status") == "approval_required"
        ),
        "blocked_fixture_count": sum(
            1
            for fixture in payload.get("no_send_replay_fixtures") or []
            if fixture.get("status") == "blocked_by_policy"
        ),
        "approval_required_route_lock_count": sum(
            1 for check in payload.get("route_lock_checks") or [] if check.get("status") == "approval_required"
        ),
        "blocked_route_lock_count": sum(
            1 for check in payload.get("route_lock_checks") or [] if check.get("status") == "blocked_by_policy"
        ),
        "approval_required_verifier_count": sum(
            1 for check in payload.get("replay_verifier_checks") or [] if check.get("status") == "approval_required"
        ),
        "critical_blocker_count": sum(
            1 for blocker in payload.get("blocked_sends") or [] if blocker.get("severity") == "critical"
        ),
    }
    mismatches = _mismatches(rollups, expected_counts)
    if mismatches:
        raise ValueError(f"{label}: rollup counts mismatch: {mismatches}")

    zero_rollups = {
        "owner_approval_received_count",
        "canonical_runtime_target_read_count",
        "live_query_count",
        "failure_receipt_send_count",
        "gateway_queue_write_count",
        "telegram_send_count",
        "bot_api_call_count",
        "report_receipt_write_count",
        "reviewer_queue_write_count",
        "result_capture_write_count",
        "learning_write_count",
        "playbook_trust_write_count",
        "production_write_count",
        "secret_read_count",
        "destructive_operation_count",
    }
    non_zero = sorted(field for field in zero_rollups if rollups.get(field) != 0)
    if non_zero:
        raise ValueError(f"{label}: live/send/write rollups must remain zero: {non_zero}")


def _mismatches(actual: dict[str, Any], expected: dict[str, Any]) -> dict[str, dict[str, Any]]:
    return {
        key: {"expected": expected_value, "actual": actual.get(key)}
        for key, expected_value in expected.items()
        if actual.get(key) != expected_value
    }


def _is_redacted_sha256(value: Any) -> bool:
    if not isinstance(value, str):
        return False
    if not value.startswith("sha256:") or len(value) != len("sha256:") + 64:
        return False
    digest = value.split(":", 1)[1]
    return all(char in "0123456789abcdef" for char in digest)
