# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-terminal-state-divergence-between-its-local-a2a-v1-0-task-projection-and-the-remote-agent-s-authoritative-task-record-du.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-terminal-state-divergence-between-its-local-a2a-v1-0-task-projection-and-the-remote-agent-s-authoritative-task-record-du.warrant.json
# Markdown SHA-256:   786bf78185a1a071e100af93dfba8c8aaf0f1d231f84745e414acd07b5c63f5f
# Code AST SHA-256:   f9e43bfa49b59721109a8d462ff47fa12887aa8fb06bfe841370a3d344bd1870
# Verified Classes:   TaskProjectionDivergence, TaskState, CardDelta
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class TaskProjectionDivergence(RuntimeError):
    """Raised when a live task's remote state is unreachable from the local projection
    and the instance has not yet reconciled against the authoritative remote record."""


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


# Legal edges in a locally-observed A2A v1.0 projection.
_LEGAL: dict[TaskState, set[TaskState]] = {
    TaskState.SUBMITTED: {TaskState.WORKING, TaskState.INPUT_REQUIRED, TaskState.FAILED, TaskState.CANCELED},
    TaskState.WORKING: {TaskState.INPUT_REQUIRED, TaskState.FAILED, TaskState.CANCELED},
    TaskState.INPUT_REQUIRED: {TaskState.WORKING, TaskState.FAILED, TaskState.CANCELED},
    TaskState.COMPLETED: set(),
    TaskState.FAILED: set(),
    TaskState.CANCELED: set(),
}


@dataclass(frozen=True)
class CardDelta:
    url_changed: bool
    skills_changed: bool
    capabilities_changed: bool

    @property
    def requires_reconciliation(self) -> bool:
        return self.url_changed or self.skills_changed or self.capabilities_changed


def reconcile_task(
    task_id: str,
    local_state: TaskState,
    remote_state: TaskState,
    delta: CardDelta,
    reconciled: bool = False,
) -> TaskState:
    """Adopt the remote authoritative state for a live task handle.

    If the remote state is unreachable from the local projection AND the card
    has not changed (so no reconciliation pass has run), raising is the only
    safe outcome: acting on the local projection risks a duplicate side effect.
    """
    if remote_state == local_state:
        return local_state

    legal = remote_state in _LEGAL.get(local_state, set())

    if not legal and not delta.requires_reconciliation and not reconciled:
        raise TaskProjectionDivergence(
            f"task {task_id}: remote state {remote_state.value!r} is unreachable "
            f"from local projection {local_state.value!r} and no card delta "
            f"was observed to justify reconciliation; refusing to adopt"
        )

    if not legal and delta.requires_reconciliation and not reconciled:
        # Card changed under a live handle: the remote record is authoritative.
        # Re-fetch and adopt, marking intermediates as reconciled rather than observed.
        return remote_state

    return remote_state
