# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-agent-card-after-a-revocation-event-crosses-a-federated-a2a-registry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-agent-card-after-a-revocation-event-crosses-a-federated-a2a-registry-boundary.warrant.json
# Markdown SHA-256:   da1c3108d71403597b913a005b5df8f1d8382096054ca411340e0016a1a63e6b
# Code AST SHA-256:   1f0993568712960d0456d49114f5c33a5cc632b36284a5a5e49ddd59c9b01eb6
# Verified Classes:   StaleAuthorizationView, UnverifiableClaim, ClaimFreshness, CachedAgentCard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Optional


class StaleAuthorizationView(RuntimeError):
    """Raised when a cached Agent Card is used for authorization while its
    revocation freshness has fallen below the safe threshold."""
    pass


class UnverifiableClaim(RuntimeError):
    """Raised when the authoritative revocation source for a claim is
    unreachable or has been de-peered; the claim cannot be trusted."""
    pass


@dataclass
class ClaimFreshness:
    last_auth_fetch: float          # monotonic ts of last authoritative revocation fetch
    h_max: Optional[float]          # max propagation delay; None => unbounded
    authoritative_reachable: bool = True


@dataclass
class CachedAgentCard:
    card_id: str
    cached_at: float
    hard_expiry: float
    claims: Dict[str, ClaimFreshness] = field(default_factory=dict)


def authorize_invocation(
    card: CachedAgentCard,
    claim: str,
    now: float,
    safety_fraction: float = 0.5,
) -> bool:
    """Gate an A2A invocation on the *shorter* of card life and revocation
    freshness. Returns True only in the fresh regime; raises otherwise."""
    if claim not in card.claims:
        raise UnverifiableClaim(
            f"claim {claim!r} not present on card {card.card_id!r}"
        )

    cf = card.claims[claim]

    if not cf.authoritative_reachable or cf.h_max is None:
        # De-peered or unbounded propagation: no caching is sound.
        raise UnverifiableClaim(
            f"claim {claim!r} on {card.card_id!r}: authoritative revocation "
            f"source unreachable or propagation bound unknown"
        )

    remaining_card_life = card.hard_expiry - now
    elapsed_since_fetch = now - cf.last_auth_fetch
    remaining_revocation_freshness = cf.h_max - elapsed_since_fetch
    h_safe = cf.h_max * safety_fraction

    # Stale regime: either the fetch is too old, or the card will outlive
    # the revocation freshness window. Both force synchronous re-fetch.
    if elapsed_since_fetch >= h_safe or remaining_card_life > remaining_revocation_freshness:
        raise StaleAuthorizationView(
            f"claim {claim!r} on {card.card_id!r} in stale regime: "
            f"elapsed_since_fetch={elapsed_since_fetch:.0f}s "
            f"h_safe={h_safe:.0f}s "
            f"remaining_card_life={remaining_card_life:.0f}s "
            f"remaining_revocation_freshness={remaining_revocation_freshness:.0f}s "
            f"-> synchronous re-fetch required before dispatch"
        )

    return True


def dispatch_with_reverify(
    card: CachedAgentCard,
    claim: str,
    now: float,
    refetch_revocation,
) -> bool:
    """Wraps authorize_invocation: on StaleAuthorizationView, re-fetch the
    authoritative revocation record and retry once. If the re-fetch reveals
    a revocation, the claim is dead and the call must not proceed."""
    try:
        return authorize_invocation(card, claim, now)
    except StaleAuthorizationView:
        fresh = refetch_revocation(card.card_id, claim)
        if fresh is None:
            raise UnverifiableClaim(
                f"re-fetch for {claim!r} on {card.card_id!r} returned nothing"
            )
        if fresh.get("revoked"):
            raise StaleAuthorizationView(
                f"claim {claim!r} on {card.card_id!r} revoked at "
                f"{fresh.get('revoked_at')}; dispatch blocked"
            )
        # Update the freshness clock and re-authorize against fresh data.
        cf = card.claims[claim]
        cf.last_auth_fetch = fresh["fetched_at"]
        cf.authoritative_reachable = True
        return authorize_invocation(card, claim, now)
