# 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-task-ledger-and-a-peer-s-advertised-taskstate-when-a2a-v1-0-tasks-get-return.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-terminal-state-divergence-between-its-local-task-ledger-and-a-peer-s-advertised-taskstate-when-a2a-v1-0-tasks-get-return.warrant.json
# Markdown SHA-256:   d48fe80ee3762f474db58df37f13ea1cff7e6ad5b31c39ee4aadb491ef6a2422
# Code AST SHA-256:   9e305c08efd655ed621fe3ca3aa3135fb3198f4d602f0c44416fb88a0ad96d90
# Verified Classes:   CardTaskStateDivergence, AgentCard, TaskRecord, Orchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any, Optional


class CardTaskStateDivergence(RuntimeError):
    """Raised when a task's terminal state contradicts a cached card's capability gate
    in a way the orchestrator cannot resolve without a card re-fetch or planner escalation."""


@dataclass
class AgentCard:
    raw: dict
    version: str

    def content_hash(self) -> str:
        return hashlib.sha256(
            json.dumps(self.raw, sort_keys=True).encode()
        ).hexdigest()


@dataclass
class TaskRecord:
    task_id: str
    skill_id: str
    pinned_card_hash: str
    state: str
    clarification_schema: Optional[dict] = None
    clarification_cache_key: Optional[str] = None


@dataclass
class Orchestrator:
    card_cache: dict = field(default_factory=dict)          # skillId -> AgentCard
    clarification_cache: dict = field(default_factory=dict)  # cacheKey -> schema
    ledger: dict = field(default_factory=dict)               # taskId -> TaskRecord

    def _cache_key(self, skill_id: str, task_id: str) -> str:
        # Invariant: clarify schema is per-task, never per-skill.
        return f"{skill_id}::{task_id}"

    def on_input_required(
        self,
        task: TaskRecord,
        card: AgentCard,
        clarification: dict,
    ) -> dict:
        key = self._cache_key(task.skill_id, task.task_id)
        task.clarification_cache_key = key
        task.clarification_schema = clarification.get("schema")

        # A2A v1.0: card does not constrain clarification schema.
        # If the orchestrator has a memoized schema for this skill (not this task),
        # it MUST NOT compare. Detect the violation explicitly.
        skill_memo = self.clarification_cache.get(task.skill_id)
        if skill_memo is not None and skill_memo != task.clarification_schema:
            raise CardTaskStateDivergence(
                f"skill-scoped clarification memo for {task.skill_id!r} "
                f"diverges from task {task.task_id!r} clarification; "
                f"re-fetch card and escalate to planner, do not fail task"
            )

        self.clarification_cache[key] = task.clarification_schema
        return clarification

    def on_tasks_get(self, task: TaskRecord, card: AgentCard, response: dict) -> str:
        state = response["state"]
        if state in ("completed", "failed", "canceled"):
            # Terminal state wins for this taskId; card is NOT invalidated.
            task.state = state
            self.clarification_cache.pop(task.clarification_cache_key or "", None)
            return state

        if state == "input-required":
            # Card gate must still be satisfiable; if the pinned card hash
            # no longer matches the live card, force re-fetch before accepting.
            if card.content_hash() != task.pinned_card_hash:
                raise CardTaskStateDivergence(
                    f"task {task.task_id!r} still input-required but card hash "
                    f"drifted from {task.pinned_card_hash[:12]} to "
                    f"{card.content_hash()[:12]}; re-pin card before re-issuing"
                )
        return state
