# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-is-unrecoverable-after-a-push-notification-signature-mismatch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-is-unrecoverable-after-a-push-notification-signature-mismatch.warrant.json
# Markdown SHA-256:   3fbdc99ecc894fe7371efeeabe68f1ff727f9af06956322bfecad3646f2125e6
# Code AST SHA-256:   e8b884e9b6efb8aa5b909c33d2009303c7b3d0dc2e88f81de4165aeb4a852276
# Verified Classes:   PushObservationGapError, SignatureKeyStaleError, TaskObservation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class PushObservationGapError(RuntimeError):
    """Raised when a task's terminal state cannot be observed via push
    notifications and the caller has no positive evidence of the gap."""
    pass


class SignatureKeyStaleError(PushObservationGapError):
    """Raised when JWS verification fails against cached keys but the
    caller has not yet re-fetched the agent card's JWKS."""
    pass


@dataclass
class TaskObservation:
    task_id: str
    last_observed_state: str = "submitted"
    last_webhook_at: Optional[float] = None
    dispatched_at: float = field(default_factory=time.time)
    expected_runtime_s: float = 60.0
    reconciliation_interval_s: float = 15.0


def verify_push_notification(
    obs: TaskObservation,
    jws_valid_against_cached: bool,
    jws_valid_against_fresh: Optional[bool],
) -> bool:
    if jws_valid_against_cached:
        return True
    if jws_valid_against_fresh is None:
        # We have not re-fetched JWKS. This is a recoverable key-rotation
        # event, not a permanent rejection. Do NOT return False yet.
        raise SignatureKeyStaleError(
            f"task {obs.task_id}: JWS failed against cached keys; "
            f"re-fetch JWKS from agent card before rejecting"
        )
    if not jws_valid_against_fresh:
        # Invalid even against fresh keys: permanent, but now we KNOW
        # we have an observation gap and must reconcile.
        raise PushObservationGapError(
            f"task {obs.task_id}: notification permanently unverifiable; "
            f"reconciliation poll required"
        )
    return True


def reconcile_or_redispatch(obs: TaskObservation) -> str:
    now = time.time()
    last_signal = obs.last_webhook_at or obs.dispatched_at
    gap = now - last_signal

    if obs.last_observed_state in ("completed", "failed", "canceled"):
        return obs.last_observed_state

    if gap > obs.reconciliation_interval_s:
        # Positive evidence of a possible observation gap: reconcile
        # via tasks/get BEFORE any re-dispatch decision.
        return "reconcile"

    if gap > obs.expected_runtime_s * 2:
        # No webhook, no reconciliation result, past 2x expected runtime.
        # We cannot distinguish stalled from unobserved-terminal.
        raise PushObservationGapError(
            f"task {obs.task_id}: state indeterminate after {gap:.0f}s; "
            f"refusing to re-dispatch without tasks/get reconciliation"
        )

    return "continue"
