# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a2a-v1-0-push-notification-webhook-binding-as-a-non-idempotent-side-effect-rather-than-a-resumable-subscr.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a2a-v1-0-push-notification-webhook-binding-as-a-non-idempotent-side-effect-rather-than-a-resumable-subscr.warrant.json
# Markdown SHA-256:   a11b63c30cd60e1afec629234ad9094ab24f8efe290c7bfb6b981d0dc02ead9c
# Code AST SHA-256:   516317d86c15c4adf4e860d2333e8e1a4fd8f15b0c15237d10e182fb65eb378f
# Verified Classes:   PushConfigBindingError, AgentCard, Checkpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class PushConfigBindingError(RuntimeError):
    """Raised when a task resumption would re-register a non-idempotent webhook binding."""


@dataclass(frozen=True)
class AgentCard:
    push_notifications: bool
    push_config_idempotent: Optional[bool]  # None == unspecified


@dataclass(frozen=True)
class Checkpoint:
    task_id: str
    config_id: Optional[str]   # None if lost during distillation / truncation
    url: str
    token: str


def binding_fingerprint(cp: Checkpoint) -> str:
    h = hashlib.sha256()
    h.update(cp.task_id.encode())
    h.update(b"\x00")
    h.update(cp.url.encode())
    h.update(b"\x00")
    h.update(cp.token.encode())
    return h.hexdigest()


def assert_resumable(card: AgentCard, cp: Checkpoint, server_configs: list[Checkpoint]) -> str:
    """
    Decide whether a task may be resumed without re-registering a webhook.
    Returns the config_id to reuse. Raises PushConfigBindingError otherwise.
    """
    if not card.push_notifications:
        # Polling fallback is the only safe path; caller must not use webhooks.
        raise PushConfigBindingError(
            f"task {cp.task_id}: card does not advertise pushNotifications; "
            "resume via tasks/get polling, not webhook"
        )

    # Case 1: idempotency explicitly advertised -> retry is safe if we have the id.
    if card.push_config_idempotent is True:
        if cp.config_id is None:
            raise PushConfigBindingError(
                f"task {cp.task_id}: idempotent server but checkpoint lost configId; "
                "reconcile via tasks/pushNotificationConfig/list before resume"
            )
        return cp.config_id

    # Case 2: idempotency unspecified or false -> treat set as non-idempotent side effect.
    fp = binding_fingerprint(cp)
    matches = [c for c in server_configs if binding_fingerprint(c) == fp]
    if len(matches) == 1:
        return matches[0].config_id  # type: ignore[return-value]
    if len(matches) > 1:
        raise PushConfigBindingError(
            f"task {cp.task_id}: {len(matches)} duplicate bindings for fingerprint {fp[:12]}; "
            "server accepted multiple creates for one (task,url,token); "
            "delete all but one before resume"
        )
    # No existing binding: a fresh set is safe precisely once.
    if cp.config_id is not None:
        raise PushConfigBindingError(
            f"task {cp.task_id}: checkpoint claims configId {cp.config_id} but server has no "
            "matching config; binding was GC'd or never persisted; re-set once and persist id"
        )
    return "CREATE_ONCE"
