# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a2a-v1-0-agent-card-skills-id-drift-against-a-peer-s-post-handoff-task-state-vocabulary-and-what-breaks-when-it-doesn.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a2a-v1-0-agent-card-skills-id-drift-against-a-peer-s-post-handoff-task-state-vocabulary-and-what-breaks-when-it-doesn.warrant.json
# Markdown SHA-256:   901552599afd27dd967655c1332eb5cbdbbec86cfb5d078ed6cac155273f7016
# Code AST SHA-256:   149fc3f2e1a769b918829673616846ef37dbee3bfdb3278e43a91121624cc67b
# Verified Classes:   LifecycleReconciliationError, AgentCard, TaskObservation, PeerLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field


class LifecycleReconciliationError(RuntimeError):
    """Raised when an A2A peer's observed TaskState vocabulary or skill-id
    namespace diverges from the card used to route the task, and the
    divergence cannot be safely absorbed by the default branch."""


@dataclass
class AgentCard:
    skills: dict[str, str]          # skillId -> description
    content_hash: str = ""

    def __post_init__(self) -> None:
        payload = "|".join(sorted(self.skills))
        self.content_hash = hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class TaskObservation:
    task_id: str
    state: str                       # observed TaskState token
    skill_id: str


@dataclass
class PeerLedger:
    card: AgentCard
    observed_states: dict[tuple[str, str], set[str]] = field(default_factory=dict)

    def record(self, obs: TaskObservation) -> None:
        key = (self.card.content_hash, obs.skill_id)
        self.observed_states.setdefault(key, set()).add(obs.state)


KNOWN_STATES = {"submitted", "working", "input-required", "completed", "canceled", "failed", "unknown"}
BLOCKING_STATES = {"input-required"}
TERMINAL_STATES = {"completed", "canceled", "failed"}


def reconcile_first_response(
    ledger: PeerLedger,
    obs: TaskObservation,
    has_continuation_path: bool,
) -> str:
    """Return the action the orchestrator must take for the first Task
    response of a freshly issued task. Raises if the invariant cannot hold."""
    if obs.skill_id not in ledger.card.skills:
        raise LifecycleReconciliationError(
            f"skill {obs.skill_id!r} not present in cached card "
            f"(hash={ledger.card.content_hash[:12]}); card is stale, re-fetch before routing"
        )

    if obs.state not in KNOWN_STATES:
        raise LifecycleReconciliationError(
            f"peer emitted unenumerated TaskState {obs.state!r} for {obs.skill_id!r}; "
            "no default branch may silently treat this as completion"
        )

    ledger.record(obs)

    if obs.state in BLOCKING_STATES:
        if not has_continuation_path:
            raise LifecycleReconciliationError(
                f"task {obs.task_id!r} entered {obs.state!r} but orchestrator has no "
                "same-taskId continuation path; must fail explicitly, not hold subscription"
            )
        return "continue_same_task"

    if obs.state in TERMINAL_STATES:
        return "terminal"

    return "await_events"


def handle_task_not_found(ledger: PeerLedger, fresh_card: AgentCard, skill_id: str) -> str:
    """Reconcile TaskNotFoundError against a freshly re-fetched card."""
    if fresh_card.content_hash != ledger.card.content_hash:
        raise LifecycleReconciliationError(
            f"peer redeployed mid-task: skill-id namespace hash changed "
            f"({ledger.card.content_hash[:12]} -> {fresh_card.content_hash[:12]}); "
            "abort and re-plan, do not retry with stale skillId"
        )
    if skill_id not in fresh_card.skills:
        raise LifecycleReconciliationError(
            f"skill {skill_id!r} vanished from unchanged card; peer state is inconsistent"
        )
    return "terminal_unknown"
