# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-agent-card-capability-negotiation-as-a-monotonic-commitment-rather-than-a-re-queryable-hint.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-agent-card-capability-negotiation-as-a-monotonic-commitment-rather-than-a-re-queryable-hint.warrant.json
# Markdown SHA-256:   e71bb5871d9b2035275dfbaece5aed6fdac3c4f516ba6a2e2a28f57af2f0366d
# Code AST SHA-256:   888b250ac7609a3f8f622deb8291850e2f812b0bdcbffaff52055102786bf20e
# Verified Classes:   NegotiationDriftError, TaskState, Task
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class NegotiationDriftError(RuntimeError):
    """Raised when a re-fetched Agent Card is used to mutate an in-flight task's contract."""
    pass


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


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


def capability_epoch(card: dict) -> str:
    """Seal the negotiated capability subset into an epoch stamp at dispatch."""
    subset = {
        "skills": sorted(card.get("skills", [])),
        "inputModes": sorted(card.get("capabilities", {}).get("inputModes", [])),
        "outputModes": sorted(card.get("capabilities", {}).get("outputModes", [])),
    }
    blob = json.dumps(subset, sort_keys=True).encode()
    return hashlib.sha256(blob).hexdigest()[:16]


@dataclass
class Task:
    id: str
    state: TaskState
    epoch: str
    consumed_input_under_epoch: bool = False


def reconcile_card_refetch(task: Task, fresh_card: dict) -> Optional[str]:
    """
    Decide what a mid-task Card re-fetch is allowed to mean.
    Returns an action hint, or raises if the caller attempts an illegal transition.
    """
    fresh_epoch = capability_epoch(fresh_card)

    if task.state in TERMINAL:
        return "ignore: task already terminal; card is informational"

    if fresh_epoch == task.epoch:
        return "no-op: capability set unchanged"

    # Card drifted after negotiation. The epoch is sealed; drift is not a violation.
    if task.state in {TaskState.WORKING, TaskState.INPUT_REQUIRED} and \
            task.consumed_input_under_epoch:
        # Must NOT synthesize a terminal state from this discrepancy.
        return "record-drift: resume under sealed epoch; defer to remote terminal state"

    if task.state == TaskState.SUBMITTED:
        # Nothing consumed yet: legal to re-dispatch with a fresh epoch.
        return "re-dispatch: cancel and renegotiate with new epoch"

    # Any attempt to fail/cancel an in-flight task purely on Card drift is illegal.
    raise NegotiationDriftError(
        f"task {task.id} in state {task.state.value} attempted terminal transition "
        f"from card drift {task.epoch} -> {fresh_epoch}; "
        f"terminal state must come from remote Task or explicit confirmed cancel"
    )


def apply_refetch(task: Task, fresh_card: dict, want_terminal_from_drift: bool) -> str:
    action = reconcile_card_refetch(task, fresh_card)
    if want_terminal_from_drift and task.state not in TERMINAL:
        raise NegotiationDriftError(
            f"refusing to terminate task {task.id} on capability drift alone"
        )
    return action
