# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-byzantine-equivocator-from-an-honest-peer-that-merely-replayed-a-stale-attestation-after-a-partial-quorum-view-ch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-byzantine-equivocator-from-an-honest-peer-that-merely-replayed-a-stale-attestation-after-a-partial-quorum-view-ch.warrant.json
# Markdown SHA-256:   a32df590f6f6bf8079b94bc5aa27b215c2c1fe04f95fc65860672ca0f447d90b
# Code AST SHA-256:   06ade566d5ef5c2a804b0708e9dce45df760a0ee894ccad292c519a0b56cb66b
# Verified Classes:   EpochConflictError, Decision, Attestation, ReceiverState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class EpochConflictError(RuntimeError):
    """Raised when a replayed attestation cannot be safely classified."""


class Decision(Enum):
    ACCEPT_AND_GRANT = "accept_and_grant"
    REJECT_AND_QUARANTINE = "reject_and_quarantine"
    REJECT_AND_SUSPEND = "reject_and_suspend"


@dataclass(frozen=True)
class Attestation:
    signer: str
    task_id: str
    view: int
    payload_hash: str
    solicited: bool


@dataclass
class ReceiverState:
    local_epoch: int
    lookback_delta: int
    # signer -> list of (view, task_id, payload_hash) retained within lookback
    attestation_log: dict


def classify_replay(att: Attestation, state: ReceiverState) -> Decision:
    if att.view >= state.local_epoch:
        # Not a replay; handled by the normal current-view path.
        return Decision.ACCEPT_AND_GRANT

    # Stale replay: scan lookback window for a conflicting attestation
    # from the same signer at any view in [local_epoch, att.view + delta].
    window_lo = state.local_epoch
    window_hi = att.view + state.lookback_delta
    log = state.attestation_log.get(att.signer, [])

    conflict_found = False
    for (v, tid, ph) in log:
        if window_lo <= v <= window_hi and tid != att.task_id:
            conflict_found = True
            break

    if conflict_found:
        return Decision.REJECT_AND_QUARANTINE

    if att.solicited:
        return Decision.ACCEPT_AND_GRANT

    return Decision.REJECT_AND_SUSPEND


def handle_attestation(att: Attestation, state: ReceiverState) -> Decision:
    decision = classify_replay(att, state)

    if decision is Decision.REJECT_AND_QUARANTINE:
        # Signer is Byzantine: it signed conflicting payloads across the
        # epoch boundary. Quarantine all its attestations in every view.
        raise EpochConflictError(
            f"equivocation detected: signer={att.signer} task={att.task_id} "
            f"view={att.view} local_epoch={state.local_epoch}"
        )

    if decision is Decision.REJECT_AND_SUSPEND:
        # Unsolicited stale push with no conflict yet. Do not grant epoch;
        # require an explicit state-sync request from the lagging peer.
        # The rejection must carry the current epoch so the peer can
        # re-solicit correctly.
        return Decision.REJECT_AND_SUSPEND

    # ACCEPT_AND_GRANT: either current-view or solicited stale with no
    # conflict. Count as informational; grant new epoch on state-sync.
    return Decision.ACCEPT_AND_GRANT
