# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-an-a2a-v1-0-agent-card-s-declared-task-lifecycle-against-a-peer-s-actual-state-machine-when-tasks-get-returns-a-termi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-an-a2a-v1-0-agent-card-s-declared-task-lifecycle-against-a-peer-s-actual-state-machine-when-tasks-get-returns-a-termi.warrant.json
# Markdown SHA-256:   75d3e425392d10190c31662b38ebf8680f4cbd33ead0fcbfe986398a95c5bfb0
# Code AST SHA-256:   99924716fba229daa0e3da695266a5fd7e2523e82f76e787a8cb874bebf46f80
# Verified Classes:   CardStateMachineConflict, AgentCard, TaskTracker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

# Maximal A2A v1.0 graph: every non-terminal state can reach every other.
A2A_STATES = {"submitted", "working", "input-required", "completed", "failed", "canceled"}
TERMINAL = {"completed", "failed", "canceled"}
MAXIMAL_EDGES = {(a, b) for a in A2A_STATES if a not in TERMINAL for b in A2A_STATES if b != a}


class CardStateMachineConflict(RuntimeError):
    """Raised when an observed transition is not in the client's derived graph
    and the card is too stale to be trusted as a witness."""


@dataclass
class AgentCard:
    fetched_at: float
    capabilities: dict
    skills: list


@dataclass
class TaskTracker:
    task_id: str
    last_state: str
    graph_source: str  # "observed" | "maximal" | "derived"
    derived_edges: set = field(default_factory=set)
    card: Optional[AgentCard] = None

    def observe(self, new_state: str, now: float, max_task_lifetime: float) -> str:
        if new_state not in A2A_STATES:
            raise CardStateMachineConflict(f"unknown state {new_state!r} for task {self.task_id}")

        edge = (self.last_state, new_state)
        if self.graph_source == "maximal" or edge in self.derived_edges:
            self.last_state = new_state
            return new_state

        # Out-of-graph transition. Decide by card freshness, not by the edge.
        card_age = now - self.card.fetched_at if self.card else float("inf")
        if card_age <= max_task_lifetime:
            if self.card.capabilities.get("stateTransitionHistory"):
                # Peer can witness itself; fetch history and rebuild graph.
                self.graph_source = "observed"
                self.last_state = new_state
                return new_state
            # Fresh card, no history: peer is non-conformant. Orphan, do not fail.
            self.last_state = "orphaned"
            return "orphaned"

        # Stale card: re-discovery is mandatory before any further action.
        raise CardStateMachineConflict(
            f"task {self.task_id}: {self.last_state} -> {new_state} out of graph; "
            f"card age {card_age:.1f}s > {max_task_lifetime:.1f}s; re-discover before proceeding"
        )

    def send_or_cancel(self, new_state: str, now: float, max_task_lifetime: float) -> str:
        # Guardrail: no outbound action against a stale-card, out-of-graph task.
        if self.last_state == "orphaned":
            raise CardStateMachineConflict(
                f"task {self.task_id} orphaned; re-discovery required before send/cancel"
            )
        return self.observe(new_state, now, max_task_lifetime)
