# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-push-notification-binding-from-outliving-the-task-lifecycle.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-push-notification-binding-from-outliving-the-task-lifecycle.warrant.json
# Markdown SHA-256:   2f949c952c087d6e954539aa9205a2a41a3b370c8812e4edde393c2a3ee0d6b3
# Code AST SHA-256:   1031940faa62cb7838ad120c945e2b0d946e8797c02ee648980c443dfe13d750
# Verified Classes:   BindingDriftError, Task, PushBinding, StatusEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class BindingDriftError(RuntimeError):
    """Raised when a push-notification binding is used outside its task's valid lifecycle."""
    pass


TERMINAL_STATES = frozenset({"completed", "failed", "canceled", "rejected"})


@dataclass
class Task:
    task_id: str
    state: str  # submitted | working | completed | failed | canceled | rejected


@dataclass
class PushBinding:
    push_config_id: str
    task_id: str
    webhook_url: str
    token: str
    delivered_event_ids: set = field(default_factory=set)


@dataclass
class StatusEvent:
    task_id: str
    push_config_id: str
    event_id: str
    payload: bytes


def register_binding(task: Task, webhook_url: str, token: str, push_config_id: str) -> PushBinding:
    # Gate (2): registration-time state gate — reject if task already terminal.
    if task.state in TERMINAL_STATES:
        raise BindingDriftError(
            f"refusing to bind push config to terminal task {task.task_id} (state={task.state})"
        )
    return PushBinding(
        push_config_id=push_config_id,
        task_id=task.task_id,
        webhook_url=webhook_url,
        token=token,
    )


def deliver(task: Task, binding: PushBinding, event: StatusEvent, signing_key: bytes) -> bool:
    # Conjunct 1-2: identity match across both key spaces.
    if binding.task_id != event.task_id or binding.push_config_id != event.push_config_id:
        raise BindingDriftError(
            f"binding {binding.push_config_id} does not match event {event.event_id}"
        )

    # Conjunct 3: token authenticates the channel.
    expected = hmac.new(signing_key, event.payload, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, binding.token):
        raise BindingDriftError(f"token mismatch for binding {binding.push_config_id}")

    # Conjunct 4: terminal-event replay suppression — the commonly omitted guard.
    if task.state in TERMINAL_STATES and event.event_id in binding.delivered_event_ids:
        raise BindingDriftError(
            f"terminal event {event.event_id} already delivered for task {task.task_id}; "
            f"binding {binding.push_config_id} would drift past task lifecycle"
        )

    binding.delivered_event_ids.add(event.event_id)
    return True
