# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-honoring-a-federated-agent-capability-after-the-issuing-org-has-revoked-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-honoring-a-federated-agent-capability-after-the-issuing-org-has-revoked-it.warrant.json
# Markdown SHA-256:   2d6569511e838c7eb1413677d4455ce985c0f3b6898fa11cc8fc6de7d3564089
# Code AST SHA-256:   be428139a47865a8d63602f86e993135c8949b2555e89b7eaa0ac8ed42f73a85
# Verified Classes:   StaleEpochWarrantError, Warrant, PeerState
# Defensive Guards:   11 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleEpochWarrantError(RuntimeError):
    """Raised when a warrant is authorized against an issuer epoch watermark
    older than the scope's max_skew, or when a chain link is revoked."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    subject: str
    scope: str
    not_before: float
    not_after: float
    issuer_epoch: int
    parent_id: str | None = None


@dataclass
class PeerState:
    epoch_floor: dict[str, int] = field(default_factory=dict)   # issuer -> last acked epoch
    epoch_floor_at: dict[str, float] = field(default_factory=dict)  # issuer -> wall time of ack
    revoked: set[str] = field(default_factory=set)              # warrant ids (root + descendants)
    revoked_roots_unspecified_descendants: set[str] = field(default_factory=set)


SCOPE_MAX_SKEW = {
    "read:public": 60.0,
    "deploy:staging": 60.0,
    "deploy:prod": 0.0,      # no cache: must re-probe
    "transfer:funds": 0.0,
}


def authorize(chain: list[Warrant], state: PeerState, now: float) -> None:
    """Validate a delegation chain root->leaf at action time. Fails closed."""
    if not chain:
        raise StaleEpochWarrantError("empty delegation chain")

    leaf = chain[-1]
    scope = leaf.scope
    max_skew = SCOPE_MAX_SKEW.get(scope)
    if max_skew is None:
        raise StaleEpochWarrantError(f"unknown scope {scope!r}: no skew policy, fail closed")

    # Structural checks on every link.
    for i, w in enumerate(chain):
        if not (w.not_before <= now <= w.not_after):
            raise StaleEpochWarrantError(f"{w.warrant_id}: outside validity window")
        if w.warrant_id in state.revoked:
            raise StaleEpochWarrantError(f"{w.warrant_id}: revoked")
        root = chain[0]
        if (root.warrant_id in state.revoked_roots_unspecified_descendants
                and w.warrant_id != root.warrant_id):
            raise StaleEpochWarrantError(
                f"{w.warrant_id}: root {root.warrant_id} revoked with unspecified "
                f"descendants; descendant trust cannot be established")
        if i > 0 and w.parent_id != chain[i - 1].warrant_id:
            raise StaleEpochWarrantError(f"{w.warrant_id}: broken parent linkage")

    # Epoch freshness for every distinct issuer in the chain.
    for issuer in {w.issuer for w in chain}:
        floor = state.epoch_floor.get(issuer)
        acked_at = state.epoch_floor_at.get(issuer)
        if floor is None or acked_at is None:
            raise StaleEpochWarrantError(f"{issuer}: no epoch floor acknowledged; fail closed")
        age = now - acked_at
        if age > max_skew:
            raise StaleEpochWarrantError(
                f"{issuer}: epoch floor age {age:.1f}s exceeds max_skew {max_skew}s "
                f"for scope {scope!r}")
        for w in chain:
            if w.issuer == issuer and w.issuer_epoch < floor:
                raise StaleEpochWarrantError(
                    f"{w.warrant_id}: issuer_epoch {w.issuer_epoch} below "
                    f"acknowledged floor {floor} for {issuer}")

    # For zero-skew scopes, a probe must confirm the issuer's *current* epoch
    # equals the floor at action time; caller supplies probe result via state.
    if max_skew == 0.0:
        for issuer in {w.issuer for w in chain}:
            if state.epoch_floor.get(issuer) != _probe_current_epoch(issuer):
                raise StaleEpochWarrantError(
                    f"{issuer}: current epoch advanced beyond acknowledged floor; "
                    f"re-probe required for scope {scope!r}")


def _probe_current_epoch(issuer: str) -> int:
    # In production: synchronous signed epoch probe with a hard deadline.
    # Placeholder returns the acknowledged floor to keep the example runnable.
    raise NotImplementedError
