# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-resumed-a2a-task-when-the-agent-card-s-declared-taskstate-capability-set-diverges-from-the-persisted-lifec.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-resumed-a2a-task-when-the-agent-card-s-declared-taskstate-capability-set-diverges-from-the-persisted-lifec.warrant.json
# Markdown SHA-256:   7ee5790aa019ab98069099fd9e92787a6636148b58c58edf346fa3d700c7e68b
# Code AST SHA-256:   1c8553d25d165c38acd1a81f2f3bfa898701334a53a603195b6453ed6bcdc4c5
# Verified Classes:   CardDivergenceError, AgentCard, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CardDivergenceError(RuntimeError):
    """Raised when a persisted A2A checkpoint cannot be safely resumed
    against the currently served Agent Card."""
    pass


@dataclass
class AgentCard:
    card_hash: str
    task_states: set[str]
    transitions: dict[str, set[str]]
    webhook_keys: set[str]  # key IDs declared under securitySchemes


@dataclass
class Checkpoint:
    task_id: str
    state: str
    card_hash: str
    continuation_token: Optional[str] = None
    pending_transition: Optional[str] = None


def validate_resume(checkpoint: Checkpoint,
                    persisted_card: AgentCard,
                    current_card: AgentCard,
                    webhook_key_id: Optional[str] = None) -> str:
    """Return the transition table to use for resume, or raise.

    Invariant: resume is permitted only if the checkpoint's state is
    reachable under the CURRENT card, and every transition the client
    intends to take survives the card delta.
    """
    if webhook_key_id is not None and webhook_key_id not in current_card.webhook_keys:
        raise CardDivergenceError(
            f"webhook key {webhook_key_id!r} not declared in current card "
            f"{current_card.card_hash}; stale-key replay refused for task "
            f"{checkpoint.task_id}"
        )

    removed_states = persisted_card.task_states - current_card.task_states
    if checkpoint.state in removed_states:
        raise CardDivergenceError(
            f"checkpoint state {checkpoint.state!r} for task "
            f"{checkpoint.task_id} was removed in card "
            f"{current_card.card_hash}; checkpoint orphaned"
        )

    if checkpoint.pending_transition is not None:
        persisted_targets = persisted_card.transitions.get(checkpoint.state, set())
        current_targets = current_card.transitions.get(checkpoint.state, set())
        if checkpoint.pending_transition not in current_targets:
            raise CardDivergenceError(
                f"pending transition {checkpoint.state!r} -> "
                f"{checkpoint.pending_transition!r} for task "
                f"{checkpoint.task_id} no longer supported by card "
                f"{current_card.card_hash}"
            )
        # Narrow the table to the surviving intersection.
        return f"{checkpoint.state}->{checkpoint.pending_transition}"

    return f"{checkpoint.state} (no pending transition; resume read-only)"
