# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-push-notification-webhook-signature-verification-as-a-per-task-epoch-rather-than-a-per-agent-constan.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-push-notification-webhook-signature-verification-as-a-per-task-epoch-rather-than-a-per-agent-constan.warrant.json
# Markdown SHA-256:   da875c2519d550f82b50c2ad9b98247ef6264ff26367e1e0a762776512aec7b6
# Code AST SHA-256:   1b452925ccbd7c811abf351f9ef2f8b3be6dfd62f3ad5325033fbe915a8b053c
# Verified Classes:   StaleEpochError, UnknownSigningKeyError, JWKSUnavailableError, TaskEpoch, EpochBoundVerifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class StaleEpochError(RuntimeError):
    """Inbound webhook is validly signed but not reachable from local task state."""


class UnknownSigningKeyError(RuntimeError):
    """Webhook kid is absent from JWKS even after a bounded refresh."""


class JWKSUnavailableError(RuntimeError):
    """JWKS endpoint unreachable; refusing to fall back to stale key set."""


LEGAL_TRANSITIONS: Dict[str, Set[str]] = {
    "submitted": {"working", "canceled", "failed"},
    "working": {"input-required", "completed", "canceled", "failed"},
    "input-required": {"working", "canceled", "failed"},
    "completed": set(),
    "canceled": set(),
    "failed": set(),
}


@dataclass
class TaskEpoch:
    task_id: str
    state: str
    epoch: int = 0
    last_jwks_refresh: float = 0.0
    jwks: Dict[str, str] = field(default_factory=dict)  # kid -> public key
    jwks_uri: str = ""


class EpochBoundVerifier:
    JWKS_REFRESH_MIN_INTERVAL_S = 60.0

    def __init__(self, task: TaskEpoch, jwks_fetcher):
        self.task = task
        self._fetch_jwks = jwks_fetcher

    def _refresh_jwks(self, now: float) -> None:
        if now - self.task.last_jwks_refresh < self.JWKS_REFRESH_MIN_INTERVAL_S:
            raise UnknownSigningKeyError(
                f"kid miss within refresh cooldown for {self.task.task_id}; "
                "refusing to hammer JWKS endpoint"
            )
        try:
            self.task.jwks = self._fetch_jwks(self.task.jwks_uri)
        except Exception as exc:
            raise JWKSUnavailableError(
                f"JWKS fetch failed for {self.task.jwks_uri}: {exc}"
            ) from exc
        self.task.last_jwks_refresh = now

    def verify(self, kid: str, signature: bytes, payload: bytes, new_state: str) -> int:
        now = time.monotonic()

        if kid not in self.task.jwks:
            self._refresh_jwks(now)
            if kid not in self.task.jwks:
                raise UnknownSigningKeyError(
                    f"kid {kid!r} unknown after refresh for task {self.task.task_id}"
                )

        # Signature check is delegated; assume it passes here.
        if not self._signature_ok(kid, signature, payload):
            raise StaleEpochError(
                f"signature invalid for kid {kid!r} on task {self.task.task_id}"
            )

        if new_state not in LEGAL_TRANSITIONS.get(self.task.state, set()):
            raise StaleEpochError(
                f"illegal transition {self.task.state} -> {new_state} "
                f"on task {self.task.task_id} at epoch {self.task.epoch}; "
                "probable replay or out-of-order delivery"
            )

        self.task.state = new_state
        self.task.epoch += 1
        return self.task.epoch

    def _signature_ok(self, kid: str, signature: bytes, payload: bytes) -> bool:
        # Real implementation verifies JWS against self.task.jwks[kid].
        return True
