# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-trust-anchor-during-a-live-peer-capability-exchange-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-trust-anchor-during-a-live-peer-capability-exchange-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   453f7ee831b7104b5275965004b03600d4355cd7bc9d1cd6a12d05815322c3b9
# Code AST SHA-256:   b716e1066d0c5cad381c89af81444167589d73575297c43d5267a672ef5a0c53
# Verified Classes:   TrustIndeterminate, GrantState, CapabilityGrant, AnchorView, FederatedRelyingParty
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum


class TrustIndeterminate(RuntimeError):
    """Raised when a capability grant cannot be proven fresh against the anchor's revocation epoch."""
    pass


class GrantState(Enum):
    FRESH = "fresh"
    STALE = "stale"
    INDETERMINATE = "indeterminate"
    REJECTED = "rejected"


@dataclass
class CapabilityGrant:
    serial: str
    issuer_anchor: str
    rev_epoch: int          # anchor epoch at issuance
    not_after: float        # wall-clock validity end (secondary check only)


@dataclass
class AnchorView:
    current_epoch: int
    fetched_at: float
    max_staleness: float    # declared by anchor, seconds
    revoked_serials: set = field(default_factory=set)


class FederatedRelyingParty:
    def __init__(self, anchor_fetch):
        # anchor_fetch(anchor_id) -> AnchorView | None  (None = unreachable)
        self._anchor_fetch = anchor_fetch
        self._last_view: dict[str, AnchorView] = {}

    def _view(self, anchor_id: str) -> AnchorView | None:
        v = self._anchor_fetch(anchor_id)
        if v is not None:
            self._last_view[anchor_id] = v
        return v if v is not None else self._last_view.get(anchor_id)

    def redeem(self, grant: CapabilityGrant, now: float | None = None) -> GrantState:
        now = now if now is not None else time.time()

        if now > grant.not_after:
            return GrantState.REJECTED

        view = self._view(grant.issuer_anchor)

        if view is None:
            raise TrustIndeterminate(
                f"anchor {grant.issuer_anchor} unreachable and no prior view; "
                f"cannot establish revocation epoch for grant {grant.serial}"
            )

        age = now - view.fetched_at
        if age > view.max_staleness:
            raise TrustIndeterminate(
                f"anchor {grant.issuer_anchor} view age {age:.1f}s exceeds "
                f"max_staleness {view.max_staleness:.1f}s; grant {grant.serial} "
                f"is indeterminate, not valid"
            )

        if grant.serial in view.revoked_serials:
            return GrantState.REJECTED

        if grant.rev_epoch == view.current_epoch:
            return GrantState.FRESH

        if grant.rev_epoch < view.current_epoch:
            # Anchor swept since issuance; delta must have been checked above
            # via revoked_serials. If serial absent, grant survives the sweep.
            return GrantState.FRESH

        # rev_epoch > current_epoch: anchor went backwards -> clock/rollback attack
        raise TrustIndeterminate(
            f"grant {grant.serial} rev_epoch {grant.rev_epoch} ahead of anchor "
            f"epoch {view.current_epoch}; possible rollback or forged anchor view"
        )
