# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-quorum-signed-commitment-because-its-own-prior-vote-is-missing-from-the-certificate.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-quorum-signed-commitment-because-its-own-prior-vote-is-missing-from-the-certificate.warrant.json
# Markdown SHA-256:   b7d0cbf47074425a628ee677e629fc242cf9ecc09817f439555fca5f5a625dee
# Code AST SHA-256:   4b4cba60deced1ac5097276f0bf5a9ebcab72c6bb48b87f5fc27032f92c58df0
# Verified Classes:   CommitmentReconciliationRequired, Vote, QuorumCertificate, LocalState
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class CommitmentReconciliationRequired(RuntimeError):
    """Raised when a quorum certificate cannot be reconciled with local vote history.

    This is a *safety* signal, not an error to be swallowed. The caller must
    freeze the task, request state-sync from >= f+1 peers, and escalate if the
    reconstructed history is inconsistent.
    """


@dataclass
class Vote:
    task_id: str
    view: int
    value: str
    epoch: int
    signature: bytes


@dataclass
class QuorumCertificate:
    task_id: str
    view: int
    value: str
    epoch: int
    signers: list[Vote]          # each Vote carries a signature over (task, view, value, epoch, roster_hash)
    roster_hash: bytes


@dataclass
class LocalState:
    task_id: str
    votes: dict[int, Vote] = field(default_factory=dict)   # view -> own vote
    current_epoch: int = 0
    current_roster_hash: bytes = b""
    last_adopted_value: Optional[str] = None


def _verify_signature(v: Vote, roster_hash: bytes) -> bool:
    # Placeholder: real impl verifies sig over (task_id, view, value, epoch, roster_hash).
    return len(v.signature) > 0


def accept_commitment(state: LocalState, qc: QuorumCertificate, quorum_size: int) -> str:
    """Adopt a QC only if it is consistent with this instance's own vote history.

    Returns the adopted value. Raises CommitmentReconciliationRequired when the
    QC lands in a vote-log gap or contradicts the last recorded vote.
    """
    if qc.task_id != state.task_id:
        raise CommitmentReconciliationRequired(
            f"QC task {qc.task_id} does not match local task {state.task_id}"
        )

    # 1. Roster and epoch binding: a QC from a different epoch/roster is not
    #    comparable to this instance's votes, even if signatures verify.
    if qc.epoch != state.current_epoch or qc.roster_hash != state.current_roster_hash:
        raise CommitmentReconciliationRequired(
            f"QC epoch/roster mismatch: qc=({qc.epoch},{qc.roster_hash.hex()[:8]}) "
            f"local=({state.current_epoch},{state.current_roster_hash.hex()[:8]})"
        )

    # 2. Signature and quorum count.
    valid = [v for v in qc.signers if _verify_signature(v, qc.roster_hash)]
    if len(valid) < quorum_size:
        raise CommitmentReconciliationRequired(
            f"QC quorum short: {len(valid)} < {quorum_size}"
        )

    # 3. Locate the highest view at which this instance actually voted.
    if not state.votes:
        raise CommitmentReconciliationRequired(
            f"no local vote history for task {qc.task_id}; cannot account for non-participation"
        )
    last_view = max(state.votes)
    last_vote = state.votes[last_view]

    # 4. Idempotent re-delivery: same value, view <= last vote.
    if qc.view <= last_view:
        if qc.value == last_vote.value:
            return qc.value
        raise CommitmentReconciliationRequired(
            f"QC at view {qc.view} contradicts recorded vote at same view: "
            f"qc={qc.value} local={last_vote.value}"
        )

    # 5. Vote-log gap check: every view in (last_view, qc.view) must have a
    #    recorded vote. A gap means we cannot prove our own non-equivocation.
    missing = [v for v in range(last_view + 1, qc.view) if v not in state.votes]
    if missing:
        raise CommitmentReconciliationRequired(
            f"vote-log gap for task {qc.task_id} at views {missing}; "
            f"refusing QC at view {qc.view} value={qc.value}"
        )

    # 6. Contradiction check: if we voted a different value at last_view,
    #    a QC for a new value at a later view is only adoptable if the
    #    intervening votes show a consistent chain to qc.value.
    intervening = [state.votes[v].value for v in range(last_view + 1, qc.view)]
    if last_vote.value != qc.value and qc.value not in intervening and intervening:
        raise CommitmentReconciliationRequired(
            f"QC value {qc.value} at view {qc.view} unreachable from local "
            f"vote {last_vote.value} at view {last_view} via {intervening}"
        )

    # 7. Adopt.
    state.last_adopted_value = qc.value
    state.votes[qc.view] = Vote(
        task_id=qc.task_id, view=qc.view, value=qc.value,
        epoch=qc.epoch, signature=b"adopted",
    )
    return qc.value
