# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-attestation-chain-replay-during-delegated-aaif-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-attestation-chain-replay-during-delegated-aaif-handoff.warrant.json
# Markdown SHA-256:   03fde5ce1cf571899de72df867503771ac2fefde528036fabce2d8e8c8aab4fe
# Code AST SHA-256:   b51f4ed4e0e7543400033104a7b77d9a1bea0d0efc84a8772885716e3f28b629
# Verified Classes:   AttestationReplayError, Warrant, NonceLedger
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class AttestationReplayError(RuntimeError):
    """Raised when a delegated AAIF warrant violates delegation cardinality
    or presentation binding invariants."""


@dataclass(frozen=True)
class Warrant:
    parent_nonce: str
    child_nonce: str
    leaf_subject: str
    parent_hash: str
    scope: frozenset
    expires_at: float
    signature_ok: bool


class NonceLedger:
    """Write-once consumption ledger keyed on (parent_nonce, child_nonce, leaf_subject).

    Entries must be retained for at least the root warrant TTL, not the
    intermediate's TTL, because the replay window is bounded by root expiry.
    """

    def __init__(self) -> None:
        self._consumed: dict[tuple[str, str, str], float] = {}

    def consume(self, w: Warrant, now: float) -> None:
        key = (w.parent_nonce, w.child_nonce, w.leaf_subject)
        if key in self._consumed:
            raise AttestationReplayError(
                f"delegation nonce tuple {key} already consumed at "
                f"{self._consumed[key]}; replay of child_nonce={w.child_nonce}"
            )
        self._consumed[key] = now

    def gc(self, now: float, root_ttl_floor: float) -> None:
        # Only evict entries older than the root TTL floor, never the intermediate TTL.
        cutoff = now - root_ttl_floor
        for k in [k for k, t in self._consumed.items() if t < cutoff]:
            del self._consumed[k]


def verify_delegated_warrant(
    warrant: Warrant,
    presenter_identity: str,
    fetched_parent_hash: Optional[str],
    ledger: NonceLedger,
    now: float,
) -> None:
    if not warrant.signature_ok:
        raise AttestationReplayError("signature chain did not verify")

    if warrant.expires_at <= now:
        raise AttestationReplayError(
            f"warrant expired at {warrant.expires_at}, now={now}"
        )

    # Presentation binding: the leaf subject must match the authenticated presenter.
    if warrant.leaf_subject != presenter_identity:
        raise AttestationReplayError(
            f"presentation binding mismatch: warrant names {warrant.leaf_subject!r} "
            f"but presenter is {presenter_identity!r}"
        )

    # Attenuation provenance: the child must have been attenuated from the
    # exact parent bytes the verifier fetched, not a re-issued parent.
    if fetched_parent_hash is None:
        raise AttestationReplayError("parent warrant unavailable for provenance check")
    if fetched_parent_hash != warrant.parent_hash:
        raise AttestationReplayError(
            f"attenuation provenance mismatch: child expects parent "
            f"{warrant.parent_hash[:12]}..., fetched {fetched_parent_hash[:12]}..."
        )

    # Cardinality: consume the nonce tuple; raises on replay.
    ledger.consume(warrant, now)
