# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-replayed-a2a-delegation-envelope-whose-signed-nonce-is-valid-but-whose-issued-at-has-slid-outside-the-downstream-warran.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-replayed-a2a-delegation-envelope-whose-signed-nonce-is-valid-but-whose-issued-at-has-slid-outside-the-downstream-warran.warrant.json
# Markdown SHA-256:   c652de92ea43e8020f17d3d6198c44012475db2acc2a9a91d153500a70ab15bf
# Code AST SHA-256:   a38eb1b41bdb6a9d8b4cfa879490e62c27d3081eaccc0e852bbcd633f1f5d03c
# Verified Classes:   DelegationLapsed, WarrantRevoked, Envelope, ReplayCache
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DelegationLapsed(RuntimeError):
    """Raised when a signed A2A envelope is authentic and nonce-fresh but its
    warrant window has slid outside the receiver's acceptance window."""


class WarrantRevoked(RuntimeError):
    """Raised when the envelope's warrant is no longer authoritative at the
    issuer, regardless of nonce freshness."""


@dataclass
class Envelope:
    issuer_id: str
    nonce: str
    issued_at: float      # sender clock
    expires_at: float     # sender clock
    warrant_id: str
    signature_ok: bool


class ReplayCache:
    def __init__(self, ttl: float):
        self._seen: dict[tuple[str, str], float] = {}
        self._ttl = ttl

    def unseen(self, issuer_id: str, nonce: str, now: float) -> bool:
        self._evict(now)
        return (issuer_id, nonce) not in self._seen

    def record(self, issuer_id: str, nonce: str, now: float) -> None:
        self._seen[(issuer_id, nonce)] = now

    def _evict(self, now: float) -> None:
        cutoff = now - self._ttl
        for key in [k for k, t in self._seen.items() if t < cutoff]:
            del self._seen[key]


def accept_delegation(
    env: Envelope,
    cache: ReplayCache,
    warrant_is_live,
    now: float,
    recv_window: float = 300.0,
    max_skew: float = 5.0,
) -> None:
    # 1. Signature.
    if not env.signature_ok:
        raise DelegationLapsed(f"bad signature on nonce={env.nonce}")

    # 2. Freshness (replay resistance).
    if not cache.unseen(env.issuer_id, env.nonce, now):
        raise DelegationLapsed(f"replay: nonce={env.nonce} already seen")

    # 3. Receiver-anchored validity window. Do NOT trust sender clock alone.
    lower = now - recv_window - max_skew
    if env.issued_at < lower:
        # Stale-but-unseen: authentic, nonce-fresh, but lapsed. Do NOT record
        # the nonce; the issuer must re-mint and the receiver must not poison
        # the cache against a future legitimate delivery.
        raise DelegationLapsed(
            f"lapsed delegation: issued_at={env.issued_at:.0f} "
            f"< lower={lower:.0f} (nonce={env.nonce})"
        )
    if env.expires_at < now - max_skew:
        raise DelegationLapsed(
            f"expired delegation: expires_at={env.expires_at:.0f} < now={now:.0f}"
        )

    # 4. Warrant liveness — orthogonal to freshness.
    if not warrant_is_live(env.warrant_id):
        # Record the nonce so repeated redelivery does not re-trigger the
        # revocation path, then surface a distinct error.
        cache.record(env.issuer_id, env.nonce, now)
        raise WarrantRevoked(f"warrant {env.warrant_id} revoked at issuer")

    # 5. Full acceptance: now and only now record the nonce.
    cache.record(env.issuer_id, env.nonce, now)


# --- demonstration of the stale-but-unseen failure ---
if __name__ == "__main__":
    cache = ReplayCache(ttl=3600.0)
    now = time.time()
    late = Envelope(
        issuer_id="planner-01",
        nonce="7f3a",
        issued_at=now - 412,
        expires_at=now - 112,
        warrant_id="w-42",
        signature_ok=True,
    )
    try:
        accept_delegation(late, cache, warrant_is_live=lambda w: False, now=now)
    except DelegationLapsed as e:
        # Correct behavior: reject as lapsed, nonce NOT recorded.
        assert cache.unseen("planner-01", "7f3a", now)
        print("rejected lapsed:", e)
