# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-replayed-a2a-push-notification-as-a-state-machine-violation-rather-than-an-idempotent-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-replayed-a2a-push-notification-as-a-state-machine-violation-rather-than-an-idempotent-retry.warrant.json
# Markdown SHA-256:   33f9fc96be7cba494fcd3dcbae1cd2959c3cf9c94e32c0308915d5be40c85596
# Code AST SHA-256:   5046df3a5ef44e55b7de907d84ff78d5b98a19247fe72523297e8f5e033dd559
# Verified Classes:   TaskState, ContradictoryTerminalState, IllegalStateTransition, TaskMirror
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
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}

# Forward-reachable transitions per A2A v1.0. Backward/skip transitions are
# permitted only when explained by timestamp ordering (handled separately).
REACHABLE = {
    TaskState.SUBMITTED: {TaskState.WORKING, TaskState.INPUT_REQUIRED,
                          TaskState.CANCELED, TaskState.FAILED},
    TaskState.WORKING: {TaskState.INPUT_REQUIRED, TaskState.COMPLETED,
                        TaskState.FAILED, TaskState.CANCELED},
    TaskState.INPUT_REQUIRED: {TaskState.WORKING, TaskState.FAILED,
                               TaskState.CANCELED},
    TaskState.COMPLETED: set(),
    TaskState.FAILED: set(),
    TaskState.CANCELED: set(),
}


class ContradictoryTerminalState(RuntimeError):
    """Raised when a replayed terminal notification carries a divergent payload."""


class IllegalStateTransition(RuntimeError):
    """Raised when a notification's state is not reachable from the mirror's state."""


@dataclass
class TaskMirror:
    task_id: str
    state: TaskState
    payload_hash: Optional[str] = None
    last_transition_at: float = 0.0
    history: list = field(default_factory=list)


def _hash_payload(artifacts: dict) -> str:
    canonical = repr(sorted(artifacts.items())).encode("utf-8")
    return hashlib.sha256(canonical).hexdigest()


def apply_notification(mirror: TaskMirror, notification: dict) -> TaskMirror:
    """
    Apply an A2A v1.0 push-notification to a local task mirror.

    notification = {
        "taskId": str,
        "state": str,
        "artifacts": dict,          # may be empty for non-terminal states
        "terminalReason": str|None,
        "timestamp": float,
        "notificationId": str,      # NOT used for dedupe
    }
    """
    new_state = TaskState(notification["state"])
    new_hash = _hash_payload(notification.get("artifacts") or {})
    ts = float(notification["timestamp"])

    # Case 1: terminal self-transition. Absorb only if payload identical.
    if mirror.state in TERMINAL and new_state == mirror.state:
        if new_hash != mirror.payload_hash:
            raise ContradictoryTerminalState(
                f"task {mirror.task_id}: replayed terminal state {new_state.value} "
                f"with divergent payload hash {new_hash[:12]} != "
                f"{mirror.payload_hash[:12]}"
            )
        mirror.history.append(("noop-duplicate", new_state, ts))
        return mirror

    # Case 2: terminal already reached, different terminal state.
    if mirror.state in TERMINAL and new_state != mirror.state:
        raise ContradictoryTerminalState(
            f"task {mirror.task_id}: terminal state {mirror.state.value} "
            f"cannot transition to {new_state.value}"
        )

    # Case 3: forward-reachable transition.
    if new_state in REACHABLE.get(mirror.state, set()):
        mirror.state = new_state
        mirror.payload_hash = new_hash if new_state in TERMINAL else mirror.payload_hash
        mirror.last_transition_at = ts
        mirror.history.append(("transition", new_state, ts))
        return mirror

    # Case 4: backward/skip transition — legal only if timestamp precedes the
    # mirror's last transition (reordering artifact).
    if ts < mirror.last_transition_at:
        mirror.history.append(("reordered", new_state, ts))
        return mirror

    raise IllegalStateTransition(
        f"task {mirror.task_id}: state {mirror.state.value} -> "
        f"{new_state.value} is not reachable in A2A v1.0 transition table "
        f"(timestamp {ts} >= last {mirror.last_transition_at})"
    )
