# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-terminal-task-status-delivered-by-push-webhook-against-a-divergent-authoritative-task-record-during-a2a-v1-0-resync.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-terminal-task-status-delivered-by-push-webhook-against-a-divergent-authoritative-task-record-during-a2a-v1-0-resync.warrant.json
# Markdown SHA-256:   888bf4b60f3131ffdabc5a5d4a3fe5410e51f7c50879d6f98e1849012a932127
# Code AST SHA-256:   f09b7d2ceda4d16b3a873e641ae5bf04f186ac78eb153b00de0c03f1d965c6b0
# Verified Classes:   TerminalReconciliationError, LocalTaskRecord, WebhookPayload
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class TerminalReconciliationError(RuntimeError):
    """Raised when a terminal webhook cannot be reconciled against the
    authoritative task record and the client must not proceed."""


@dataclass
class LocalTaskRecord:
    task_id: str
    state: str
    timestamp: float
    artifact_hash: Optional[str] = None
    artifacts_resolvable: bool = True


@dataclass
class WebhookPayload:
    task_id: str
    state: str
    timestamp: float
    artifact_hash: Optional[str] = None


def reconcile_terminal_webhook(
    local: LocalTaskRecord,
    payload: WebhookPayload,
    fetch_authoritative,          # callable(task_id) -> LocalTaskRecord
    artifact_exists,              # callable(hash) -> bool
    max_clock_skew_s: float = 5.0,
) -> LocalTaskRecord:
    """Apply the terminal-absorption invariant.

    A terminal webhook is a no-op duplicate ONLY if it is not newer than the
    local record AND the local artifact reference still resolves. Otherwise it
    is a reconciliation event and we must consult the authoritative record.
    """
    if payload.task_id != local.task_id:
        raise TerminalReconciliationError(
            f"webhook task_id {payload.task_id!r} does not match local "
            f"record {local.task_id!r}"
        )

    if payload.state != "completed" and payload.state != "failed":
        # Non-terminal webhooks are applied directly; no absorption logic.
        local.state = payload.state
        local.timestamp = max(local.timestamp, payload.timestamp)
        return local

    # Terminal webhook. Is it a duplicate or a reconciliation event?
    is_newer = payload.timestamp > local.timestamp + max_clock_skew_s
    local_artifact_ok = (
        local.artifact_hash is None or artifact_exists(local.artifact_hash)
    )

    if local.state in ("completed", "failed"):
        if not is_newer and local_artifact_ok:
            # Genuine duplicate: same-or-older timestamp, artifact still valid.
            return local
        # Otherwise: revision or artifact orphaned. Must reconcile.
        authoritative = fetch_authoritative(local.task_id)
        if authoritative.timestamp < local.timestamp:
            raise TerminalReconciliationError(
                f"authoritative record for {local.task_id!r} is older than "
                f"local ({authoritative.timestamp} < {local.timestamp}); "
                f"server clock or record is inconsistent, refusing to regress"
            )
        if (
            authoritative.artifact_hash is not None
            and not artifact_exists(authoritative.artifact_hash)
        ):
            raise TerminalReconciliationError(
                f"authoritative artifact {authoritative.artifact_hash!r} for "
                f"{local.task_id!r} is not resolvable; cannot commit terminal "
                f"state to memory"
            )
        return authoritative

    # Local record was non-terminal; webhook claims terminal. Verify before
    # writing artifact reference into durable memory.
    authoritative = fetch_authoritative(local.task_id)
    if authoritative.state != payload.state:
        raise TerminalReconciliationError(
            f"webhook claims {payload.state!r} for {local.task_id!r} but "
            f"authoritative state is {authoritative.state!r}"
        )
    if (
        authoritative.artifact_hash is not None
        and not artifact_exists(authoritative.artifact_hash)
    ):
        raise TerminalReconciliationError(
            f"webhook terminal for {local.task_id!r} references unresolvable "
            f"artifact {authoritative.artifact_hash!r}"
        )
    return authoritative
