# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-a2a-agent-card-as-non-authoritative-for-task-state-transitions-after-a-push-notification-webhook.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-a2a-agent-card-as-non-authoritative-for-task-state-transitions-after-a-push-notification-webhook.warrant.json
# Markdown SHA-256:   fbe9e822f55ac93d4bcf7bc2726baebc2cf87d6fbdfe3edc12ac358d900d37a7
# Code AST SHA-256:   b63a70d04a3dbd82c7a7861b8775bc35d2f12cf058798fd8522506c0ceb039d0
# Verified Classes:   OrphanedSubscriptionError, IllegalTransitionError, Subscription
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class OrphanedSubscriptionError(RuntimeError):
    """Raised when a webhook arrives for a task whose bound card revision
    no longer matches the peer's current Agent Card revision."""
    pass


class IllegalTransitionError(RuntimeError):
    """Raised when a webhook asserts a state transition that is neither a
    legal forward move from the confirmed state nor a recognized restart."""
    pass


FORWARD = {
    "submitted": {"working", "canceled", "failed"},
    "working": {"input-required", "completed", "failed", "canceled"},
    "input-required": {"working", "canceled", "failed"},
    "completed": set(),
    "failed": set(),
    "canceled": set(),
}


def card_revision(card: dict) -> str:
    """Stable revision identifier for an Agent Card."""
    material = (
        card.get("url", "")
        + str(sorted(card.get("capabilities", {}).items()))
        + str(card.get("pushNotifications", {}))
    )
    return hashlib.sha256(material.encode()).hexdigest()


@dataclass
class Subscription:
    task_id: str
    bound_revision: str
    confirmed_state: str


def handle_webhook(
    sub: Subscription,
    payload: dict,
    current_card: dict,
    signature_ok: bool,
    reconcile,  # callable(task_id) -> str, performs tasks/get
) -> str:
    """Apply a push-notification webhook, enforcing the revision-binding invariant.

    Returns the new confirmed state.
    """
    live_rev = card_revision(current_card)

    if sub.bound_revision != live_rev:
        # Orphaned subscription: card changed since we subscribed.
        # Do NOT trust the payload body. Reconcile against tasks/get.
        if not signature_ok:
            raise OrphanedSubscriptionError(
                f"task {sub.task_id}: card revision drifted and webhook "
                f"signature failed; refusing to apply payload"
            )
        true_state = reconcile(sub.task_id)
        if true_state != sub.confirmed_state:
            # Peer restarted or advanced the task under a new contract.
            sub.confirmed_state = true_state
            sub.bound_revision = live_rev
            return true_state
        sub.bound_revision = live_rev
        return sub.confirmed_state

    # Revision matches: signature must verify, transition must be legal.
    if not signature_ok:
        raise IllegalTransitionError(
            f"task {sub.task_id}: signature failed at matching revision; "
            f"possible injection or mid-flight key rotation"
        )

    new_state = payload["status"]["state"]
    if new_state == sub.confirmed_state:
        return sub.confirmed_state  # duplicate delivery, idempotent

    if new_state in FORWARD.get(sub.confirmed_state, set()):
        sub.confirmed_state = new_state
        return new_state

    # Backwards or illegal transition at matching revision: treat as restart
    # only if tasks/get confirms it; otherwise hard-fail.
    true_state = reconcile(sub.task_id)
    if true_state == new_state:
        sub.confirmed_state = new_state
        return new_state

    raise IllegalTransitionError(
        f"task {sub.task_id}: webhook claims {new_state} from "
        f"{sub.confirmed_state}, but tasks/get reports {true_state}"
    )
