# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-task-state-divergence-when-a2a-v1-0-task-lifecycle-negotiation-succeeds-at-the-protocol-layer-but-the-peer-s-inte.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-task-state-divergence-when-a2a-v1-0-task-lifecycle-negotiation-succeeds-at-the-protocol-layer-but-the-peer-s-inte.warrant.json
# Markdown SHA-256:   715cc1a3ad91617a802c662924a0bf374dda49fa2fbeb1eef8554813f3cb10a9
# Code AST SHA-256:   2dd61ac192e6f47c9c0183ca58108beaa6d4d1efbb69e629ef1eab02dbbfdd74
# Verified Classes:   TaskState, ProjectionDivergenceError, TaskView, TerminalConfirmationGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


TERMINAL = {TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED}


class ProjectionDivergenceError(RuntimeError):
    """Raised when peer task state contradicts an acknowledged state-mutating operation."""
    pass


@dataclass
class TaskView:
    task_id: str
    state: TaskState
    epoch: Optional[int] = None
    artifact_present: bool = False
    observed_at: float = field(default_factory=time.monotonic)


class TerminalConfirmationGuard:
    """
    Enforces the A2A v1.0 invariant that a 200 OK on tasks/cancel does not
    imply the peer's internal state machine has transitioned to canceled.
    Requires terminal-state confirmation before closing the local ledger.
    """

    def __init__(self, poll_interval: float = 2.0, confirmation_deadline: float = 30.0):
        self.poll_interval = poll_interval
        self.confirmation_deadline = confirmation_deadline

    def confirm_cancel(
        self,
        task_id: str,
        cancel_ack: TaskView,
        poll_fn,
    ) -> TaskView:
        """
        poll_fn: callable(task_id) -> TaskView, performs tasks/get.
        Returns the terminal TaskView the client should adopt.
        Raises ProjectionDivergenceError if the peer never reaches a terminal
        state or returns a state inconsistent with the cancel acknowledgment.
        """
        if cancel_ack.state in TERMINAL:
            # Peer was already terminal when cancel was issued; accept it.
            return cancel_ack

        deadline = time.monotonic() + self.confirmation_deadline
        last_epoch = cancel_ack.epoch

        while time.monotonic() < deadline:
            time.sleep(self.poll_interval)
            view = poll_fn(task_id)

            if view.epoch is not None and last_epoch is not None:
                if view.epoch < last_epoch:
                    raise ProjectionDivergenceError(
                        f"task {task_id}: epoch regressed {last_epoch} -> {view.epoch}; "
                        f"peer re-opened a closed task ID"
                    )
                last_epoch = view.epoch

            if view.state in TERMINAL:
                if view.state == TaskState.COMPLETED and not view.artifact_present:
                    raise ProjectionDivergenceError(
                        f"task {task_id}: peer reported completed after cancel ack "
                        f"but produced no artifact; cancel may have been silently dropped"
                    )
                return view

            if view.state == TaskState.WORKING:
                # Still projected as working; keep polling until deadline.
                continue

            raise ProjectionDivergenceError(
                f"task {task_id}: unexpected state {view.state} during cancel confirmation"
            )

        raise ProjectionDivergenceError(
            f"task {task_id}: no terminal state within {self.confirmation_deadline}s "
            f"after cancel ack; peer projection lag exceeds client tolerance"
        )
