#!/usr/bin/env python3
"""
ONE BIG BACKEND — ALGORITHMICA / INFORMATION-THEORETIC CIVIC TRANSPORT LAYER
(`obb_info_theoretic_channel.py`)
License: GNU AGPLv3
External Dependencies: 0 (100% Python Standard Library + local obb_primitives & obb_epistemic_lattice)
Attestation: probabilistic_structural

Zero computational hardness assumptions. Remains mathematically secure even in
Impagliazzo's "Algorithmica" world (a practical low-degree P = NP solver or
infinite-compute adversary):

  1. OneTimePadBook (Shannon 1949):
       - True Vernam cipher over pre-shared hardware-RNG pad drives exchanged in
         person (e.g., at City Hall, a Credit Union vault, or co-op meeting).
       - Strict burn-after-read non-overlapping interval tracking on BOTH sender
         and receiver -> guarantees zero pad reuse and instant replay rejection.
       - A single $80 1 TB SSD holds > 10,000 years of typical municipal OBB JSON.

  2. WegmanCarterMac over Mersenne Prime Field F_p, p = 2^127 - 1 (Wegman & Carter 1981):
       - 100% information-theoretically unforgeable Encrypt-then-MAC authentication.
       - Uses a fresh one-time uniform key pair (r, s) in F_p x F_p per message
         (32 bytes of pad per message regardless of message length!).
       - Forgery probability even against an infinite-compute NP-oracle is strictly
         bounded by:  Pr[forge] <= (ceil(|M| / 15) + 1) / (2^127 - 1)  <  10^-35.

  3. ShamirQuorum over F_p, p = 2^127 - 1 (Shamir 1979):
       - Information-theoretic t-of-n threshold secret sharing across independent
         civic anchors (e.g., 3 of 5 Roanoke/Winnipeg institutions).
       - Any t - 1 shares reveal strictly 0 bits of mutual information about the secret.

  4. AlgorithmicaCivicChannel:
       - Combines OTP + Wegman-Carter MAC with Node 0 (`ObbSafetyFloor` Zero-PII),
         Node 1 (`SweetbrierEpistemicGate` 3-valued K3/B4 + LeCun Inversion), and
         Node 2 (`ObbUndoEngine` 1-Click local Undo) over dedicated municipal fiber.
"""

from __future__ import annotations

import hmac
import json
import math
import secrets
from dataclasses import dataclass
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple

from obb_epistemic_lattice import (
    EpistemicBoundaryError,
    EpistemicClaim,
    EpistemicTruth,
    SourceKind,
    SweetbrierEpistemicGate,
)
from obb_primitives import ObbSafetyFloor, StateSnapshot, deep_freeze, deep_thaw

# 127-bit Mersenne Prime p = 2^127 - 1
MERSENNE_P: int = (1 << 127) - 1
FIELD_MASK_127: int = (1 << 127) - 1
BLOCK_BYTES: int = 15  # 120 bits per block < 127 bits (injective in F_p)
BLOCK_SENTINEL: int = 1 << 120


class PadExhaustedError(RuntimeError):
    """Raised when a pre-shared One-Time Pad book does not have enough unused bytes left."""


class PadReuseError(PermissionError):
    """Raised immediately if an envelope attempts to reuse or replay an already-burned OTP slice."""


class InfoTheoreticSecurityError(PermissionError):
    """Raised when a Wegman-Carter information-theoretic MAC fails verification (tampered bit/header)."""


class QuorumThresholdError(ValueError):
    """Raised when fewer than `t` valid distinct Shamir witness shares are presented."""


# =============================================================================
# 1. ONE-TIME PAD BOOK (SHANNON PERFECT SECRECY + BURN-AFTER-READ GUARD)
# =============================================================================


