# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-aaif-hardware-attested-identity-when-the-secure-enclave-re-signs-a-rotated-key-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-aaif-hardware-attested-identity-when-the-secure-enclave-re-signs-a-rotated-key-mid-handoff.warrant.json
# Markdown SHA-256:   a58e91175c424ab38464322085d4f4b8fcc8b1ca8f59adaa6d1cd62cc7a0407b
# Code AST SHA-256:   e2cbb4ddc2b5e7380fd1e30faad7bb7458174606b273fc0651ecaf934ca3e3aa
# Verified Classes:   AttestationError, KeySubstitutionError, UnprovenRotationError, PinnedIdentity, PresentedCredential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttestationError(RuntimeError):
    """Base class for AAIF attestation failures."""


class KeySubstitutionError(AttestationError):
    """Same agent_id+epoch, different key, no valid rotation statement."""


class UnprovenRotationError(AttestationError):
    """Successor key presented without a verifiable Rot(K1->K2) statement."""


@dataclass(frozen=True)
class PinnedIdentity:
    agent_id: str
    issuer: str
    measurement: str          # enclave PCR/quote digest
    epoch: int
    chain_head_pubkey: bytes  # current trusted key (K1 at pin time)


@dataclass(frozen=True)
class PresentedCredential:
    agent_id: str
    issuer: str
    measurement: str
    epoch: int
    pubkey: bytes
    rotation_stmt_valid: bool = False  # Rot(prev->this) verified against chain head


def classify_presentation(pin: PinnedIdentity, cred: PresentedCredential) -> str:
    """Return 'accept' | 'rehandshake' | raise on substitution."""
    # Measurement change is always a different instance, never a continuation.
    if cred.measurement != pin.measurement:
        raise KeySubstitutionError(
            f"measurement drift for {pin.agent_id}: {pin.measurement} -> {cred.measurement}"
        )
    if cred.agent_id != pin.agent_id or cred.issuer != pin.issuer:
        raise KeySubstitutionError(
            f"identity/issuer mismatch: pinned {pin.agent_id}/{pin.issuer}, "
            f"presented {cred.agent_id}/{cred.issuer}"
        )
    # Same key: trivially the pinned identity.
    if cred.pubkey == pin.chain_head_pubkey and cred.epoch == pin.epoch:
        return "accept"
    # Successor key: must advance epoch AND prove rotation from chain head.
    if cred.epoch > pin.epoch:
        if not cred.rotation_stmt_valid:
            return "rehandshake"   # ambiguous: dropped stmt or attack -> re-verify
        return "accept"
    # Same-or-older epoch but different key: replay / substitution.
    if cred.pubkey != pin.chain_head_pubkey:
        raise KeySubstitutionError(
            f"epoch {cred.epoch} key substitution for {pin.agent_id}: "
            f"no rotation statement, epoch not advanced"
        )
    return "accept"


def handle_handoff_frame(pin: PinnedIdentity, cred: PresentedCredential,
                         last_checkpoint_seq: int, current_seq: int) -> PinnedIdentity:
    verdict = classify_presentation(pin, cred)
    if verdict == "accept":
        if cred.epoch > pin.epoch and cred.rotation_stmt_valid:
            # Re-pin to the new chain head; task continues.
            return PinnedIdentity(pin.agent_id, pin.issuer, pin.measurement,
                                  cred.epoch, cred.pubkey)
        return pin
    # rehandshake path: state between last checkpoint and now is at risk.
    if current_seq - last_checkpoint_seq > 0:
        # Checkpoint cadence invariant violated: rotation detected mid-window.
        raise UnprovenRotationError(
            f"rotation at seq {current_seq} but last durable checkpoint at "
            f"{last_checkpoint_seq}; {current_seq - last_checkpoint_seq} frames "
            f"of state cannot be safely resumed for {pin.agent_id}"
        )
    return pin  # safe to re-handshake from checkpoint boundary
