# 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-taskstatusupdateevent-as-authoritative-after-a-push-notification-webhook-replay-and-when-must.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-taskstatusupdateevent-as-authoritative-after-a-push-notification-webhook-replay-and-when-must.warrant.json
# Markdown SHA-256:   a048dbcfda4903c116425926cedecdcbd621a1ea66f7831a5d11199222d41bd1
# Code AST SHA-256:   98be984c1890009816c953f42c86c5c1842ff563b7590b6f107cd31600e0307d
# Verified Classes:   TaskStateDivergence, Projection
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

TERMINAL = {"completed", "failed", "canceled"}
LEGAL = {
    "submitted": {"working", "completed", "failed", "canceled"},
    "working": {"input-required", "completed", "failed", "canceled"},
    "input-required": {"working", "canceled"},
}
CLOCK_SKEW_BUDGET_S = 5.0
RECONCILE_FLOOR_S = 30.0


class TaskStateDivergence(RuntimeError):
    """Raised when a webhook event cannot be safely applied to the local projection."""


@dataclass
class Projection:
    task_id: str
    state: str = "submitted"
    last_ts: float = 0.0
    last_reconciled: float = field(default_factory=time.time)


def apply_webhook_event(proj: Projection, event_state: str, event_ts: float,
                        now: Optional[float] = None) -> bool:
    """Apply a TaskStatusUpdateEvent to the local projection.

    Returns True if applied directly, False if the caller must re-derive via tasks/get.
    Raises TaskStateDivergence on a payload that must never be applied.
    """
    now = now if now is not None else time.time()

    if event_ts > now + CLOCK_SKEW_BUDGET_S:
        raise TaskStateDivergence(
            f"task {proj.task_id}: event timestamp {event_ts:.3f} exceeds "
            f"skew budget ({now:.3f} + {CLOCK_SKEW_BUDGET_S}s); quarantined"
        )

    if proj.state in TERMINAL and event_state not in TERMINAL:
        return False  # terminal is absorbing; treat as replay hint

    if event_ts <= proj.last_ts:
        return False  # stale or duplicate; re-derive to be safe

    if event_state not in LEGAL.get(proj.state, set()):
        return False  # illegal transition; re-derive from tasks/get

    proj.state = event_state
    proj.last_ts = event_ts
    return True


def reconcile_if_due(proj: Projection, now: Optional[float] = None) -> bool:
    """Unconditional reconciliation floor. Webhook arrivals must not reset this."""
    now = now if now is not None else time.time()
    if proj.state in TERMINAL:
        return False
    if now - proj.last_reconciled < RECONCILE_FLOOR_S:
        return False
    proj.last_reconciled = now
    return True


def consume_artifact_gate(proj: Projection, event_state: str) -> None:
    """Guard: artifacts may only be consumed from a re-derived terminal status."""
    if event_state == "completed" and proj.last_reconciled < proj.last_ts:
        raise TaskStateDivergence(
            f"task {proj.task_id}: refusing to consume artifacts from a "
            f"webhook-sourced terminal state; call tasks/get first"
        )