class OneTimePadBook:
    """
    Single-direction pre-shared One-Time Pad tape with strict burn-after-read zeroization
    and non-overlapping interval enforcement.
    """

    def __init__(self, pad_id: str, raw_pad_bytes: bytes) -> None:
        if len(raw_pad_bytes) < 64:
            raise ValueError("OneTimePadBook requires at least 64 bytes of random pad material.")
        self.pad_id = pad_id
        self._tape = bytearray(raw_pad_bytes)
        self._total_len = len(raw_pad_bytes)
        self._cursor: int = 0
        self._consumed_intervals: List[Tuple[int, int]] = []

    @classmethod
    def create_paired_books(
        cls,
        pad_id: str,
        size_bytes: int = 65536,
        trng_bytes: Optional[bytes] = None,
    ) -> Tuple["OneTimePadBook", "OneTimePadBook"]:
        """
        Simulate an in-person civic key ceremony minting two identical mirrored copies
        of a single-direction hardware-RNG pad (one for sender, one for receiver).
        """
        raw = trng_bytes if trng_bytes is not None else secrets.token_bytes(size_bytes)
        return cls(pad_id, raw), cls(pad_id, raw)

    @property
    def total_bytes(self) -> int:
        return self._total_len

    @property
    def remaining_bytes(self) -> int:
        used = sum(end - start for start, end in self._consumed_intervals)
        return self._total_len - used

    def _assert_unconsumed(self, start: int, end: int) -> None:
        if start < 0 or end <= start or end > self._total_len:
            raise PadExhaustedError(
                f"Requested OTP slice [{start}, {end}) out of bounds for pad '{self.pad_id}' (len={self._total_len})."
            )
        for c_start, c_end in self._consumed_intervals:
            if start < c_end and c_start < end:
                raise PadReuseError(
                    f"OTP REUSE / REPLAY BLOCKED on pad '{self.pad_id}': slice [{start}, {end}) "
                    f"overlaps already-burned slice [{c_start}, {c_end})."
                )

    def _burn_slice(self, start: int, end: int) -> bytes:
        self._assert_unconsumed(start, end)
        out = bytes(self._tape[start:end])
        # Burn-after-read: zeroize consumed pad bytes immediately
        for idx in range(start, end):
            self._tape[idx] = 0
        self._consumed_intervals.append((start, end))
        if end > self._cursor:
            self._cursor = end
        return out

    def consume_next(self, n_bytes: int) -> Tuple[int, bytes]:
        """Sender consumes the next unused contiguous slice and permanently burns it."""
        if n_bytes <= 0:
            raise ValueError("n_bytes must be strictly positive.")
        start = self._cursor
        end = start + n_bytes
        if end > self._total_len:
            raise PadExhaustedError(
                f"Pad '{self.pad_id}' exhausted: need {n_bytes} B, only {self._total_len - start} B ahead of cursor."
            )
        return start, self._burn_slice(start, end)

    def consume_at(self, offset: int, n_bytes: int) -> bytes:
        """Receiver consumes the exact slice specified by the envelope header (zero reuse allowed)."""
        if n_bytes <= 0:
            raise ValueError("n_bytes must be strictly positive.")
        return self._burn_slice(offset, offset + n_bytes)

    def draw_uniform_field_pair(self) -> Tuple[int, int, int, int]:
        """
        Draw two strictly uniform elements (r, s) in F_(2^127 - 1) using rejection sampling
        from unused pad bytes. Returns (r, s, pad_offset, pad_byte_len).
        """
        start = self._cursor
        vals: List[int] = []
        while len(vals) < 2:
            _, chunk = self.consume_next(16)
            candidate = int.from_bytes(chunk, "big") & FIELD_MASK_127
            if candidate < MERSENNE_P:
                vals.append(candidate)
        total_len = self._cursor - start
        return vals[0], vals[1], start, total_len

    @staticmethod
    def extract_uniform_field_pair(pad_slice: bytes) -> Tuple[int, int]:
        """Deterministically extract the exact same (r, s) pair on the receiver side."""
        if len(pad_slice) < 32 or (len(pad_slice) % 16) != 0:
            raise InfoTheoreticSecurityError("Malformed Wegman-Carter key pad slice length.")
        vals: List[int] = []
        for idx in range(0, len(pad_slice), 16):
            candidate = int.from_bytes(pad_slice[idx : idx + 16], "big") & FIELD_MASK_127
            if candidate < MERSENNE_P:
                vals.append(candidate)
                if len(vals) == 2:
                    return vals[0], vals[1]
        raise InfoTheoreticSecurityError("Key pad slice did not contain two valid field elements.")

    @staticmethod
    def xor_bytes(data: bytes, key: bytes) -> bytes:
        if len(data) != len(key):
            raise ValueError(f"OTP length mismatch: data={len(data)} B vs key={len(key)} B.")
        return bytes(a ^ b for a, b in zip(data, key))

    @staticmethod
    def estimate_drive_longevity_years(
        drive_terabytes: float = 1.0,
        messages_per_day: int = 500,
        avg_message_bytes: int = 512,
        mac_key_bytes_per_msg: int = 32,
    ) -> float:
        """
        Estimate how many years a single physical pre-shared SSD lasts for a municipal
        or co-op One Big Backend network (OTP ciphertext + Wegman-Carter MAC key).
        """
        total_bytes = drive_terabytes * 1e12
        bytes_per_day = messages_per_day * (avg_message_bytes + mac_key_bytes_per_msg)
        return round(total_bytes / (bytes_per_day * 365.25), 1)


