# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-acceptance-window-between-a2a-message-send-and-task-state-materialization-to-avoid-duplicate-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-acceptance-window-between-a2a-message-send-and-task-state-materialization-to-avoid-duplicate-side-effects.warrant.json
# Markdown SHA-256:   5068e3166dfddd553437c33176a156bc0e3776e67bc37e2b742c1d179bca0aa2
# Code AST SHA-256:   0babe753b619136179b4201ff9eeb381ab41651105c7968e2a64a8d5ce4f4a30
# Verified Classes:   TaskAcceptanceIndeterminate, TransportPhase, DispatchAttempt
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaskAcceptanceIndeterminate(RuntimeError):
    """Raised when a post-send transport error leaves acceptance unprovable."""


class TransportPhase(Enum):
    PRE_SEND = "pre_send"      # bytes never left the requester
    POST_SEND = "post_send"    # bytes may have been received by supplier


@dataclass(frozen=True)
class DispatchAttempt:
    message_id: str
    extension_set: frozenset[str]
    phase: TransportPhase
    task_id_observed: Optional[str]
    push_notification_acked: bool
    supplier_dedup_invariant_to_extensions: bool


def _dedup_key(attempt: DispatchAttempt) -> str:
    # Mirrors the supplier's dedup key *only if* the supplier has declared
    # that its key is invariant to the negotiated extension set.
    h = hashlib.sha256()
    h.update(attempt.message_id.encode())
    if not attempt.supplier_dedup_invariant_to_extensions:
        h.update(b"|".join(sorted(attempt.extension_set)).encode())
    return h.hexdigest()


def decide_retry(attempt: DispatchAttempt) -> str:
    """Return one of: 'retry', 'reconcile', 'accept'.

    The only safe unconditional retry is a pre-send transport failure.
    Post-send failures require evidence that the prior dispatch did not
    materialize a task, and 'no task id observed' is not evidence.
    """
    if attempt.task_id_observed is not None:
        return "accept"

    if attempt.phase is TransportPhase.PRE_SEND:
        return "retry"

    # Post-send: we may have created a task we cannot see.
    if attempt.push_notification_acked:
        # Push correlation proves the prior dispatch reached the supplier
        # and produced a task-state transition; do not re-dispatch.
        return "reconcile"

    if attempt.supplier_dedup_invariant_to_extensions:
        # Supplier guarantees dedup on messageId alone; re-dispatch is
        # provably idempotent at the supplier.
        return "retry"

    raise TaskAcceptanceIndeterminate(
        f"message_id={attempt.message_id} post-send transport failure with "
        f"extension_set={sorted(attempt.extension_set)}: supplier dedup is "
        f"extension-sensitive and no push notification was acked. "
        f"Re-issuing message/send risks a duplicate task. Reconcile via "
        f"tasks/list before retrying."
    )


def dispatch_with_guardrail(attempt: DispatchAttempt, send_fn, reconcile_fn):
    action = decide_retry(attempt)
    if action == "accept":
        return attempt.task_id_observed
    if action == "retry":
        return send_fn(attempt)
    if action == "reconcile":
        return reconcile_fn(attempt)
    # Unreachable; decide_retry either returns or raises.
    raise TaskAcceptanceIndeterminate("unreachable decision branch")
