"""
AI Agent Redis dry-run gate snapshot.

Loads the latest committed, read-only P2-403C gate for Redis Streams
consumer group dry-run, handoff envelopes, ack/dead-letter decisions, and
replay idempotency. This module never connects to Redis, creates consumer
groups, writes queues, sends Telegram messages, or performs learning writeback.
"""

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_redis_dry_run_gate_*.json"
_SCHEMA_VERSION = "ai_agent_redis_dry_run_gate_v1"


def load_latest_ai_agent_redis_dry_run_gate(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed AI Agent Redis dry-run gate snapshot."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(
            f"no AI Agent Redis dry-run 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")
    _require_schema(payload, str(latest))
    _require_read_only_boundaries(payload, str(latest))
    _require_fixture_contract(payload, str(latest))
    _require_handoff_safety(payload, str(latest))
    _require_rollup_consistency(payload, str(latest))
    return payload


def _require_schema(payload: dict[str, Any], label: str) -> None:
    actual = payload.get("schema_version")
    if actual != _SCHEMA_VERSION:
        raise ValueError(f"{label}: expected schema_version={_SCHEMA_VERSION}, got {actual!r}")
    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") != "dry_run_contract_only_no_redis_runtime":
        raise ValueError(f"{label}: runtime_authority must stay dry_run_contract_only_no_redis_runtime")


def _require_read_only_boundaries(payload: dict[str, Any], label: str) -> None:
    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}")

    truth = payload.get("dry_run_truth") or {}
    false_flags = {
        "redis_connection_allowed",
        "consumer_group_created",
        "xadd_allowed",
        "xreadgroup_allowed",
        "ack_allowed",
        "dead_letter_write_allowed",
        "replay_runtime_allowed",
        "telegram_send_allowed",
        "learning_writeback_allowed",
    }
    unsafe = sorted(flag for flag in false_flags if truth.get(flag) is not False)
    if unsafe:
        raise ValueError(f"{label}: dry-run truth flags must remain false: {unsafe}")

    zero_counts = {
        "live_dry_run_event_count",
        "live_ack_count",
        "live_dead_letter_count",
        "live_replay_count",
    }
    non_zero = sorted(key for key in zero_counts if truth.get(key) != 0)
    if non_zero:
        raise ValueError(f"{label}: live dry-run counts must remain zero: {non_zero}")


def _require_fixture_contract(payload: dict[str, Any], label: str) -> None:
    contract = payload.get("consumer_group_dry_run_contract") or {}
    if contract.get("fixture_only") is not True:
        raise ValueError(f"{label}: dry-run contract must stay fixture_only")
    if contract.get("redis_network_call_allowed") is not False:
        raise ValueError(f"{label}: Redis network calls must remain blocked")
    if not contract.get("required_fixture_fields"):
        raise ValueError(f"{label}: required_fixture_fields must not be empty")


def _require_handoff_safety(payload: dict[str, Any], label: str) -> None:
    envelope = payload.get("handoff_envelope_contract") or {}
    required_fields = set(envelope.get("required_fields") or [])
    required_minimum = {
        "event_id",
        "trace_id",
        "session_id",
        "incident_id",
        "from_agent",
        "to_agent",
        "handoff_type",
        "redacted_evidence_ref",
        "idempotency_key",
    }
    missing = sorted(required_minimum - required_fields)
    if missing:
        raise ValueError(f"{label}: handoff envelope missing required fields: {missing}")
    if envelope.get("redacted_evidence_required") is not True:
        raise ValueError(f"{label}: redacted evidence refs must be required")
    if envelope.get("idempotency_key_required") is not True:
        raise ValueError(f"{label}: idempotency key must be required")

    ack_contract = payload.get("ack_dead_letter_replay_contract") or {}
    for flag in ("ack_requires_verifier", "dead_letter_requires_reason", "replay_requires_idempotency"):
        if ack_contract.get(flag) is not True:
            raise ValueError(f"{label}: {flag} must be true")
    if ack_contract.get("runtime_replay_allowed") is not False:
        raise ValueError(f"{label}: runtime replay must remain blocked")

    redaction = payload.get("display_redaction_contract") or {}
    if redaction.get("redaction_required") is not True:
        raise ValueError(f"{label}: frontend redaction must be required")
    for flag in ("raw_payload_display_allowed", "private_reasoning_display_allowed", "secret_value_display_allowed"):
        if redaction.get(flag) is not False:
            raise ValueError(f"{label}: {flag} must remain false")


def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    rollups = payload.get("rollups") or {}
    steps = payload.get("dry_run_steps") or []
    lanes = payload.get("handoff_lanes") or []
    envelope = payload.get("handoff_envelope_contract") or {}
    truth = payload.get("dry_run_truth") or {}
    expected_counts = {
        "source_ref_count": len(payload.get("source_refs") or []),
        "dry_run_step_count": len(steps),
        "handoff_lane_count": len(lanes),
        "blocked_runtime_action_count": len({step.get("blocked_runtime_action") for step in steps}),
        "required_handoff_field_count": len(envelope.get("required_fields") or []),
        "forbidden_field_count": len(envelope.get("forbidden_fields") or []),
    }
    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}")

    contract_ready = sorted(
        step.get("step_id") for step in steps if step.get("status") == "contract_ready"
    )
    if sorted(rollups.get("contract_ready_step_ids") or []) != contract_ready:
        raise ValueError(f"{label}: rollups.contract_ready_step_ids mismatch")

    approval_required = sorted(
        step.get("step_id") for step in steps if step.get("status") == "approval_required"
    )
    if sorted(rollups.get("approval_required_step_ids") or []) != approval_required:
        raise ValueError(f"{label}: rollups.approval_required_step_ids mismatch")

    live_total = sum(
        int(truth.get(key) or 0)
        for key in (
            "live_dry_run_event_count",
            "live_ack_count",
            "live_dead_letter_count",
            "live_replay_count",
        )
    )
    if rollups.get("live_truth_count_total") != live_total:
        raise ValueError(f"{label}: rollups.live_truth_count_total mismatch")