# =============================================================================
# 2. WEGMAN-CARTER UNIVERSAL-HASH MAC OVER F_(2^127 - 1)
# =============================================================================


class WegmanCarterMac:
    """
    Polynomial universal-hash authenticator over F_p (p = 2^127 - 1) with one-time mask s.
    Information-theoretically unforgeable even against an adversary with an O(n) NP-oracle.
    """

    @staticmethod
    def encode_message_blocks(message: bytes) -> List[int]:
        """
        Injectively encode an arbitrary byte string into field elements in F_p:
          - Each 15-byte chunk gets a 2^120 sentinel bit so empty/zero chunks never vanish.
          - Final element encodes exact byte length `len(message)` to prevent length extension.
        """
        blocks: List[int] = []
        for idx in range(0, len(message), BLOCK_BYTES):
            chunk = message[idx : idx + BLOCK_BYTES]
            blocks.append(int.from_bytes(chunk, "big") | BLOCK_SENTINEL)
        # Domain-separated exact byte length block (strictly < 2^120, distinct from chunk blocks)
        blocks.append(len(message) % MERSENNE_P)
        return blocks

    @classmethod
    def forgery_probability_bound(cls, message_len_bytes: int) -> float:
        """Exact information-theoretic upper bound k / (2^127 - 1) on single-attempt forgery."""
        k = max(1, math.ceil(message_len_bytes / BLOCK_BYTES)) + 1
        return k / float(MERSENNE_P)

    @classmethod
    def compute_tag(cls, message: bytes, r: int, s: int) -> bytes:
        """
        Compute tag = (Sum_{j=1..k} m_j * r^j + s) mod (2^127 - 1) as 16 big-endian bytes.
        """
        if not (0 <= r < MERSENNE_P and 0 <= s < MERSENNE_P):
            raise ValueError("Wegman-Carter key (r, s) must lie in F_(2^127 - 1).")
        blocks = cls.encode_message_blocks(message)
        # Horner evaluation of Sum_{j=1..k} m_j * r^j = r * (m_1 + r * (m_2 + ... + r * m_k))
        acc = 0
        for coeff in reversed(blocks):
            acc = ((acc + coeff) * r) % MERSENNE_P
        tag_int = (acc + s) % MERSENNE_P
        return tag_int.to_bytes(16, "big")

    @classmethod
    def verify_tag(cls, message: bytes, r: int, s: int, observed_tag: bytes) -> bool:
        expected = cls.compute_tag(message, r, s)
        return hmac.compare_digest(expected, observed_tag)


