# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-s-advertised-capabilities-pushnotifications-as-a-signed-warrant-precondition-rathe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-s-advertised-capabilities-pushnotifications-as-a-signed-warrant-precondition-rathe.warrant.json
# Markdown SHA-256:   39fbee21af9b03126b92d8c1a130d18722bced8d39bc493cd7568ae62659cf1e
# Code AST SHA-256:   8d179289098492c046036ae0c8f0e6e0fa8362ec211785c6b054f4428454c1b4
# Verified Classes:   PushChannelInvariantError, SignatureKeyUnknown, SignatureInvalid, TaskChannel
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class PushChannelInvariantError(RuntimeError):
    """Raised when a push-registered task's channel liveness cannot be proven
    within the watchdog budget, or when the client attempts to treat an Agent
    Card's pushNotifications flag as a warrant without scheme agreement."""


class SignatureKeyUnknown(Exception):
    """Receiver-side: signature's kid is not in the current JWKS allowlist.
    This is a rotation signal, NOT a cryptographic failure. Retry after
    JWKS re-fetch; escalate to client re-registration only if still unknown."""


class SignatureInvalid(Exception):
    """Receiver-side: signature failed cryptographic verification against a
    known kid. Drop, alert, do not retry."""


@dataclass
class TaskChannel:
    task_id: str
    card_push_flag: bool
    scheme_agreed: bool = False
    jwks_allowlist: set = field(default_factory=set)
    last_push_at: Optional[float] = None
    registered_at: Optional[float] = None
    channel_dead: bool = False


def register_push(task: TaskChannel, server_ack_scheme: Optional[str],
                  now: float) -> None:
    # The card flag is necessary but NOT sufficient. Scheme must be echoed.
    if not task.card_push_flag:
        raise PushChannelInvariantError(
            f"task {task.task_id}: card does not advertise push; "
            f"do not register"
        )
    if server_ack_scheme is None:
        raise PushChannelInvariantError(
            f"task {task.task_id}: pushNotification/set response did not "
            f"echo a signature scheme; card flag alone is a discovery hint, "
            f"not a warrant. Refusing to mark channel live."
        )
    task.scheme_agreed = True
    task.registered_at = now


def on_signature_key_unknown(task: TaskChannel, kid: str, jwks_fetch,
                             now: float) -> None:
    # Boundary A: unknown kid triggers JWKS re-fetch, one retry, then escalate.
    fresh = jwks_fetch()
    if kid in fresh:
        task.jwks_allowlist.add(kid)
        return
    # Still unknown after re-fetch -> channel is not provably live.
    task.channel_dead = True
    raise PushChannelInvariantError(
        f"task {task.task_id}: kid {kid!r} absent from refreshed JWKS; "
        f"channel marked dead, client must re-register with scheme "
        f"negotiation and re-fetch Agent Card"
    )


def channel_watchdog(task: TaskChannel, retry_exhaustion_window: float,
                     now: float, tasks_get) -> None:
    if task.channel_dead:
        return
    if task.last_push_at is not None:
        return
    if task.registered_at is None:
        raise PushChannelInvariantError(
            f"task {task.task_id}: watchdog fired on unregistered channel"
        )
    if now - task.registered_at < retry_exhaustion_window:
        return
    # No push within the peer's retry-exhaustion window: the channel is
    # dead even though the task may be working. Poll to disambiguate.
    state = tasks_get(task.task_id)
    if state in ("submitted", "working"):
        task.channel_dead = True
        raise PushChannelInvariantError(
            f"task {task.task_id}: no push in {retry_exhaustion_window}s "
            f"while task state={state!r}; channel dead, task alive. "
            f"Re-register webhook; do not extend task timeout."
        )
