# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-dpop-bound-mtls-handoff-the-attestation-nonce-replay-window-at-cross-vendor-trust-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-dpop-bound-mtls-handoff-the-attestation-nonce-replay-window-at-cross-vendor-trust-boundaries.warrant.json
# Markdown SHA-256:   b70f55f18337ad337b48e9567343044d2a81909641a0ba7ebc5b6e0d2ba5ad8c
# Code AST SHA-256:   2834bba1c44799a8139111591884040e323ed734138e4fe217db15c25df76eee
# Verified Classes:   ReplayInvariantViolation, Proof, Attestation, QuorumCounter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ReplayInvariantViolation(RuntimeError):
    """Raised when an instance is asked to treat a replayed DPoP proof,
    or a duplicate attestation sharing a jti, as a distinct action."""


@dataclass
class Proof:
    jti: str
    iat: float
    jkt: str


@dataclass
class Attestation:
    jti: str
    jkt: str
    issued_at: float


@dataclass
class QuorumCounter:
    required: int
    # dedupe key is (jkt, jti): same holder, same proof == one action
    seen: set = field(default_factory=set)

    def record(self, att: Attestation) -> int:
        key = (att.jkt, att.jti)
        if key in self.seen:
            raise ReplayInvariantViolation(
                f"attestation jti={att.jti} jkt={att.jkt} already counted; "
                f"peer nonce store likely evicted under load — refusing to "
                f"advance quorum on a replay"
            )
        self.seen.add(key)
        return len(self.seen)


def retry_handoff(sign_fn, send_fn, max_attempts: int = 3) -> Attestation:
    """Retry MUST re-sign with a fresh jti/iat; never resend a cached proof."""
    last_err = None
    for attempt in range(max_attempts):
        proof = sign_fn()  # fresh jti + iat every attempt
        try:
            return send_fn(proof)
        except TimeoutError as e:
            last_err = e
            # deliberately do NOT cache `proof`; it is now replayable
            continue
    raise ReplayInvariantViolation(
        f"handoff failed after {max_attempts} fresh-signed attempts: {last_err}"
    )


def admit_attestation(att: Attestation, quorum: QuorumCounter,
                      max_skew_s: float = 60.0, now: float | None = None) -> int:
    now = time.time() if now is None else now
    if abs(now - att.issued_at) > max_skew_s:
        raise ReplayInvariantViolation(
            f"attestation iat={att.issued_at} outside skew window at now={now}"
        )
    return quorum.record(att)
