# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-a2a-v1-0-agent-card-whose-capabilities-pushnotifications-flag-is-true-given-that-the-card-is-cr.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-a2a-v1-0-agent-card-whose-capabilities-pushnotifications-flag-is-true-given-that-the-card-is-cr.warrant.json
# Markdown SHA-256:   54a3180c70a3cb24719d8d565ab208513d451edbde3b2a306a27c7ef62a4ead3
# Code AST SHA-256:   49c8feff33da8ecd85c564f64d99a005869b84d984f84e95a9a0f343e511dbbf
# Verified Classes:   PushNotificationContractError, AgentCard, TrustRecord, PushCapabilityGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class PushNotificationContractError(RuntimeError):
    """Raised when a peer's Agent Card advertises pushNotifications but the
    task lifecycle cannot be shown to reach a notifiable state for the
    intended skill, or when the webhook contract is unverifiable."""


@dataclass
class AgentCard:
    url: str
    streaming: bool
    push_notifications: bool
    input_modes: list
    output_modes: list
    skills: list = field(default_factory=list)


@dataclass
class TrustRecord:
    origin: str
    webhook_observed: bool = False
    last_card_signature: Optional[str] = None


class PushCapabilityGate:
    def __init__(self, trust_window_seconds: int = 3600):
        self._trust: dict[str, TrustRecord] = {}
        self._window = trust_window_seconds

    def _trusted(self, origin: str, sig: str) -> bool:
        rec = self._trust.get(origin)
        return bool(rec and rec.webhook_observed and rec.last_card_signature == sig)

    def evaluate(self, card: AgentCard, signature: str, payload_mode: str) -> str:
        """Return 'register' or 'poll'. Raise on hard contract violations."""
        if payload_mode not in card.input_modes:
            raise PushNotificationContractError(
                f"input mode {payload_mode!r} not in card.input_modes "
                f"{card.input_modes!r}; task would park in 'submitted' "
                f"and no notification can fire"
            )

        if not card.push_notifications:
            return "poll"

        # The boundary condition: push=true, streaming=false, unproven peer.
        if card.push_notifications and not card.streaming:
            if not self._trusted(card.url, signature):
                raise PushNotificationContractError(
                    f"peer {card.url} advertises pushNotifications with "
                    f"streaming=false and no observed webhook; notification "
                    f"emission is unproven for this peer. Fall back to "
                    f"tasks/get polling or run a capability probe first."
                )

        if card.push_notifications and card.streaming:
            if not self._trusted(card.url, signature):
                # Legal but unverified; caller may register with watchdog.
                return "register_with_watchdog"

        return "register"

    def record_webhook(self, origin: str, signature: str) -> None:
        self._trust[origin] = TrustRecord(
            origin=origin, webhook_observed=True, last_card_signature=signature
        )


def register_or_fallback(gate: PushCapabilityGate, card: AgentCard,
                         signature: str, payload_mode: str,
                         task_timeout_s: int) -> str:
    decision = gate.evaluate(card, signature, payload_mode)
    if decision == "poll":
        return f"poll every {max(5, task_timeout_s // 10)}s"
    if decision == "register_with_watchdog":
        # Arm a NotificationTimeout watchdog; if no webhook by
        # 2*timeout, demote peer and resync via tasks/get.
        return "register; arm NotificationTimeout watchdog"
    return "register"


# --- observed failure reproduction ---
if __name__ == "__main__":
    card = AgentCard(
        url="https://worker-b.example",
        streaming=False,
        push_notifications=True,
        input_modes=["text/plain"],
        output_modes=["text/plain"],
    )
    gate = PushCapabilityGate()
    # This call raises: the exact condition under which the instance must
    # reject the push registration despite a valid, schema-conformant card.
    register_or_fallback(gate, card, signature="valid-jws", payload_mode="text/plain",
                         task_timeout_s=600)
