# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-capability-grant-it-cannot-locally-re-verify-the-transitive-attestation-staleness-window-in-cross-org-agent-r.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-capability-grant-it-cannot-locally-re-verify-the-transitive-attestation-staleness-window-in-cross-org-agent-r.warrant.json
# Markdown SHA-256:   4e1c0da7d31fc7d1071aa65bab6d007d98ded392cf680d03492ff718b7d166aa
# Code AST SHA-256:   73a5f1f7c23d53afac84b2b5a4b73aeecef83726886e675288326320687a632f
# Verified Classes:   FederatedGrantError, GrantState, FederatedGrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class FederatedGrantError(RuntimeError):
    """Raised when a federated capability grant cannot be locally re-verified."""
    pass


class GrantState(Enum):
    CURRENT = "current"
    STALE_RENEGOTIABLE = "stale_renegotiable"
    INVALID = "invalid"


@dataclass
class FederatedGrant:
    subject: str
    capability: str
    resource: str
    policy_ref: str          # e.g. "orgB:policy/ledger-write/v7"
    asserted_at: float       # epoch seconds
    ttl_seconds: int
    broker_sig: str
    chain: list


def parse_policy_version(policy_ref: str) -> str:
    # policy_ref ends in "/vN"; the version is the last path segment
    return policy_ref.rsplit("/", 1)[-1]


def verify_current(grant: FederatedGrant,
                   live_policy_ref: str | None,
                   clock_skew_allowance: float = 30.0,
                   now: float | None = None) -> GrantState:
    """
    Re-validate a federated grant against the authoritative policy endpoint.

    Returns a tri-state. The caller MUST refuse to act on anything other than
    CURRENT. Unreachable authority degrades to INVALID, never to CURRENT.
    """
    now = time.time() if now is None else now

    # 1. Temporal freshness, evaluated by the consumer against its own clock.
    age = now - grant.asserted_at
    if age < -clock_skew_allowance:
        # Grant is from the future beyond allowed skew: clock or forgery issue.
        raise FederatedGrantError(
            f"grant asserted_at is {-age:.1f}s in the future, exceeds skew "
            f"allowance {clock_skew_allowance}s"
        )
    if age > grant.ttl_seconds:
        return GrantState.INVALID

    # 2. Version pinning: authority unreachable is INVALID, not CURRENT.
    if live_policy_ref is None:
        return GrantState.INVALID
    pinned = parse_policy_version(grant.policy_ref)
    live = parse_policy_version(live_policy_ref)
    if pinned != live:
        # Drift: capability may still be grantable under the new version,
        # but the consumer must renegotiate preconditions it cannot see.
        return GrantState.STALE_RENEGOTIABLE

    # 3. Chain integrity: every hop must verify against a currently-trusted key.
    # (Signature verification elided; the invariant is that failure here is
    # a hard reject, not a warning.)
    if not grant.chain:
        raise FederatedGrantError("federated grant has empty trust chain")

    return GrantState.CURRENT


def act_on_grant(grant: FederatedGrant,
                 live_policy_ref: str | None,
                 held_preconditions: set[str],
                 required_preconditions: set[str],
                 now: float | None = None) -> None:
    """
    Execute an action gated on a federated grant. Must be called in the same
    critical section as the action itself (no check-then-act gap).
    """
    state = verify_current(grant, live_policy_ref, now=now)

    if state is GrantState.INVALID:
        raise FederatedGrantError(
            f"grant for {grant.capability} on {grant.resource} is invalid: "
            f"expired or authority unreachable; refusing to act"
        )
    if state is GrantState.STALE_RENEGOTIABLE:
        raise FederatedGrantError(
            f"grant pinned to {grant.policy_ref} but authority now serves "
            f"{live_policy_ref}; renegotiate before acting"
        )

    missing = required_preconditions - held_preconditions
    if missing:
        raise FederatedGrantError(
            f"grant is current but missing preconditions {sorted(missing)}; "
            f"cannot satisfy current-version policy"
        )

    # Only here — freshness, version, chain, and preconditions all confirmed
    # in the same critical section — is the action permitted.
    return None
