"""
AI Agent result capture owner release approval gate snapshot.

Loads the latest committed P2-131 owner release approval gate. This module
validates committed evidence only; it never approves owner release, approves
maintenance windows, releases live apply, applies writers, writes receipts,
writes result captures, writes learning records, updates PlayBook trust,
writes reviewer / Gateway queues, sends Telegram messages, 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_release_approval_gate_*.json"
_SCHEMA_VERSION = "ai_agent_result_capture_owner_release_approval_gate_v1"
# P2-131 no-op deploy retrigger anchor; behavior remains read-only.
_RUNTIME_AUTHORITY = "result_capture_owner_release_approval_gate_only_no_live_write"


def load_latest_ai_agent_result_capture_owner_release_approval_gate(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed owner release approval gate."""
    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 release approval gate 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_packets(payload, label)
    _require_maintenance_windows(payload, label)
    _require_live_apply_gates(payload, label)
    _require_rollback_checks(payload, label)
    _require_blocked_transitions(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-131",
        "next_task_id": "P2-132",
        "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_approved_release_readiness_readback") or {}
    expected = {
        "schema_version": "ai_agent_result_capture_owner_approved_release_readiness_readback_v1",
        "release_readiness_readback_count": 5,
        "owner_release_readiness_check_count": 5,
        "live_apply_readiness_gate_count": 5,
        "rollback_readiness_check_count": 5,
        "blocked_readiness_transition_count": 6,
        "operator_action_count": 5,
        "approval_required_total": 8,
        "blocked_total": 9,
        "owner_release_approved_count": 0,
        "maintenance_window_approved_count": 0,
        "rollback_owner_confirmed_count": 0,
        "post_release_verifier_ready_count": 0,
        "release_readiness_pass_count": 0,
        "live_apply_release_pass_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_owner_approved_release_readiness_readback mismatch: {mismatches}")
    if not prior.get("readiness_note"):
        raise ValueError(f"{label}: prior_owner_approved_release_readiness_readback.readiness_note is required")


def _require_truth(payload: dict[str, Any], label: str) -> None:
    truth = payload.get("owner_release_approval_truth") or {}
    required_true = {
        "p2_130_readiness_loaded",
        "owner_release_approval_gate_ready",
        "owner_release_review_required",
        "maintenance_window_review_required",
        "live_apply_approval_hold_active",
        "rollback_owner_review_required",
        "post_release_verifier_required",
        "redaction_review_required",
        "owner_release_approval_gate_only",
    }
    missing = sorted(field for field in required_true if truth.get(field) is not True)
    if missing:
        raise ValueError(f"{label}: owner release approval gate flags must remain true: {missing}")

    required_false = {
        "owner_release_approved",
        "maintenance_window_approved",
        "rollback_owner_confirmed",
        "post_release_verifier_ready",
        "release_approval_passed",
        "live_apply_release_passed",
        "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}: owner release approval live/send/write flags must remain false: {unsafe}")

    zero_counts = {
        "owner_release_approved_count",
        "maintenance_window_approved_count",
        "rollback_owner_confirmed_count",
        "post_release_verifier_ready_count",
        "release_approval_pass_count",
        "live_apply_release_pass_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}: owner release approval live counters must remain zero: {non_zero}")
    if not truth.get("truth_note"):
        raise ValueError(f"{label}: owner_release_approval_truth.truth_note is required")


def _require_packets(payload: dict[str, Any], label: str) -> None:
    items = payload.get("owner_release_approval_packets") or []
    _require_ids(
        items,
        "packet_id",
        {
            "approval_gate_result_capture_writer",
            "approval_gate_learning_writer",
            "approval_gate_playbook_trust_writer",
            "approval_gate_reviewer_queue_writer",
            "approval_gate_gateway_queue_writer",
        },
        label,
        "owner release approval packets",
    )
    for item in items:
        item_id = item.get("packet_id")
        if item.get("approval_mode") != "owner_release_approval_gate":
            raise ValueError(f"{label}: owner release approval packet {item_id} mode is invalid")
        if item.get("owner_release_approved") is not False or item.get("release_approval_passed") is not False:
            raise ValueError(f"{label}: owner release approval packet {item_id} must stay unapproved and unpassed")
        if item.get("status") not in {"ready_for_owner_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: owner release approval packet {item_id} status is invalid")
        if not item.get("approval_summary") or not _is_redacted_sha256(item.get("evidence_hash")):
            raise ValueError(f"{label}: owner release approval packet {item_id} must include summary and redacted evidence_hash")


