# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-delegated-credential-revocation-as-a-two-phase-commit-rather-than-a-single-tombstone.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-delegated-credential-revocation-as-a-two-phase-commit-rather-than-a-single-tombstone.warrant.json
# Markdown SHA-256:   e51aacc8c36b7c479f9ac6cf65edce1f5fcb956ad29c0a8efcb357a1b958d240
# Code AST SHA-256:   f1e9d15ee673089f79c744f03ac5e377803b9fbb538cfa6d86c81651fb21c682
# Verified Classes:   RevocationProtocolError, RevState, DelegatedCredential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Set


class RevocationProtocolError(RuntimeError):
    """Raised when a delegate attempts an illegal revocation state transition."""
    pass


class RevState(Enum):
    ACTIVE = "active"
    REVOKING = "revoking"   # quiesced; awaiting enforcement-point acks
    REVOKED = "revoked"     # terminal; safe to checkpoint as dead


@dataclass
class DelegatedCredential:
    credential_id: str
    fingerprint: str
    state: RevState = RevState.ACTIVE
    outstanding_presentations: Set[str] = field(default_factory=set)  # enforcement-point ids
    acknowledged: Set[str] = field(default_factory=set)


def begin_revocation(cred: DelegatedCredential) -> RevState:
    """Phase 1: quiesce. Never jump straight to REVOKED if presentations are live."""
    if cred.state is RevState.REVOKED:
        raise RevocationProtocolError(
            f"credential {cred.credential_id} already terminal; re-revocation is a no-op, not an error path"
        )
    if not cred.outstanding_presentations:
        # No forwarding, no shadow: single-phase tombstone is sound.
        cred.state = RevState.REVOKED
        return cred.state
    cred.state = RevState.REVOKING
    return cred.state


def acknowledge(cred: DelegatedCredential, enforcement_point: str) -> RevState:
    """Phase 2: collect acks keyed on fingerprint; only then commit to REVOKED."""
    if cred.state is not RevState.REVOKING:
        raise RevocationProtocolError(
            f"ack for {cred.credential_id} arrived in state {cred.state.value}; "
            "enforcement point confirmed rejection of a credential not under revocation"
        )
    if enforcement_point not in cred.outstanding_presentations:
        raise RevocationProtocolError(
            f"ack from {enforcement_point} does not correspond to any outstanding presentation "
            f"of {cred.credential_id}; fingerprint {cred.fingerprint} mismatch"
        )
    cred.acknowledged.add(enforcement_point)
    if cred.acknowledged >= cred.outstanding_presentations:
        cred.state = RevState.REVOKED
    return cred.state


def checkpoint(cred: DelegatedCredential) -> dict:
    """The checkpoint must preserve REVOKING distinctly; collapsing it is the bug."""
    if cred.state is RevState.REVOKING:
        return {
            "credential_id": cred.credential_id,
            "state": "revoking",
            "unacked": sorted(cred.outstanding_presentations - cred.acknowledged),
            "resume_action": "re-enter_quiesce_and_recollect_acks",
        }
    return {"credential_id": cred.credential_id, "state": cred.state.value}
