# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-task-state-as-authoritative-only-after-the-input-required-working-transition-is-acknowledged-and-ref.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-task-state-as-authoritative-only-after-the-input-required-working-transition-is-acknowledged-and-ref.warrant.json
# Markdown SHA-256:   22945fdfc6b144a0fb10a589009daaacd85b2d846f9309ef6c09dc2735dcd8a8
# Code AST SHA-256:   2514f11899563d9b21acfa87d42aa229f06fdb846124f5257dddd47892faf3d9
# Verified Classes:   UnacknowledgedResumeError, TaskSnapshot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class UnacknowledgedResumeError(RuntimeError):
    """Raised when a caller advances local task state past a resume
    transition the callee has not durably acknowledged."""


@dataclass
class TaskSnapshot:
    task_id: str
    state: str  # submitted | working | input-required | completed | failed | canceled
    resume_synchronous_declared: bool


def resume_and_gate(
    task: TaskSnapshot,
    post_resume: Callable[[str], TaskSnapshot],
    poll_durable_state: Callable[[str], TaskSnapshot],
    deadline_s: float = 30.0,
    poll_interval_s: float = 0.5,
) -> TaskSnapshot:
    """POST the resume payload, then gate local advancement on the callee's
    durable state reaching 'working'.

    Returns the acknowledged snapshot. Raises UnacknowledgedResumeError if the
    callee never acknowledges the working transition within the deadline, or
    if the resume response echoes a state that contradicts a declared
    synchronous contract.
    """
    if task.state != "input-required":
        raise UnacknowledgedResumeError(
            f"task {task.task_id}: resume attempted from state {task.state!r}, "
            f"expected 'input-required'"
        )

    echoed = post_resume(task.task_id)

    # Fast path: callee declares synchronous resume AND echoes 'working'.
    if echoed.resume_synchronous_declared and echoed.state == "working":
        return echoed

    # Contradiction: declared synchronous but echoed a non-working state.
    if echoed.resume_synchronous_declared and echoed.state != "working":
        raise UnacknowledgedResumeError(
            f"task {task.task_id}: callee declared synchronous resume but "
            f"echoed state {echoed.state!r}; refusing to advance"
        )

    # Asynchronous (or undeclared) resume: gate on durable state.
    start = time.monotonic()
    while time.monotonic() - start < deadline_s:
        observed = poll_durable_state(task.task_id)
        if observed.state == "working":
            return observed
        if observed.state in ("failed", "canceled"):
            raise UnacknowledgedResumeError(
                f"task {task.task_id}: callee transitioned to {observed.state!r} "
                f"during resume; caller must reconcile, not retry"
            )
        if observed.state == "input-required":
            # Callee re-emitted input-required; schema may have changed.
            # Do NOT retry blindly -- surface for reconciliation.
            time.sleep(poll_interval_s)
            continue
        time.sleep(poll_interval_s)

    raise UnacknowledgedResumeError(
        f"task {task.task_id}: no 'working' acknowledgement within "
        f"{deadline_s}s; local state must not advance"
    )