def _require_maintenance_windows(payload: dict[str, Any], label: str) -> None:
    items = payload.get("maintenance_window_approval_gates") or []
    _require_ids(
        items,
        "gate_id",
        {
            "maintenance_window_result_capture",
            "maintenance_window_learning",
            "maintenance_window_playbook_trust",
            "maintenance_window_reviewer_queue",
            "maintenance_window_gateway_queue",
        },
        label,
        "maintenance window approval gates",
    )
    for item in items:
        item_id = item.get("gate_id")
        if item.get("gate_mode") != "maintenance_window_approval_gate":
            raise ValueError(f"{label}: maintenance window approval gate {item_id} mode is invalid")
        if item.get("maintenance_window_review_required") is not True or item.get("maintenance_window_approved") is not False:
            raise ValueError(f"{label}: maintenance window approval gate {item_id} must remain required and unapproved")
        if item.get("status") not in {"ready_for_owner_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: maintenance window approval gate {item_id} status is invalid")
        if not item.get("required_before_live_apply"):
            raise ValueError(f"{label}: maintenance window approval gate {item_id} required_before_live_apply is required")


def _require_live_apply_gates(payload: dict[str, Any], label: str) -> None:
    items = payload.get("live_apply_release_approval_gates") or []
    _require_ids(
        items,
        "gate_id",
        {
            "live_apply_approval_result_capture",
            "live_apply_approval_learning",
            "live_apply_approval_playbook_trust",
            "live_apply_approval_reviewer_queue",
            "live_apply_approval_gateway_queue",
        },
        label,
        "live apply release approval gates",
    )
    for item in items:
        item_id = item.get("gate_id")
        if item.get("gate_mode") != "live_apply_release_approval_gate":
            raise ValueError(f"{label}: live apply release approval gate {item_id} mode is invalid")
        if item.get("release_approval_passed") is not False or item.get("live_apply_release_enabled") is not False:
            raise ValueError(f"{label}: live apply release approval gate {item_id} must stay held and disabled")
        if item.get("status") not in {"ready_for_owner_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: live apply release approval gate {item_id} status is invalid")
        if not item.get("hold_reason") or not item.get("release_condition"):
            raise ValueError(f"{label}: live apply release approval gate {item_id} hold_reason and release_condition are required")


def _require_rollback_checks(payload: dict[str, Any], label: str) -> None:
    items = payload.get("rollback_owner_approval_checks") or []
    _require_ids(
        items,
        "check_id",
        {
            "rollback_owner_result_capture",
            "rollback_owner_learning",
            "rollback_owner_playbook_trust",
            "rollback_owner_reviewer_queue",
            "rollback_owner_gateway_queue",
        },
        label,
        "rollback owner approval checks",
    )
    for item in items:
        item_id = item.get("check_id")
        if item.get("rollback_owner_required") is not True or item.get("rollback_owner_confirmed") is not False:
            raise ValueError(f"{label}: rollback owner approval check {item_id} must remain required and unconfirmed")
        if item.get("status") not in {"ready_for_owner_review", "approval_required", "blocked_by_policy"}:
            raise ValueError(f"{label}: rollback owner approval check {item_id} status is invalid")
        if not item.get("rollback_scope") or not item.get("hold_reason"):
            raise ValueError(f"{label}: rollback owner approval check {item_id} rollback_scope and hold_reason are required")


def _require_blocked_transitions(payload: dict[str, Any], label: str) -> None:
    items = payload.get("blocked_approval_transitions") or []
    _require_ids(
        items,
        "blocker_id",
        {
            "blocked_writer_apply_approval",
            "blocked_execution_apply_approval",
            "blocked_receipt_write_approval",
            "blocked_result_capture_write_approval",
            "blocked_gateway_queue_write_approval",
            "blocked_telegram_send_approval",
        },
        label,
        "blocked approval transitions",
    )
    for item in items:
        item_id = item.get("blocker_id")
        if item.get("severity") not in {"critical", "high"}:
            raise ValueError(f"{label}: blocked approval transition {item_id} severity is invalid")
        if item.get("status") not in {"blocked_by_policy", "approval_required"}:
            raise ValueError(f"{label}: blocked approval transition {item_id} status is invalid")
        if not item.get("blocked_action") or not item.get("blocked_until") or not _is_redacted_sha256(item.get("evidence_hash")):
            raise ValueError(f"{label}: blocked approval transition {item_id} must include action, until, and redacted evidence_hash")


