# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-replayed-a2a-handshake-when-ephemeral-task-keys-collide-across-resumed-checkpoints.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-replayed-a2a-handshake-when-ephemeral-task-keys-collide-across-resumed-checkpoints.warrant.json
# Markdown SHA-256:   2f2db506d82b8ef5836e9538bfb5c3063abb8970a13d01a28bc23698e3149026
# Code AST SHA-256:   bb96975b025ea9dd8a0c338f8735ade3a4834472de5b8f8f407512ca9fe8facc
# Verified Classes:   EphemeralKeyReuseError, ReplayWindowViolation, SupersessionWarrant, HandshakeState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EphemeralKeyReuseError(RuntimeError):
    """Raised when a ClientHello presents an ephemeral public key already
    accepted for this peer and task lineage, without a supersession warrant."""


class ReplayWindowViolation(RuntimeError):
    """Raised when a ClientHello nonce is already inside the replay window."""


@dataclass
class SupersessionWarrant:
    prior_nonce: str
    prior_session_id: str
    new_nonce: str
    eph_pub: bytes
    task_lineage_id: str
    signature: bytes  # verified against the checkpoint authority's key


@dataclass
class HandshakeState:
    replay_window: dict = field(default_factory=dict)      # (peer, nonce) -> True
    accepted_keys: dict = field(default_factory=dict)      # (peer, lineage, eph_pub) -> session_id
    warrant_log: list = field(default_factory=list)


def _verify_warrant(w: SupersessionWarrant, trusted_authority_pub: bytes) -> bool:
    # Placeholder: real impl verifies Ed25519 over the canonical field encoding.
    payload = b"|".join([
        w.prior_nonce.encode(), w.prior_session_id.encode(),
        w.new_nonce.encode(), w.eph_pub, w.task_lineage_id.encode(),
    ])
    expected = hashlib.sha256(payload + trusted_authority_pub).digest()
    return w.signature == expected


def accept_client_hello(
    state: HandshakeState,
    peer_id: str,
    task_lineage_id: str,
    nonce: str,
    eph_pub: bytes,
    warrant: SupersessionWarrant | None,
    trusted_authority_pub: bytes,
) -> str:
    if (peer_id, nonce) in state.replay_window:
        raise ReplayWindowViolation(
            f"nonce {nonce!r} from {peer_id!r} already inside replay window"
        )

    key_slot = (peer_id, task_lineage_id, eph_pub)
    if key_slot in state.accepted_keys:
        prior_session_id = state.accepted_keys[key_slot]
        if warrant is None:
            raise EphemeralKeyReuseError(
                f"ephemeral key for {peer_id!r}/{task_lineage_id!r} already bound "
                f"to session {prior_session_id!r}; no supersession warrant presented"
            )
        if not _verify_warrant(warrant, trusted_authority_pub):
            raise EphemeralKeyReuseError(
                f"supersession warrant for {peer_id!r}/{task_lineage_id!r} failed "
                f"signature verification against trusted authority"
            )
        if warrant.prior_session_id != prior_session_id:
            raise EphemeralKeyReuseError(
                f"warrant names prior session {warrant.prior_session_id!r} but "
                f"accepted key is bound to {prior_session_id!r}; refusing fork"
            )
        if warrant.new_nonce != nonce or warrant.eph_pub != eph_pub:
            raise EphemeralKeyReuseError(
                "warrant does not cover the presented nonce/eph_pub pair"
            )
        state.warrant_log.append(warrant)

    # Atomically commit: window entry and key binding must land together,
    # or a crash between them reintroduces the resume-boundary failure.
    new_session_id = hashlib.sha256(
        peer_id.encode() + task_lineage_id.encode() + nonce.encode() + eph_pub
    ).hexdigest()[:16]
    state.replay_window[(peer_id, nonce)] = True
    state.accepted_keys[key_slot] = new_session_id
    return new_session_id
