# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-fault-tolerant-agent-swarm-commit-to-a-task-whose-supporting-votes-were-cast-against-a-stale-shared-state-root-and.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-fault-tolerant-agent-swarm-commit-to-a-task-whose-supporting-votes-were-cast-against-a-stale-shared-state-root-and.warrant.json
# Markdown SHA-256:   627e18e4cb9675a6d0c3813d13c66af7f1081696c26b28fcbc482ec1c4869938
# Code AST SHA-256:   54104df37d1d8207607aea5e85ef9ef5ca448e17eea4cf83e9fbdc2851926df4
# Verified Classes:   StalePreimageQuorumError, Vote
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StalePreimageQuorumError(RuntimeError):
    """Raised when a quorum certificate's votes resolve to divergent state preimages."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    task_id: str
    state_root: str
    epoch: int
    inclusion_proof: dict  # leaf_key -> (leaf_hash, merkle_path)


def verify_vote_against_pinned_root(vote: Vote, pinned_root: str, pinned_epoch: int) -> bool:
    """A vote is only valid if it attests to the pinned root AND its inclusion proofs
    reconstruct that root. Digest-only agreement is explicitly insufficient."""
    if vote.state_root != pinned_root:
        return False
    if vote.epoch != pinned_epoch:
        return False
    for leaf_key, (leaf_hash, path) in vote.inclusion_proof.items():
        recomputed = leaf_hash
        for sibling, direction in path:
            recomputed = (
                hashlib.sha256((sibling + recomputed).encode()).hexdigest()
                if direction == "left"
                else hashlib.sha256((recomputed + sibling).encode()).hexdigest()
            )
        if recomputed != pinned_root:
            return False
    return True


def assemble_quorum(votes: list[Vote], pinned_root: str, pinned_epoch: int, quorum: int) -> str:
    """Assemble a QC. Dedup keys on the full attested tuple, not (agent_id, task_id)."""
    seen: set[tuple[str, str, str, int]] = set()
    valid = 0
    for v in votes:
        key = (v.agent_id, v.task_id, v.state_root, v.epoch)
        if key in seen:
            continue
        seen.add(key)
        if not verify_vote_against_pinned_root(v, pinned_root, pinned_epoch):
            # An honest agent that voted on a stale preimage lands here.
            # It is a rejection, not a support — and not a silent equivocation.
            continue
        valid += 1

    if valid < quorum:
        raise StalePreimageQuorumError(
            f"Only {valid}/{quorum} votes reconstructed pinned root {pinned_root} "
            f"at epoch {pinned_epoch}; remaining votes attested divergent preimages."
        )
    return hashlib.sha256(f"{pinned_root}:{pinned_epoch}:{valid}".encode()).hexdigest()