# =============================================================================
# 3. SHAMIR t-OF-n INFORMATION-THEORETIC WITNESS QUORUM OVER F_(2^127 - 1)
# =============================================================================


@dataclass(frozen=True)
class WitnessShare:
    """Single civic anchor's Shamir threshold share over F_(2^127 - 1)."""

    quorum_id: str
    anchor_name: str
    x_index: int
    threshold_t: int
    total_n: int
    secret_byte_len: int
    y_blocks: Tuple[int, ...]


class ShamirQuorum:
    """
    Exact Shamir t-of-n Secret Sharing over F_(2^127 - 1) for municipal/co-op root stewardship.
    Any t - 1 shares reveal strictly 0 bits of mutual information even under P = NP.
    """

    @staticmethod
    def _eval_poly(coeffs: Sequence[int], x: int) -> int:
        acc = 0
        for c in reversed(coeffs):
            acc = (acc * x + c) % MERSENNE_P
        return acc

    @staticmethod
    def _lagrange_interpolate_zero(points: Sequence[Tuple[int, int]]) -> int:
        """Exact Lagrange interpolation at x = 0 over F_(2^127 - 1)."""
        secret = 0
        k = len(points)
        for i in range(k):
            xi, yi = points[i]
            num = 1
            den = 1
            for j in range(k):
                if i == j:
                    continue
                xj = points[j][0]
                num = (num * (-xj % MERSENNE_P)) % MERSENNE_P
                den = (den * ((xi - xj) % MERSENNE_P)) % MERSENNE_P
            inv_den = pow(den, -1, MERSENNE_P)
            secret = (secret + yi * num * inv_den) % MERSENNE_P
        return secret

    @classmethod
    def split_secret(
        cls,
        quorum_id: str,
        secret_bytes: bytes,
        anchor_names: Sequence[str],
        threshold_t: int,
    ) -> List[WitnessShare]:
        n = len(anchor_names)
        if threshold_t < 2 or threshold_t > n:
            raise ValueError(f"Threshold t must satisfy 2 <= t <= n (got t={threshold_t}, n={n}).")
        if len(set(anchor_names)) != n:
            raise ValueError("All civic anchor names must be unique.")
        if not secret_bytes:
            raise ValueError("secret_bytes must be non-empty.")

        # Split arbitrary byte secret into 15-byte field blocks (< 2^120 < MERSENNE_P)
        secret_blocks: List[int] = [
            int.from_bytes(secret_bytes[i : i + BLOCK_BYTES], "big")
            for i in range(0, len(secret_bytes), BLOCK_BYTES)
        ]

        # Independent random degree-(t-1) polynomial for each block
        polys: List[List[int]] = [
            [blk] + [secrets.randbelow(MERSENNE_P) for _ in range(threshold_t - 1)]
            for blk in secret_blocks
        ]

        shares: List[WitnessShare] = []
        for idx, anchor in enumerate(anchor_names, start=1):
            y_vals = tuple(cls._eval_poly(poly, idx) for poly in polys)
            shares.append(
                WitnessShare(
                    quorum_id=quorum_id,
                    anchor_name=anchor,
                    x_index=idx,
                    threshold_t=threshold_t,
                    total_n=n,
                    secret_byte_len=len(secret_bytes),
                    y_blocks=y_vals,
                )
            )
        return shares

    @classmethod
    def reconstruct_secret(cls, shares: Sequence[WitnessShare]) -> bytes:
        if not shares:
            raise QuorumThresholdError("No witness shares provided.")
        first = shares[0]
        if len(shares) < first.threshold_t:
            raise QuorumThresholdError(
                f"Insufficient quorum: need at least {first.threshold_t} of {first.total_n} anchors "
                f"(got {len(shares)}; {first.threshold_t - 1} shares reveal 0 bits of information)."
            )

        seen_x = set()
        for sh in shares:
            if sh.quorum_id != first.quorum_id or sh.threshold_t != first.threshold_t:
                raise QuorumThresholdError("Mismatched quorum_id or threshold across shares.")
            if sh.x_index in seen_x:
                raise QuorumThresholdError(f"Duplicate witness share x_index={sh.x_index}.")
            seen_x.add(sh.x_index)

        subset = list(shares[: first.threshold_t])
        num_blocks = len(first.y_blocks)
        out = bytearray()
        remaining = first.secret_byte_len

        for blk_idx in range(num_blocks):
            pts = [(sh.x_index, sh.y_blocks[blk_idx]) for sh in subset]
            val = cls._lagrange_interpolate_zero(pts)
            chunk_len = min(BLOCK_BYTES, remaining)
            out.extend(val.to_bytes(chunk_len, "big"))
            remaining -= chunk_len

        return bytes(out)


