# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-quorum-accept-a-commitment-it-cannot-later-reconstruct-and-how-does-equivocation-hiding-break-bft-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-quorum-accept-a-commitment-it-cannot-later-reconstruct-and-how-does-equivocation-hiding-break-bft-task-commitment.warrant.json
# Markdown SHA-256:   2be5ed65296d69084568f4764f3ad88c213294b360a1e2e817dbbca64023f0c6
# Code AST SHA-256:   1f225dd1c7acd9caf093025533045428fcf19d5d5b11587b0bb066ae52b6b265
# Verified Classes:   CommitmentReconstructionError, CanonicalCommitment, CommitmentStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CommitmentReconstructionError(RuntimeError):
    """Raised when a certified commitment cannot be reconstructed from durable state."""
    pass


@dataclass
class CanonicalCommitment:
    task_id: str
    epoch: int
    agent_id: str
    content: dict  # full semantic content, e.g. {"summary": ..., "citations": [...]}

    def canonical_bytes(self) -> bytes:
        # Deterministic serialization: sorted keys, no whitespace variance.
        return json.dumps(self.content, sort_keys=True, separators=(",", ":")).encode("utf-8")

    def digest(self) -> str:
        return hashlib.sha256(self.canonical_bytes()).hexdigest()


class CommitmentStore:
    """Durable store; reconstruction reads here, never re-runs tools."""

    def __init__(self) -> None:
        self._persisted: dict[tuple[str, int, str], bytes] = {}

    def persist_before_vote(self, c: CanonicalCommitment) -> str:
        key = (c.task_id, c.epoch, c.agent_id)
        self._persisted[key] = c.canonical_bytes()
        return c.digest()

    def reconstruct(self, task_id: str, epoch: int, agent_id: str, signed_digest: str) -> dict:
        key = (task_id, epoch, agent_id)
        raw = self._persisted.get(key)
        if raw is None:
            raise CommitmentReconstructionError(
                f"no persisted canonical form for {key}; commitment is orphaned"
            )
        actual = hashlib.sha256(raw).hexdigest()
        if actual != signed_digest:
            raise CommitmentReconstructionError(
                f"reconstruction mismatch for {key}: signed={signed_digest} actual={actual}"
            )
        return json.loads(raw.decode("utf-8"))


def verify_quorum_reconstructable(
    store: CommitmentStore,
    votes: list[tuple[str, str, int, str, str]],  # (agent_id, task_id, epoch, signed_digest, content_hash)
    threshold: int,
) -> dict:
    """Auditor check: quorum certificate is valid AND every honest vote reconstructs
    to byte-identical content. Narrow-binding votes (content omitted) fail here."""
    if len(votes) < threshold:
        raise CommitmentReconstructionError(f"quorum not met: {len(votes)} < {threshold}")

    reconstructions: dict[str, dict] = {}
    for agent_id, task_id, epoch, signed_digest, _content_hash in votes:
        try:
            content = store.reconstruct(task_id, epoch, agent_id, signed_digest)
        except CommitmentReconstructionError as e:
            raise CommitmentReconstructionError(
                f"vote from {agent_id} is validly signed but not reconstructable: {e}"
            ) from e
        reconstructions[agent_id] = content

    baseline = next(iter(reconstructions.values()))
    for agent_id, content in reconstructions.items():
        if content != baseline:
            raise CommitmentReconstructionError(
                f"equivocation-hiding detected: {agent_id} reconstructs divergent content "
                f"under a valid quorum certificate"
            )
    return baseline
