# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-a2a-agent-card-whose-declared-task-lifecycle-no-longer-matches-the-peer-s-live-state-machine-and-why-push-notifica.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-a2a-agent-card-whose-declared-task-lifecycle-no-longer-matches-the-peer-s-live-state-machine-and-why-push-notifica.warrant.json
# Markdown SHA-256:   de082e24e8f2ecdd75cd451ee8ce9aea13cc35346c7a69573ef889c9395e762d
# Code AST SHA-256:   9165f0808e9ee1492566610c4fc4f7ddcff9b75fb0f56d0eb05ded03fc657ed0
# Verified Classes:   TerminalState, TaskReconciliationError, TaskView, ClientTask
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TerminalState(Enum):
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


class TaskReconciliationError(RuntimeError):
    """Raised when a webhook and the pollable task record cannot be reconciled
    into a single terminal state for the same task id."""


@dataclass
class TaskView:
    task_id: str
    state: str
    artifact_hash: Optional[str] = None
    card_pin: Optional[str] = None


@dataclass
class ClientTask:
    task_id: str
    pinned_card_hash: str
    terminal_state: Optional[TerminalState] = None
    prior_terminal_seen: bool = False
    artifacts: dict = field(default_factory=dict)


def _hash_artifacts(artifacts) -> str:
    h = hashlib.sha256()
    for a in sorted(artifacts, key=lambda x: x.get("id", "")):
        h.update(repr(a.get("parts", [])).encode())
    return h.hexdigest()


def reconcile_webhook(
    task: ClientTask,
    webhook: TaskView,
    polled: TaskView,
    current_card_hash: str,
) -> ClientTask:
    if webhook.task_id != task.task_id or polled.task_id != task.task_id:
        raise TaskReconciliationError(
            f"task id mismatch: client={task.task_id} "
            f"webhook={webhook.task_id} poll={polled.task_id}"
        )

    # Card rotated mid-task: notifier and state machine may be different builds.
    if current_card_hash != task.pinned_card_hash:
        raise TaskReconciliationError(
            f"card rotated mid-task for {task.task_id}: "
            f"pinned={task.pinned_card_hash} live={current_card_hash}; "
            f"task is indeterminate, do not retry blindly"
        )

    webhook_terminal = webhook.state in {s.value for s in TerminalState}
    if not webhook_terminal:
        return task  # working/input-required: hint only, no advance

    # Terminal webhook must be confirmed by the authoritative task record.
    if polled.state != webhook.state:
        raise TaskReconciliationError(
            f"webhook/poll state divergence on {task.task_id}: "
            f"webhook={webhook.state} poll={polled.state}"
        )

    webhook_hash = _hash_artifacts(webhook.artifacts or [])
    poll_hash = _hash_artifacts(polled.artifacts or [])
    if webhook_hash != poll_hash:
        raise TaskReconciliationError(
            f"artifact hash divergence on {task.task_id}: "
            f"webhook={webhook_hash[:12]} poll={poll_hash[:12]}"
        )

    # Second terminal webhook for the same task: absorbing-state violation.
    if task.prior_terminal_seen:
        raise TaskReconciliationError(
            f"second terminal transition for {task.task_id}: "
            f"prior={task.terminal_state} new={webhook.state}; "
            f"peer state machine is not absorbing"
        )

    task.prior_terminal_seen = True
    task.terminal_state = TerminalState(webhook.state)
    task.artifacts = {a.get("id"): a for a in (polled.artifacts or [])}
    return task