# =============================================================================
# 4. DROP-IN ALGORITHMICA CIVIC CHANNEL (OTP + WEGMAN-CARTER + SWEETBRIER □)
# =============================================================================


@dataclass(frozen=True)
class InfoTheoreticEnvelope:
    """Zero-hardness wire envelope for local municipal dark-fiber rings (e.g., RVBA)."""

    pad_id: str
    sender_id: str
    receiver_id: str
    service_code: str
    lane: str  # "FINALIZED" | "STAGED_UNCONFIRMED"
    otp_offset: int
    otp_len: int
    ciphertext_hex: str
    mac_pad_offset: int
    mac_pad_len: int
    wc_tag_hex: str
    max_forgery_prob_bound: float
    attestation: str = "probabilistic_structural_information_theoretic"


class AlgorithmicaCivicNode:
    """
    Sovereign local civic node communicating with peers over dedicated municipal fiber
    with ZERO reliance on computational hardness (no RSA, ECC, AES, or SHA-256 on the wire).
    """

    VALID_LANES = frozenset({"FINALIZED", "STAGED_UNCONFIRMED"})

    def __init__(self, node_id: str) -> None:
        self.node_id = node_id
        self.safety_floor = ObbSafetyFloor()
        self.epistemic_gate = SweetbrierEpistemicGate(node_id=node_id, safety_floor=self.safety_floor)
        self._outbound_pads: Dict[str, OneTimePadBook] = {}
        self._inbound_pads: Dict[str, OneTimePadBook] = {}
        self.received_envelopes: List[InfoTheoreticEnvelope] = []

    def install_peer_pads(
        self,
        peer_node_id: str,
        outbound_pad: OneTimePadBook,
        inbound_pad: OneTimePadBook,
    ) -> None:
        self._outbound_pads[peer_node_id] = outbound_pad
        self._inbound_pads[peer_node_id] = inbound_pad

    @staticmethod
    def _auth_bytes(
        pad_id: str,
        sender_id: str,
        receiver_id: str,
        service_code: str,
        lane: str,
        otp_offset: int,
        otp_len: int,
        mac_pad_offset: int,
        mac_pad_len: int,
        ciphertext: bytes,
    ) -> bytes:
        header = json.dumps(
            {
                "pad_id": pad_id,
                "sender_id": sender_id,
                "receiver_id": receiver_id,
                "service_code": service_code,
                "lane": lane,
                "otp_offset": otp_offset,
                "otp_len": otp_len,
                "mac_pad_offset": mac_pad_offset,
                "mac_pad_len": mac_pad_len,
            },
            sort_keys=True,
        ).encode("utf-8")
        return header + b"\x00" + ciphertext

    def send_claim(
        self,
        peer: "AlgorithmicaCivicNode",
        service_code: str,
        claim: EpistemicClaim,
        lane: str = "FINALIZED",
    ) -> Tuple[InfoTheoreticEnvelope, StateSnapshot]:
        if lane not in self.VALID_LANES:
            raise ValueError(f"Unsupported lane '{lane}'.")
        if peer.node_id not in self._outbound_pads:
            raise KeyError(f"No pre-shared outbound OTP book installed for peer '{peer.node_id}'.")

        # Node 0: Zero-PII check
        self.safety_floor.assert_clean(claim.payload)

        # Node 1: Strict 3-valued epistemic egress boundary
        if lane == "FINALIZED":
            SweetbrierEpistemicGate.assert_commit_ready(claim)
        elif claim.truth_value is not EpistemicTruth.UNKNOWN:
            raise EpistemicBoundaryError(
                f"STAGED_UNCONFIRMED lane accepts UNKNOWN claims only (got {claim.truth_value.value})."
            )

        pad = self._outbound_pads[peer.node_id]
        plaintext = json.dumps(claim.to_wire_dict(), sort_keys=True).encode("utf-8")

        # Encrypt-then-MAC: Shannon OTP + Wegman-Carter F_(2^127-1) MAC
        otp_offset, otp_key = pad.consume_next(len(plaintext))
        ciphertext = OneTimePadBook.xor_bytes(plaintext, otp_key)
        r, s, mac_offset, mac_len = pad.draw_uniform_field_pair()
        auth_blob = self._auth_bytes(
            pad.pad_id,
            self.node_id,
            peer.node_id,
            service_code,
            lane,
            otp_offset,
            len(ciphertext),
            mac_offset,
            mac_len,
            ciphertext,
        )
        tag = WegmanCarterMac.compute_tag(auth_blob, r, s)

        env = InfoTheoreticEnvelope(
            pad_id=pad.pad_id,
            sender_id=self.node_id,
            receiver_id=peer.node_id,
            service_code=service_code,
            lane=lane,
            otp_offset=otp_offset,
            otp_len=len(ciphertext),
            ciphertext_hex=ciphertext.hex(),
            mac_pad_offset=mac_offset,
            mac_pad_len=mac_len,
            wc_tag_hex=tag.hex(),
            max_forgery_prob_bound=WegmanCarterMac.forgery_probability_bound(len(auth_blob)),
        )
        snap = peer.receive_envelope(env)
        return env, snap

    def receive_envelope(self, env: InfoTheoreticEnvelope) -> StateSnapshot:
        if env.receiver_id != self.node_id:
            raise InfoTheoreticSecurityError(f"Misrouted envelope for '{env.receiver_id}'.")
        if env.sender_id not in self._inbound_pads:
            raise InfoTheoreticSecurityError(f"No pre-shared inbound OTP book for '{env.sender_id}'.")

        pad = self._inbound_pads[env.sender_id]
        if pad.pad_id != env.pad_id:
            raise InfoTheoreticSecurityError(f"Pad ID mismatch: expected '{pad.pad_id}', got '{env.pad_id}'.")

        ciphertext = bytes.fromhex(env.ciphertext_hex)
        if len(ciphertext) != env.otp_len:
            raise InfoTheoreticSecurityError("Ciphertext length mismatch.")

        # 1. Verify non-reuse AND consume exact MAC key slice FIRST (Encrypt-then-MAC!)
        mac_slice = pad.consume_at(env.mac_pad_offset, env.mac_pad_len)
        r, s = OneTimePadBook.extract_uniform_field_pair(mac_slice)
        auth_blob = self._auth_bytes(
            env.pad_id,
            env.sender_id,
            env.receiver_id,
            env.service_code,
            env.lane,
            env.otp_offset,
            env.otp_len,
            env.mac_pad_offset,
            env.mac_pad_len,
            ciphertext,
        )
        observed_tag = bytes.fromhex(env.wc_tag_hex)
        if not WegmanCarterMac.verify_tag(auth_blob, r, s, observed_tag):
            raise InfoTheoreticSecurityError(
                "Wegman-Carter F_(2^127-1) MAC verification FAILED: mid-flight tampering or forgery detected."
            )

        # 2. Consume exact OTP decryption slice & recover plaintext
        otp_key = pad.consume_at(env.otp_offset, env.otp_len)
        plaintext = OneTimePadBook.xor_bytes(ciphertext, otp_key)
        raw_claim = json.loads(plaintext.decode("utf-8"))

        # 3. Receiver-side Node 0 (Zero-PII) + Node 1 (LeCun Inversion & K3/B4) + Node 2 (1-Click Undo)
        inbound_claim = self.epistemic_gate.ingest(
            claim_id=raw_claim["claim_id"],
            subject=raw_claim["subject"],
            payload=raw_claim["payload"],
            proposed_truth=EpistemicTruth(raw_claim["truth_value"]),
            source_kind=SourceKind(raw_claim["source_kind"]),
            source_id=env.sender_id,
            note=f"Received over Algorithmica IT-channel ({env.service_code}, pad={env.pad_id}).",
        )
        self.received_envelopes.append(env)
        if env.lane == "FINALIZED":
            return self.epistemic_gate.commit_verified(f"IT:{env.service_code}", inbound_claim)
        return self.epistemic_gate.stage_unconfirmed(f"IT_STAGED:{env.service_code}", inbound_claim)


