# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-committed-plan-and-a-re-deliberated-one-under-byzantine-plan-commitment-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-committed-plan-and-a-re-deliberated-one-under-byzantine-plan-commitment-consensus.warrant.json
# Markdown SHA-256:   42a6b9f68f876aec1d32a7cba539c5aaad499d7aaa55dd6b8f382b6cd2475924
# Code AST SHA-256:   56f041e20f7cbaede55b4ce62f268739233542f385e4d34c62f0760d2fd32547
# Verified Classes:   CommitmentEquivocationError, LockNotDurableError, DurableLock, Replica
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CommitmentEquivocationError(RuntimeError):
    """Raised when a replica attempts to sign a conflicting plan at a locked epoch."""


class LockNotDurableError(RuntimeError):
    """Raised when a vote is emitted without a confirmed durable lock write."""


@dataclass
class DurableLock:
    epoch: int
    plan_hash: str
    fsync_confirmed: bool = False


@dataclass
class Replica:
    replica_id: str
    lock: Optional[DurableLock] = None
    signed: dict = field(default_factory=dict)  # epoch -> plan_hash

    def _durable_write(self, lock: DurableLock) -> None:
        # Simulated fsync; in production this must block until the OS confirms.
        lock.fsync_confirmed = True

    def sign_vote(self, epoch: int, plan_hash: str, new_evidence: bool) -> str:
        # Gate 1: never sign twice at the same epoch with different hashes.
        prior = self.signed.get(epoch)
        if prior is not None and prior != plan_hash:
            raise CommitmentEquivocationError(
                f"replica {self.replica_id} already signed epoch {epoch} "
                f"for {prior[:12]}; refusing conflicting {plan_hash[:12]}"
            )

        # Gate 2: if locked at this epoch, only the locked plan is votable.
        if self.lock is not None and self.lock.epoch == epoch:
            if self.lock.plan_hash != plan_hash:
                # This is the boundary: better plan, wrong epoch.
                raise CommitmentEquivocationError(
                    f"replica {self.replica_id} holds lock on {self.lock.plan_hash[:12]} "
                    f"at epoch {epoch}; plan {plan_hash[:12]} must be deferred to e+1"
                )
            if not self.lock.fsync_confirmed:
                raise LockNotDurableError(
                    f"replica {self.replica_id} lock not fsync'd before vote"
                )

        # Gate 3: first vote at this epoch establishes the lock durably.
        if self.lock is None or self.lock.epoch != epoch:
            lock = DurableLock(epoch=epoch, plan_hash=plan_hash)
            self._durable_write(lock)
            self.lock = lock

        self.signed[epoch] = plan_hash
        return hashlib.sha256(f"{epoch}:{plan_hash}".encode()).hexdigest()


def handle_new_evidence(replica: Replica, epoch: int, new_plan_hash: str) -> str:
    """Called by the deliberation layer when re-planning yields a different DAG."""
    if replica.lock is not None and replica.lock.epoch == epoch:
        if replica.lock.plan_hash != new_plan_hash:
            # Defer, do not vote. Carry evidence to epoch e+1.
            return f"PROPOSAL_DEFERRED:{new_plan_hash}"
    return replica.sign_vote(epoch, new_plan_hash, new_evidence=True)
