# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-under-byzantine-quorum-equivocation-tolerant-task-commitment-and-the-shared-state-fork-at-3f-1.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-under-byzantine-quorum-equivocation-tolerant-task-commitment-and-the-shared-state-fork-at-3f-1.warrant.json
# Markdown SHA-256:   78ac18b385cecfbdae1be79f28513d8bb717fbbadca9b53a593b76827099de9c
# Code AST SHA-256:   60b62791b8a32ad4f43b0356d7478fd65d0c7815bd856de32c9282f31929d044
# Verified Classes:   QuorumForkError, QuorumCertificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, Set


class QuorumForkError(RuntimeError):
    """Raised when a QC's honest-weighted intersection falls below f+1."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    view: int
    slot: int
    proposal_hash: str
    signers: Set[str]          # agent_ids that signed
    equivocators: Set[str]     # agent_ids proven to have equivocated in this view


def honest_intersection(qc_a: QuorumCertificate, qc_b: QuorumCertificate) -> int:
    shared = qc_a.signers & qc_b.signers
    dishonest = qc_a.equivocators | qc_b.equivocators
    return len(shared - dishonest)


def verify_commit_safety(
    qc_prepare: QuorumCertificate,
    qc_commit: QuorumCertificate,
    f: int,
) -> None:
    """Enforce honest-weighted intersection >= f+1 before allowing execution."""
    if qc_prepare.view != qc_commit.view or qc_prepare.slot != qc_commit.slot:
        raise QuorumForkError(
            f"QC view/slot mismatch: prepare=({qc_prepare.view},{qc_prepare.slot}) "
            f"commit=({qc_commit.view},{qc_commit.slot})"
        )
    if qc_prepare.proposal_hash != qc_commit.proposal_hash:
        raise QuorumForkError(
            f"Conflicting proposal hashes across QCs: "
            f"{qc_prepare.proposal_hash} vs {qc_commit.proposal_hash}"
        )
    hi = honest_intersection(qc_prepare, qc_commit)
    if hi < f + 1:
        raise QuorumForkError(
            f"Honest intersection {hi} < f+1={f+1}; "
            f"equivocators={qc_prepare.equivocators | qc_commit.equivocators}. "
            f"Refusing commit; escalate to view change."
        )


def derive_deterministic_vote(agent_id: str, view: int, slot: int, proposal_hash: str) -> str:
    """Vote must be a pure function of committed inputs to prevent accidental equivocation."""
    payload = f"{agent_id}|{view}|{slot}|{proposal_hash}".encode()
    return hashlib.sha256(payload).hexdigest()


def commit_and_execute(
    qc_prepare: QuorumCertificate,
    qc_commit: QuorumCertificate,
    f: int,
    local_agent_id: str,
) -> str:
    verify_commit_safety(qc_prepare, qc_commit, f)
    # Only after safety gate passes do we authorize task execution.
    expected = derive_deterministic_vote(
        local_agent_id, qc_commit.view, qc_commit.slot, qc_commit.proposal_hash
    )
    if local_agent_id in qc_commit.signers and expected not in qc_commit.signers:
        # sanity: our own vote must be reproducible
        raise QuorumForkError(
            f"Local vote for {local_agent_id} not reproducible; "
            f"possible non-determinism in vote derivation."
        )
    return f"EXECUTE:{qc_commit.proposal_hash}@{qc_commit.view}.{qc_commit.slot}"