if __name__ == "__main__":
    # Live Roanoke RVBA "Algorithmica" Zero-Hardness Civic Fiber Demo
    roanoke_anchors = [
        "City_Hall_Roanoke",
        "Council_Community_Services",
        "Rescue_Mission_SE",
        "Melrose_Plaza_Goodwill_NW",
        "RVBA_Fiber_Board",
    ]
    master_seed = secrets.token_bytes(32)
    shares = ShamirQuorum.split_secret("ROA-QUORUM-2026", master_seed, roanoke_anchors, threshold_t=3)
    recovered = ShamirQuorum.reconstruct_secret([shares[0], shares[2], shares[4]])
    assert recovered == master_seed

    rescue = AlgorithmicaCivicNode("US-VA-ROA/NONPROFIT/rescue-mission")
    ccs = AlgorithmicaCivicNode("US-VA-ROA/NONPROFIT/council-community-services")
    rm_to_ccs_s, rm_to_ccs_r = OneTimePadBook.create_paired_books("RVBA-PAD-RM-CCS-01", size_bytes=16384)
    ccs_to_rm_s, ccs_to_rm_r = OneTimePadBook.create_paired_books("RVBA-PAD-CCS-RM-01", size_bytes=16384)
    rescue.install_peer_pads(ccs.node_id, rm_to_ccs_s, ccs_to_rm_r)
    ccs.install_peer_pads(rescue.node_id, ccs_to_rm_s, rm_to_ccs_r)

    claim = rescue.epistemic_gate.ingest(
        claim_id="IT-ROA-001",
        subject="hope_home:capacity:rescue_mission",
        payload={"site": "Rescue Mission SE", "beds_open_aggregate": 6, "client_pii_bytes": 0},
        proposed_truth=EpistemicTruth.VERIFIED,
        source_kind=SourceKind.HUMAN_ATTESTED,
        source_id="shift_supervisor",
    )
    env, snap = rescue.send_claim(ccs, "hope_home.capacity.it.v1", claim, lane="FINALIZED")

    print(
        json.dumps(
            {
                "attestation": "probabilistic_structural",
                "computational_hardness_assumptions": 0,
                "field_prime_bits": 127,
                "max_forgery_prob_bound": f"{env.max_forgery_prob_bound:.3e}",
                "shamir_3_of_5_exact_recovery": recovered == master_seed,
                "one_tb_ssd_longevity_years_at_500_msgs_day": OneTimePadBook.estimate_drive_longevity_years(1.0, 500, 512),
                "receiver_snapshot_id": snap.snapshot_id,
                "sender_pad_remaining_bytes": rm_to_ccs_s.remaining_bytes,
            },
            indent=2,
        )
    )
