# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-capability-attestation-replay-window-has-collapsed-under-continuous-trust-decay-in-a2a-agent-cards.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-capability-attestation-replay-window-has-collapsed-under-continuous-trust-decay-in-a2a-agent-cards.warrant.json
# Markdown SHA-256:   e9fb6ea2c354a4d3739aa45540ed39caafa625df88ea4e72f683b0fa3b2bd261
# Code AST SHA-256:   34aebcbfe5a42678c939cf71d8d664d38c1e5d9fa29510da628d4df01946b53c
# Verified Classes:   AttestationReplayError, Verdict, AgentCard, TrustScore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class AttestationReplayError(RuntimeError):
    """Raised when a capability grant would be honored on evidence whose
    behavioral epoch does not intersect the card's validity epoch."""
    pass


class Verdict(Enum):
    HONOR = "honor"
    DENY = "deny"
    PENDING_REATTEST = "pending_reattest"


@dataclass(frozen=True)
class AgentCard:
    peer_id: str
    capabilities: frozenset
    iat: float
    exp: float
    sig_valid: bool


@dataclass(frozen=True)
class TrustScore:
    value: float
    scored_at: float


def authorize(
    card: AgentCard,
    score: TrustScore,
    capability: str,
    now: float,
    threshold: float,
    max_trust_staleness: float = 90.0,
    refresh_margin: float = 60.0,
    staleness_margin: float = 30.0,
) -> Verdict:
    # Predicate 1: signature — binary, always first.
    if not card.sig_valid:
        return Verdict.DENY

    # Predicate 2: epoch expiry — evaluated UNCONDITIONALLY, before trust.
    # A dead card cannot be resurrected by a high trust score.
    if now > card.exp:
        raise AttestationReplayError(
            f"card for {card.peer_id} expired at {card.exp}, now={now}; "
            f"trust score (scored_at={score.scored_at}) cannot resurrect it"
        )

    # Predicate 3: trust evidence must describe the card's behavioral epoch.
    if score.scored_at < card.iat:
        raise AttestationReplayError(
            f"trust score for {card.peer_id} scored_at={score.scored_at} "
            f"predates card iat={card.iat}; stale-evidence grant"
        )

    # Staleness: last-known is NOT a valid verdict beyond the window.
    if now - score.scored_at > max_trust_staleness:
        return Verdict.PENDING_REATTEST

    # Boundary band: card near expiry AND score near staleness -> block, don't guess.
    if (card.exp - now <= refresh_margin) and (
        max_trust_staleness - (now - score.scored_at) <= staleness_margin
    ):
        return Verdict.PENDING_REATTEST

    if capability not in card.capabilities:
        return Verdict.DENY

    return Verdict.HONOR if score.value >= threshold else Verdict.DENY
