# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-discovery-mismatch-that-silently-orphans-push-notification-webhook-bindings-across-task-lifecy.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-discovery-mismatch-that-silently-orphans-push-notification-webhook-bindings-across-task-lifecy.warrant.json
# Markdown SHA-256:   e0ed85a6058008aaf7efc758e9416a181275c97c227fdcafb3c0f64e2e1ede06
# Code AST SHA-256:   21f7d1141daac3f37af13f0962fc3e356f92c4237fc786b966bad7ac7fdefcf4
# Verified Classes:   OrphanedWebhookBindingError, Binding, WebhookReceiver
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class OrphanedWebhookBindingError(RuntimeError):
    """Raised when a push-notification callback cannot be matched to a live,
    same-origin-verified binding for a task the client still owns."""
    pass


@dataclass
class Binding:
    task_id: str
    registered_url: str
    origin: str
    generation: int
    verified_at: float
    live: bool = True


class WebhookReceiver:
    def __init__(self, max_binding_age_s: float = 300.0):
        self._bindings: dict[str, Binding] = {}
        self._max_age = max_binding_age_s

    def register(self, task_id: str, url: str, origin: str, generation: int) -> Binding:
        b = Binding(task_id, url, origin, generation, time.time())
        self._bindings[task_id] = b
        return b

    def reverify(self, task_id: str, server_echo_url: str, server_origin: str) -> None:
        b = self._bindings.get(task_id)
        if b is None or not b.live:
            raise OrphanedWebhookBindingError(
                f"reverify: no live binding for task {task_id!r}"
            )
        if server_echo_url != b.registered_url or server_origin != b.origin:
            b.live = False
            raise OrphanedWebhookBindingError(
                f"reverify mismatch for {task_id!r}: registered "
                f"{b.registered_url}@{b.origin} vs server "
                f"{server_echo_url}@{server_origin}; demote to polling"
            )
        b.verified_at = time.time()

    def on_callback(self, task_id: str, payload_state: str, callback_origin: str) -> dict:
        b = self._bindings.get(task_id)
        if b is None or not b.live:
            raise OrphanedWebhookBindingError(
                f"callback for {task_id!r} has no live binding; quarantine payload"
            )
        if callback_origin != b.origin:
            raise OrphanedWebhookBindingError(
                f"callback origin {callback_origin} != bound origin {b.origin} "
                f"for task {task_id!r}; possible recycled-ID poisoning"
            )
        if time.time() - b.verified_at > self._max_age:
            b.live = False
            raise OrphanedWebhookBindingError(
                f"binding for {task_id!r} stale beyond {self._max_age}s; "
                f"re-verify before accepting {payload_state!r}"
            )
        return {"task_id": task_id, "state": payload_state, "accepted": True}
