"""
AI Agent result capture owner-approved execution rehearsal snapshot.

Loads the latest committed P2-126 owner-approved execution rehearsal package.
This module validates committed evidence only; it never applies writers, executes
live applies, writes receipts, writes result captures, writes learning records,
updates PlayBook trust, writes reviewer / Gateway queues, sends Telegram
messages, 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_result_capture_owner_approved_execution_rehearsal_*.json"
_SCHEMA_VERSION = "ai_agent_result_capture_owner_approved_execution_rehearsal_v1"
_RUNTIME_AUTHORITY = "result_capture_owner_approved_execution_rehearsal_only_no_live_write"


def load_latest_ai_agent_result_capture_owner_approved_execution_rehearsal(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed owner-approved execution rehearsal package."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(f"no AI Agent result capture owner-approved execution rehearsal 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_execution_rehearsals(payload, label)
    _require_apply_checks(payload, label)
    _require_verifier_rehearsals(payload, label)
    _require_rollback_drills(payload, label)
    _require_blocked_applies(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-126",
        "next_task_id": "P2-127",
        "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_result_capture_owner_promotion_review") or {}
    expected = {
        "schema_version": "ai_agent_result_capture_owner_promotion_review_v1",
        "owner_promotion_packet_count": 5,
        "execution_gate_check_count": 5,
        "rollback_owner_review_count": 5,
        "blocked_execution_write_count": 6,
        "operator_action_count": 5,
        "owner_promotion_approved_count": 0,
        "execution_gate_pass_count": 0,
        "rollback_owner_confirmed_count": 0,
        "post_write_verifier_ready_count": 0,
        "writer_apply_count": 0,
        "execution_apply_count": 0,
        "receipt_write_count": 0,
        "result_capture_write_count": 0,
        "learning_write_count": 0,
        "playbook_trust_write_count": 0,
        "reviewer_queue_write_count": 0,
        "gateway_queue_write_count": 0,
        "telegram_send_count": 0,
        "bot_api_call_count": 0,
        "report_receipt_write_count": 0,
    }
    mismatches = _mismatches(prior, expected)
    if mismatches:
        raise ValueError(f"{label}: prior_result_capture_owner_promotion_review mismatch: {mismatches}")
    if not prior.get("readiness_note"):
        raise ValueError(f"{label}: prior_result_capture_owner_promotion_review.readiness_note is required")


def _require_truth(payload: dict[str, Any], label: str) -> None:
    truth = payload.get("execution_rehearsal_truth") or {}
    required_true = {
        "p2_125_owner_promotion_loaded",
        "owner_approval_record_required",
        "no_write_apply_rehearsal_ready",
        "post_write_verifier_rehearsal_ready",
        "rollback_drill_ready",
        "idempotency_replay_required",
        "redaction_review_required",
        "execution_rehearsal_only",
    }
    missing = sorted(field for field in required_true if truth.get(field) is not True)
    if missing:
        raise ValueError(f"{label}: rehearsal ready flags must remain true: {missing}")
    required_false = {
        "owner_approval_record_received",
        "no_write_apply_executed",
        "post_write_verifier_passed",
        "rollback_drill_confirmed",
        "writer_apply_enabled",
        "execution_apply_enabled",
        "receipt_write_enabled",
        "reviewer_queue_write_enabled",
        "gateway_queue_write_enabled",
        "telegram_send_enabled",
        "bot_api_call_enabled",
        "report_receipt_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 execution/send/write flags must remain false: {unsafe}")
    zero_counts = {
        "owner_approval_record_received_count",
        "no_write_apply_execution_count",
        "post_write_verifier_pass_count",
        "rollback_drill_confirmed_count",
        "writer_apply_count",
        "execution_apply_count",
        "receipt_write_count",
        "reviewer_queue_write_count",
        "gateway_queue_write_count",
        "telegram_send_count",
        "bot_api_call_count",
        "report_receipt_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_counts if truth.get(field) != 0)
    if non_zero:
        raise ValueError(f"{label}: rehearsal live counters must remain zero: {non_zero}")
    if not truth.get("truth_note"):
        raise ValueError(f"{label}: execution_rehearsal_truth.truth_note is required")


def _require_execution_rehearsals(payload: dict[str, Any], label: str) -> None:
    items = payload.get("execution_rehearsals") or []
    required = {
        "rehearsal_result_capture_writer",
        "rehearsal_learning_writer",
        "rehearsal_playbook_trust_writer",
        "rehearsal_reviewer_queue_writer",
        "rehearsal_gateway_queue_writer",
    }
    ids = {item.get("rehearsal_id") for item in items}
    if ids != required:
        raise ValueError(f"{label}: execution rehearsals must match {sorted(required)}")
    for item in items:
        item_id = item.get("rehearsal_id")
        if item.get("rehearsal_mode") != "no_write_apply_rehearsal":
            raise ValueError(f"{label}: rehearsal {item_id} must remain no-write apply rehearsal")
        if item.get("no_write_only") is not True or item.get("live_apply_enabled") is not False:
            raise ValueError(f"{label}: rehearsal {item_id} must not enable live apply")
        if item.get("status") not in {"ready_for_rehearsal_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: rehearsal {item_id} status is invalid")
        if not item.get("expected_output") or not _is_redacted_sha256(item.get("evidence_hash")):
            raise ValueError(f"{label}: rehearsal {item_id} must include expected output and redacted evidence")


def _require_apply_checks(payload: dict[str, Any], label: str) -> None:
    items = payload.get("no_write_apply_checks") or []
    required = {
        "check_owner_approval_record",
        "check_idempotency_replay",
        "check_payload_redaction",
        "check_post_write_verifier",
        "check_production_write_block",
    }
    ids = {item.get("check_id") for item in items}
    if ids != required:
        raise ValueError(f"{label}: no-write apply checks must match {sorted(required)}")
    for item in items:
        item_id = item.get("check_id")
        if item.get("check_mode") != "no_write_apply_gate":
            raise ValueError(f"{label}: check {item_id} must remain no-write apply gate")
        if item.get("required_before_apply") is not True or item.get("live_apply_enabled") is not False:
            raise ValueError(f"{label}: check {item_id} must not enable live apply")
        if item.get("status") not in {"ready_for_rehearsal_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: check {item_id} status is invalid")
        if not item.get("failure_if_missing"):
            raise ValueError(f"{label}: check {item_id} failure_if_missing is required")


def _require_verifier_rehearsals(payload: dict[str, Any], label: str) -> None:
    items = payload.get("post_write_verifier_rehearsals") or []
    required = {
        "verifier_result_capture",
        "verifier_learning",
        "verifier_playbook_trust",
        "verifier_reviewer_queue",
        "verifier_gateway_queue",
    }
    ids = {item.get("verifier_id") for item in items}
    if ids != required:
        raise ValueError(f"{label}: verifier rehearsals must match {sorted(required)}")
    for item in items:
        item_id = item.get("verifier_id")
        if item.get("verifier_mode") != "fixture_only_no_live_read":
            raise ValueError(f"{label}: verifier {item_id} must remain fixture-only")
        if item.get("verifier_ready") is not False or item.get("live_read_enabled") is not False:
            raise ValueError(f"{label}: verifier {item_id} must not enable live read")
        if item.get("status") not in {"ready_for_rehearsal_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: verifier {item_id} status is invalid")
        if not item.get("expected_signal"):
            raise ValueError(f"{label}: verifier {item_id} expected_signal is required")


def _require_rollback_drills(payload: dict[str, Any], label: str) -> None:
    items = payload.get("rollback_drills") or []
    required = {
        "rollback_drill_result_capture",
        "rollback_drill_learning",
        "rollback_drill_playbook_trust",
        "rollback_drill_reviewer_queue",
        "rollback_drill_gateway_queue",
    }
    ids = {item.get("drill_id") for item in items}
    if ids != required:
        raise ValueError(f"{label}: rollback drills must match {sorted(required)}")
    for item in items:
        item_id = item.get("drill_id")
        if item.get("rollback_owner_required") is not True or item.get("rollback_drill_confirmed") is not False:
            raise ValueError(f"{label}: rollback drill {item_id} must require unconfirmed owner")
        if item.get("status") not in {"ready_for_rehearsal_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: rollback drill {item_id} status is invalid")
        if not item.get("drill_note"):
            raise ValueError(f"{label}: rollback drill {item_id} drill_note is required")


def _require_blocked_applies(payload: dict[str, Any], label: str) -> None:
    items = payload.get("blocked_live_applies") or []
    required = {
        "blocked_writer_apply",
        "blocked_execution_apply",
        "blocked_receipt_write",
        "blocked_result_capture_write",
        "blocked_gateway_queue_write",
        "blocked_telegram_send",
    }
    ids = {item.get("blocker_id") for item in items}
    if ids != required:
        raise ValueError(f"{label}: blocked live applies must match {sorted(required)}")
    for item in items:
        item_id = item.get("blocker_id")
        if item.get("status") not in {"approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: blocker {item_id} status is invalid")
        if item.get("severity") not in {"high", "critical"}:
            raise ValueError(f"{label}: blocker {item_id} severity is invalid")
        if not item.get("blocked_action") or not item.get("blocked_until"):
            raise ValueError(f"{label}: blocker {item_id} must include blocked_action and blocked_until")
        if not _is_redacted_sha256(item.get("evidence_hash")):
            raise ValueError(f"{label}: blocker {item_id} must expose redacted evidence_hash")


def _require_actions(payload: dict[str, Any], label: str) -> None:
    actions = payload.get("operator_actions") or []
    required = {
        "review_execution_rehearsals",
        "verify_no_write_apply_checks",
        "inspect_post_write_verifier_rehearsal",
        "confirm_rollback_drills",
        "hold_live_apply_gate",
    }
    ids = {action.get("action_id") for action in actions}
    if 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_write_allowed") is not False:
            raise ValueError(f"{label}: action {action_id} must not allow runtime write")
        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 {}
    expected = {
        "redaction_required": True,
        "raw_prompt_display_allowed": False,
        "private_reasoning_display_allowed": False,
        "secret_value_display_allowed": False,
        "raw_runtime_payload_display_allowed": False,
        "internal_collaboration_content_display_allowed": False,
    }
    mismatches = _mismatches(contract, expected)
    if mismatches:
        raise ValueError(f"{label}: display_redaction_contract mismatch: {mismatches}")
    if not contract.get("frontend_display_policy"):
        raise ValueError(f"{label}: display_redaction_contract.frontend_display_policy is required")


def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    rollups = payload.get("rollups") or {}
    rehearsals = payload.get("execution_rehearsals") or []
    checks = payload.get("no_write_apply_checks") or []
    verifiers = payload.get("post_write_verifier_rehearsals") or []
    drills = payload.get("rollback_drills") or []
    blockers = payload.get("blocked_live_applies") or []
    actions = payload.get("operator_actions") or []
    expected = {
        "execution_rehearsal_count": len(rehearsals),
        "no_write_apply_check_count": len(checks),
        "post_write_verifier_rehearsal_count": len(verifiers),
        "rollback_drill_count": len(drills),
        "blocked_live_apply_count": len(blockers),
        "operator_action_count": len(actions),
        "approval_required_rehearsal_count": sum(1 for item in rehearsals if item.get("status") == "approval_required"),
        "blocked_rehearsal_count": sum(1 for item in rehearsals if item.get("status") == "blocked_by_policy"),
        "approval_required_check_count": sum(1 for item in checks if item.get("status") == "approval_required"),
        "blocked_check_count": sum(1 for item in checks if item.get("status") == "blocked_by_policy"),
        "approval_required_verifier_count": sum(1 for item in verifiers if item.get("status") == "approval_required"),
        "blocked_verifier_count": sum(1 for item in verifiers if item.get("status") == "blocked_by_policy"),
        "approval_required_rollback_count": sum(1 for item in drills if item.get("status") == "approval_required"),
        "blocked_rollback_count": sum(1 for item in drills if item.get("status") == "blocked_by_policy"),
        "critical_blocker_count": sum(1 for item in blockers if item.get("severity") == "critical"),
        "owner_approval_record_received_count": 0,
        "no_write_apply_execution_count": 0,
        "post_write_verifier_pass_count": 0,
        "rollback_drill_confirmed_count": 0,
        "writer_apply_count": 0,
        "execution_apply_count": 0,
        "receipt_write_count": 0,
        "reviewer_queue_write_count": 0,
        "gateway_queue_write_count": 0,
        "telegram_send_count": 0,
        "bot_api_call_count": 0,
        "report_receipt_write_count": 0,
        "result_capture_write_count": 0,
        "learning_write_count": 0,
        "playbook_trust_write_count": 0,
        "production_write_count": 0,
        "secret_read_count": 0,
        "destructive_operation_count": 0,
    }
    mismatches = _mismatches(rollups, expected)
    if mismatches:
        raise ValueError(f"{label}: rollup counts mismatch: {mismatches}")


def _require_no_forbidden_display_terms(payload: dict[str, Any], label: str) -> None:
    serialized = json.dumps(payload, ensure_ascii=False)
    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 present: {hits}")


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


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