# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-in-byzantine-agent-commitment-ledgers-when-quorum-certificates-outlive-the-tasks-they-certify.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-in-byzantine-agent-commitment-ledgers-when-quorum-certificates-outlive-the-tasks-they-certify.warrant.json
# Markdown SHA-256:   bc90a12642da31795353a2d33dcf5b3fa65fc582acd3ca3971dc237fb695bb77
# Code AST SHA-256:   0f288205feb62cb3d4f4b38c90b2d04f1af68eb22b055cfaed5ca4438a73a27c
# Verified Classes:   LeaseEquivocationError, ObligationLease
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class LeaseEquivocationError(RuntimeError):
    """Raised when an obligation has two valid QCs with overlapping lease epochs."""
    pass


class ObligationLease:
    def __init__(self, obligation_id: str, holder: str, lease_epoch: int, expiry_height: int):
        self.obligation_id = obligation_id
        self.holder = holder
        self.lease_epoch = lease_epoch
        self.expiry_height = expiry_height


def validate_reassignment(
    prior_lease: ObligationLease,
    new_lease: ObligationLease,
    current_height: int,
    revocation_qc_present: bool,
) -> None:
    """
    Enforce certificate-lease binding before a reassignment block is accepted.
    Raises LeaseEquivocationError if the reassignment would create two valid
    certificates for the same obligation slot.
    """
    if prior_lease.obligation_id != new_lease.obligation_id:
        raise LeaseEquivocationError(
            f"obligation id mismatch: {prior_lease.obligation_id} vs {new_lease.obligation_id}"
        )

    if new_lease.lease_epoch <= prior_lease.lease_epoch:
        raise LeaseEquivocationError(
            f"reassignment epoch {new_lease.lease_epoch} does not advance "
            f"prior epoch {prior_lease.lease_epoch} for {prior_lease.obligation_id}"
        )

    lease_expired = current_height >= prior_lease.expiry_height
    if not lease_expired and not revocation_qc_present:
        raise LeaseEquivocationError(
            f"cannot reassign {prior_lease.obligation_id} from {prior_lease.holder} "
            f"to {new_lease.holder}: lease expires at height {prior_lease.expiry_height}, "
            f"current height {current_height}, no revocation QC"
        )

    if new_lease.holder == prior_lease.holder:
        raise LeaseEquivocationError(
            f"reassignment to same holder {new_lease.holder} is a no-op lease bump"
        )


def replay_lease_history(
    obligation_id: str,
    history: list[ObligationLease],
    agent_belief_epoch: int,
    current_height: int,
) -> ObligationLease:
    """
    On rejoin from partition, replay lease history and reconcile local belief.
    Forces the agent to accept height-based expiry over stale local state.
    """
    if not history:
        raise LeaseEquivocationError(f"no lease history for {obligation_id}")

    latest = max(history, key=lambda l: l.lease_epoch)
    if latest.lease_epoch < agent_belief_epoch:
        raise LeaseEquivocationError(
            f"agent belief epoch {agent_belief_epoch} exceeds ledger history "
            f"epoch {latest.lease_epoch} for {obligation_id}; agent is ahead of ledger"
        )

    if current_height >= latest.expiry_height:
        raise LeaseEquivocationError(
            f"lease for {obligation_id} expired at height {latest.expiry_height}, "
            f"current height {current_height}; agent must relinquish belief"
        )

    return latest