def _require_actions(payload: dict[str, Any], label: str) -> None:
    items = payload.get("operator_actions") or []
    _require_ids(
        items,
        "action_id",
        {
            "review_owner_release_approval_packets",
            "verify_maintenance_window_hold",
            "verify_live_apply_approval_hold",
            "verify_rollback_owner_gate",
            "prepare_p2_132_post_release_verifier_gate",
        },
        label,
        "operator actions",
    )
    for item in items:
        item_id = item.get("action_id")
        if item.get("runtime_write_allowed") is not False:
            raise ValueError(f"{label}: operator action {item_id} must remain no-write")
        if item.get("status") not in {"ready_for_operator_review", "approval_required"}:
            raise ValueError(f"{label}: operator action {item_id} status is invalid")
        if not item.get("operator_instruction"):
            raise ValueError(f"{label}: operator action {item_id} instruction is required")


def _require_display_redaction(payload: dict[str, Any], label: str) -> None:
    redaction = 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(redaction, expected)
    if mismatches:
        raise ValueError(f"{label}: display_redaction_contract mismatch: {mismatches}")
    if not redaction.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 {}
    expected = {
        "owner_release_approval_packet_count": len(payload.get("owner_release_approval_packets") or []),
        "maintenance_window_approval_gate_count": len(payload.get("maintenance_window_approval_gates") or []),
        "live_apply_release_approval_gate_count": len(payload.get("live_apply_release_approval_gates") or []),
        "rollback_owner_approval_check_count": len(payload.get("rollback_owner_approval_checks") or []),
        "blocked_approval_transition_count": len(payload.get("blocked_approval_transitions") or []),
        "operator_action_count": len(payload.get("operator_actions") or []),
        "approval_required_packet_count": _count_status(payload.get("owner_release_approval_packets"), "approval_required"),
        "blocked_packet_count": _count_status(payload.get("owner_release_approval_packets"), "blocked_by_policy"),
        "approval_required_maintenance_window_count": _count_status(payload.get("maintenance_window_approval_gates"), "approval_required"),
        "blocked_maintenance_window_count": _count_status(payload.get("maintenance_window_approval_gates"), "blocked_by_policy"),
        "approval_required_live_apply_count": _count_status(payload.get("live_apply_release_approval_gates"), "approval_required"),
        "blocked_live_apply_count": _count_status(payload.get("live_apply_release_approval_gates"), "blocked_by_policy"),
        "approval_required_rollback_count": _count_status(payload.get("rollback_owner_approval_checks"), "approval_required"),
        "blocked_rollback_count": _count_status(payload.get("rollback_owner_approval_checks"), "blocked_by_policy"),
        "critical_blocker_count": sum(1 for item in payload.get("blocked_approval_transitions") or [] if item.get("severity") == "critical"),
    }
    mismatches = _mismatches(rollups, expected)
    if mismatches:
        raise ValueError(f"{label}: rollup counts mismatch: {mismatches}")

    zero_fields = {
        "owner_release_approved_count",
        "maintenance_window_approved_count",
        "rollback_owner_confirmed_count",
        "post_release_verifier_ready_count",
        "release_approval_pass_count",
        "live_apply_release_pass_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_fields if rollups.get(field) != 0)
    if non_zero:
        raise ValueError(f"{label}: owner release approval rollup counters must remain zero: {non_zero}")


def _require_ids(items: list[dict[str, Any]], key: str, expected: set[str], label: str, group: str) -> None:
    ids = {item.get(key) for item in items}
    if ids != expected:
        raise ValueError(f"{label}: {group} must match {sorted(expected)}")


def _require_no_forbidden_display_terms(payload: dict[str, Any], label: str) -> None:
    forbidden = {
        "work_window_transcript",
        "session_id",
        "browser_context",
        "authorization_header",
        "raw Telegram payload",
        "private reasoning",
        "raw prompt",
        "chain-of-thought",
        "批准！繼續",
        "My request for Codex",
        "In app browser",
    }
    serialized = json.dumps(payload, ensure_ascii=False)
    lower = serialized.lower()
    found = sorted(term for term in forbidden if term.lower() in lower)
    if found:
        raise ValueError(f"{label}: forbidden display terms present: {found}")


def _count_status(items: Any, status: str) -> int:
    if not isinstance(items, list):
        return 0
    return sum(1 for item in items if isinstance(item, dict) and item.get("status") == status)


def _is_redacted_sha256(value: Any) -> bool:
    return isinstance(value, str) and value.startswith("sha256:") and len(value) == 71


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