# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-byzantine-quorum-certificate-and-a-locally-re-derivable-plan-commitment-when-peers-equivocate.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-byzantine-quorum-certificate-and-a-locally-re-derivable-plan-commitment-when-peers-equivocate.warrant.json
# Markdown SHA-256:   5a1e784d84e2f9a5516361008fc4116690495b7898dffaaa2c9d4be428328046
# Code AST SHA-256:   55e92edac440eff78d6796ac7b53e6726fa6ea6a27f5bc2fe4e13f0f3d8bc879
# Verified Classes:   PlanBindingError, QuorumCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class PlanBindingError(RuntimeError):
    """Raised when a delivered plan body does not hash to the QC's certified digest."""


@dataclass(frozen=True)
class QuorumCertificate:
    plan_id: str
    digest: str          # full 64-hex-char SHA256, never truncated
    round: int
    signers: tuple       # peer ids whose signatures verified against trust_root


def canonical_digest(plan_body: dict) -> str:
    # Canonicalization MUST be byte-identical on sign and verify paths.
    blob = json.dumps(plan_body, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def commit_plan(
    qc: QuorumCertificate,
    plan_body: dict,
    trust_root: frozenset,
    n_peers: int,
    last_committed_round: dict,
) -> dict:
    quorum = (2 * n_peers + 1) // 3 + 1  # ⌈(2N+1)/3⌉

    if not set(qc.signers).issubset(trust_root):
        raise PlanBindingError(f"QC signers {qc.signers} escape trust root")
    if len(set(qc.signers)) < quorum:
        raise PlanBindingError(f"QC signer count {len(set(qc.signers))} < quorum {quorum}")
    if qc.round <= last_committed_round.get(qc.plan_id, -1):
        raise PlanBindingError(f"stale round {qc.round} for plan {qc.plan_id}")
    if len(qc.digest) != 64:
        raise PlanBindingError("truncated digest in QC; collision-feasible")

    # The binding check the protocol must never omit.
    local = canonical_digest(plan_body)
    if local != qc.digest:
        raise PlanBindingError(
            f"body/digest mismatch for plan {qc.plan_id}: "
            f"qc={qc.digest[:12]}… local={local[:12]}…"
        )

    last_committed_round[qc.plan_id] = qc.round
    return plan_body
