# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-a2a-envelope-as-a-live-instruction-rather-than-a-stale-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-a2a-envelope-as-a-live-instruction-rather-than-a-stale-artifact.warrant.json
# Markdown SHA-256:   7557ff68994bd24654237c27434c15c14091efcf7aa8e8524f9299c6394132f1
# Code AST SHA-256:   acccf46b1e17d0c671cf266fba73fc0ff34c264708b7e4e71a38d22430a48596
# Verified Classes:   ReplayStateInconsistent, EnvelopeReplayError, Envelope, DurableReplayStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ReplayStateInconsistent(RuntimeError):
    """Raised when durable replay state cannot be reconciled with the effect log."""
    pass


class EnvelopeReplayError(RuntimeError):
    """Raised when a verified envelope is a replay or has expired."""
    pass


@dataclass(frozen=True)
class Envelope:
    sender_id: str
    seq: int
    nonce: bytes
    issued_at: float
    expires_at: float
    signature_valid: bool


class DurableReplayStore:
    """Replay state must be co-committed with effects; here we model the read side."""

    def __init__(self, high_water: dict, seen_nonces: dict, effect_log: dict):
        self.high_water = high_water          # sender_id -> int
        self.seen_nonces = seen_nonces        # sender_id -> set[bytes]
        self.effect_log = effect_log          # (sender_id, seq) -> effect_id

    def durable_high_water(self, sender_id: str) -> int:
        return self.high_water.get(sender_id, 0)

    def nonce_seen(self, sender_id: str, nonce: bytes) -> bool:
        return nonce in self.seen_nonces.get(sender_id, set())

    def effect_applied(self, sender_id: str, seq: int) -> bool:
        return (sender_id, seq) in self.effect_log

    def consistent(self, sender_id: str) -> bool:
        # Invariant: every applied effect must be at or below the high-water mark.
        hw = self.durable_high_water(sender_id)
        for (sid, seq) in self.effect_log:
            if sid == sender_id and seq > hw:
                return False
        return True


def admit_envelope(env: Envelope, store: DurableReplayStore, now: float | None = None) -> str:
    """Return 'accept' or raise. Fails closed on any state uncertainty."""
    now = time.time() if now is None else now

    if not env.signature_valid:
        raise EnvelopeReplayError(f"signature invalid for seq={env.seq}")

    if not store.consistent(env.sender_id):
        # Cannot prove effect/replay co-commitment: refuse to execute anything.
        raise ReplayStateInconsistent(
            f"replay state diverges from effect log for sender={env.sender_id}"
        )

    if now >= env.expires_at:
        # Expiry is the only safe fallback when freshness is in doubt.
        raise EnvelopeReplayError(f"envelope seq={env.seq} expired at {env.expires_at}")

    if env.seq <= store.durable_high_water(env.sender_id):
        raise EnvelopeReplayError(
            f"seq={env.seq} <= high_water={store.durable_high_water(env.sender_id)}"
        )

    if store.nonce_seen(env.sender_id, env.nonce):
        raise EnvelopeReplayError(f"nonce already seen for seq={env.seq}")

    if store.effect_applied(env.sender_id, env.seq):
        # Effect exists but replay window did not advance: the exact failure state.
        raise ReplayStateInconsistent(
            f"effect for seq={env.seq} already applied but high_water not advanced"
        )

    return "accept"
