# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-push-notification-callbacks-when-an-a2a-v1-0-peer-rotates-its-signing-key-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-push-notification-callbacks-when-an-a2a-v1-0-peer-rotates-its-signing-key-mid-task.warrant.json
# Markdown SHA-256:   6494a77d0560def11130ba0289600e0fe3b93f9d81a073d0b5c351e2e4478783
# Code AST SHA-256:   b96cf835a9f44987896147fdc8e5687a231d3f4e17387caed4d2355cb5248778
# Verified Classes:   KeySetStalenessError, ContinuityGapError, KeySetCache, TaskPushState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class KeySetStalenessError(RuntimeError):
    """Raised when a callback's kid is absent from the cached key set
    and the single permitted re-fetch did not resolve it."""


class ContinuityGapError(RuntimeError):
    """Raised when a task's push channel is known to have dropped events
    and no reconciliation poll has been scheduled to bound the gap."""


@dataclass
class KeySetCache:
    kids: dict[str, str] = field(default_factory=dict)  # kid -> public key
    fetched_at: float = 0.0
    last_refetch_per_kid: dict[str, float] = field(default_factory=dict)
    refetch_cooldown_s: float = 30.0

    def has(self, kid: str) -> bool:
        return kid in self.kids

    def can_refetch(self, kid: str, now: float) -> bool:
        last = self.last_refetch_per_kid.get(kid, 0.0)
        return (now - last) >= self.refetch_cooldown_s

    def record_refetch(self, kid: str, now: float) -> None:
        self.last_refetch_per_kid[kid] = now


@dataclass
class TaskPushState:
    task_id: str
    push_channel_degraded: bool = False
    last_reconciled_at: Optional[float] = None
    reconciliation_interval_s: float = 300.0


def verify_callback_signature(
    kid: str,
    signature: bytes,
    payload: bytes,
    cache: KeySetCache,
    fetch_jwks,  # callable() -> dict[str, str]
    now: Optional[float] = None,
) -> bool:
    """Verify a callback signature. On kid miss, re-fetch the JWKS exactly once
    (rate-limited per kid). If still missing, raise KeySetStalenessError so the
    caller can emit a continuity-gap event rather than a plain auth rejection.
    """
    now = time.time() if now is None else now

    if cache.has(kid):
        return _check(signature, payload, cache.kids[kid])

    if cache.can_refetch(kid, now):
        cache.record_refetch(kid, now)
        cache.kids = fetch_jwks()  # refresh the key set, not just the URL
        cache.fetched_at = now
        if cache.has(kid):
            return _check(signature, payload, cache.kids[kid])

    raise KeySetStalenessError(
        f"kid={kid!r} absent from key set after single re-fetch; "
        f"cached kids={sorted(cache.kids)}"
    )


def _check(signature: bytes, payload: bytes, public_key: str) -> bool:
    # Placeholder for real ES256/JWS verification.
    return signature == b"valid:" + public_key.encode()


def on_callback_rejected(
    task: TaskPushState,
    cache: KeySetCache,
    kid: str,
    schedule_reconcile,  # callable(task_id, delay_s) -> None
    now: Optional[float] = None,
) -> None:
    """Bound the state gap after a key-set staleness rejection.

    Invariant: any signature_key_unknown rejection on an active task must
    (a) mark the push channel degraded, and (b) schedule a reconciliation
    poll within the task's reconciliation_interval_s. Otherwise the gap
    is unbounded by the peer's retry budget.
    """
    now = time.time() if now is None else now
    task.push_channel_degraded = True

    if task.last_reconciled_at is None or (
        now - task.last_reconciled_at > task.reconciliation_interval_s
    ):
        schedule_reconcile(task.task_id, delay_s=0.0)

    if (
        task.push_channel_degraded
        and task.last_reconciled_at is None
        and not cache.has(kid)
    ):
        raise ContinuityGapError(
            f"task={task.task_id!r} push channel degraded on kid={kid!r} "
            f"with no reconciliation scheduled; state gap is unbounded"
        )
