# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-chain-whose-warrant-depth-exceeds-the-verifier-s-replay-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-chain-whose-warrant-depth-exceeds-the-verifier-s-replay-horizon.warrant.json
# Markdown SHA-256:   c890798e8a9f47e0e0336183ce7b20aaafe15938d069bb3d101669bfc5340110
# Code AST SHA-256:   bf2989952be7fac7972972f5813dd2cae3552f61d5bcde2ed3dae0fec217167a
# Verified Classes:   ReplayHorizonViolation, ReplayLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ReplayHorizonViolation(RuntimeError):
    """Raised when a delegated AAIF chain's max TTL exceeds the verifier's replay ledger horizon,
    making trunk-replay undetectable by leaf-only counter checks."""
    pass


class ReplayLedger:
    def __init__(self, horizon_seconds: int):
        self.horizon = horizon_seconds
        self.seen: dict[tuple[str, int], float] = {}  # (issuer_key_id, counter) -> seen_at

    def has(self, issuer_key_id: str, counter: int) -> bool:
        return (issuer_key_id, counter) in self.seen

    def record(self, issuer_key_id: str, counter: int, now: float) -> None:
        self.seen[(issuer_key_id, counter)] = now


def admit_chain(chain: list[dict], ledger: ReplayLedger, now: float) -> None:
    # chain is ordered root -> leaf; each warrant: {issuer_key_id, counter, ttl, issued_at}
    if not chain:
        raise ReplayHorizonViolation("empty AAIF chain")

    max_ttl = max(w["ttl"] for w in chain)
    if max_ttl > ledger.horizon:
        # The verifier cannot retain intermediate counters long enough to detect trunk replay.
        raise ReplayHorizonViolation(
            f"chain max ttl {max_ttl}s exceeds replay horizon {ledger.horizon}s; "
            f"trunk replay would be undetectable for {max_ttl - ledger.horizon}s"
        )

    # With horizon >= max_ttl, every intermediate counter must still be live in the ledger.
    for w in chain:
        if ledger.has(w["issuer_key_id"], w["counter"]):
            raise ReplayHorizonViolation(
                f"replay detected: issuer {w['issuer_key_id']} counter {w['counter']} already consumed"
            )

    # Only after full-chain freshness is confirmed do we record the leaf.
    leaf = chain[-1]
    ledger.record(leaf["issuer_key_id"], leaf["counter"], now)
