# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-in-a-bft-agent-quorum-signs-a-decision-it-cannot-reconstruct-the-equivocation-without-memory-fault.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-in-a-bft-agent-quorum-signs-a-decision-it-cannot-reconstruct-the-equivocation-without-memory-fault.warrant.json
# Markdown SHA-256:   4619ba119361701aad0df5fa50909ec0f8e372184c3dc0cbfcc785a683ac412c
# Code AST SHA-256:   171f8b3d2d87c7398c6fa91913a875b27aae46a09a2c4af8cae1f1d8fdcabad9
# Verified Classes:   WitnessUnavailableError, WitnessRedundancyViolation, SignedVote, PreImageStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class WitnessUnavailableError(RuntimeError):
    """Raised when a signed vote's pre-image cannot be produced on demand."""
    pass


class WitnessRedundancyViolation(RuntimeError):
    """Raised when a committed hash has fewer than f+1 pre-image holders."""
    pass


@dataclass
class SignedVote:
    signer: str
    round: int
    payload_hash: str
    signature: str  # opaque; validity assumed checked elsewhere


@dataclass
class PreImageStore:
    # Durable, retention-bounded store keyed by payload hash.
    # Deliberately separate from the agent's reasoning context.
    _store: dict = field(default_factory=dict)

    def pin(self, payload_hash: str, transition: dict) -> None:
        self._store[payload_hash] = transition

    def get(self, payload_hash: str) -> Optional[dict]:
        return self._store.get(payload_hash)

    def evict(self, payload_hash: str) -> None:
        self._store.pop(payload_hash, None)


def canonical_hash(transition: dict) -> str:
    return hashlib.sha256(
        json.dumps(transition, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def witness_for_vote(vote: SignedVote, store: PreImageStore) -> dict:
    """Return the pre-image a signer must produce to justify its vote.

    Forbidden: reconstructing from a semantic summary. If the pinned
    pre-image is gone, the vote is unwitnessed and must be reported as
    such, not confabulated.
    """
    transition = store.get(vote.payload_hash)
    if transition is None:
        raise WitnessUnavailableError(
            f"signer {vote.signer} signed h={vote.payload_hash[:12]} "
            f"at round {vote.round} but cannot produce the pre-image; "
            f"do not re-derive from summary"
        )
    if canonical_hash(transition) != vote.payload_hash:
        raise WitnessUnavailableError(
            f"pre-image for h={vote.payload_hash[:12]} does not hash-match; "
            f"summary-derived reconstruction is not a witness"
        )
    return transition


def check_witness_redundancy(
    committed_hash: str,
    votes: list[SignedVote],
    stores: dict[str, PreImageStore],
    f: int,
) -> None:
    """Enforce: at least f+1 agents hold the pre-image for a committed hash.

    Signatures count toward the 3f+1 threshold; pre-image holders count
    toward witness redundancy. The two counts are independent.
    """
    holders = 0
    for v in votes:
        if v.payload_hash != committed_hash:
            continue
        store = stores.get(v.signer)
        if store is None:
            continue
        try:
            witness_for_vote(v, store)
            holders += 1
        except WitnessUnavailableError:
            continue
    if holders < f + 1:
        raise WitnessRedundancyViolation(
            f"committed h={committed_hash[:12]} has {holders} pre-image "
            f"holder(s), need f+1={f + 1}; QC is valid but unbacked"
        )


def view_change_reconstruct(
    votes_by_round: dict[int, list[SignedVote]],
    stores: dict[str, PreImageStore],
    f: int,
) -> tuple[int, dict]:
    """Select the highest round anchored by f+1 pre-images, not by QC alone."""
    for rnd in sorted(votes_by_round, reverse=True):
        votes = votes_by_round[rnd]
        if not votes:
            continue
        target_hash = votes[0].payload_hash
        try:
            check_witness_redundancy(target_hash, votes, stores, f)
        except WitnessRedundancyViolation:
            # Hold, do not anchor. Flag for state-sync repair.
            continue
        return rnd, witness_for_vote(votes[0], stores[votes[0].signer])
    raise WitnessUnavailableError(
        "no round has f+1 pre-image holders; view change cannot anchor safely"
    )
