# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-divergent-agent-card-skills-before-a2a-task-submission-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-divergent-agent-card-skills-before-a2a-task-submission-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   1090179d3077a350475b363d9f47ddf6a7fb7ceb96c7aa4d819c408b0a065c53
# Code AST SHA-256:   1faa4fa5f3e5bdd3af121455a71933456473ac24d120e606e0dff64810072418
# Verified Classes:   A2ACardContractError, CardSnapshot, TaskHandle
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Any, Mapping, Optional


class A2ACardContractError(RuntimeError):
    """Raised when a submitted task violates the declared-vs-live capability invariant."""


@dataclass(frozen=True)
class CardSnapshot:
    agent_url: str
    agent_version: str
    etag: str
    fetched_at: float
    skills: Mapping[str, Mapping[str, Any]]  # skill_id -> declared schema
    capabilities: Mapping[str, bool]


@dataclass
class TaskHandle:
    task_id: str
    skill_id: str
    submitted_at: float
    dispatched: bool = False
    terminal: bool = False


# Maximum age the client will trust a cached card before forcing a re-fetch.
CARD_TRUST_WINDOW_S = 30.0


def submit_task(
    card: CardSnapshot,
    handle: TaskHandle,
    request_payload: Mapping[str, Any],
    now: Optional[float] = None,
) -> TaskHandle:
    now = time.time() if now is None else now

    # Invariant 1: card must be within the trust window, else the client
    # cannot assert declared ⊆ live and must re-fetch before submitting.
    if now - card.fetched_at > CARD_TRUST_WINDOW_S:
        raise A2ACardContractError(
            f"card for {card.agent_url}@{card.agent_version} is "
            f"{now - card.fetched_at:.1f}s old; re-fetch and diff before submit"
        )

    # Invariant 2: the submitted skill must exist in the declared card.
    if handle.skill_id not in card.skills:
        raise A2ACardContractError(
            f"skill {handle.skill_id!r} not declared by "
            f"{card.agent_url}@{card.agent_version}"
        )

    # Invariant 3: request payload must validate against the declared
    # input schema; a missing field here is the Trace-2 silent-coercion path.
    declared = card.skills[handle.skill_id]
    required = set(declared.get("required", ()))
    missing = required - set(request_payload.keys())
    if missing:
        raise A2ACardContractError(
            f"payload for skill {handle.skill_id!r} missing required "
            f"fields {sorted(missing)}; server will coerce silently"
        )

    # Invariant 4: streaming must be probed empirically, not trusted from
    # the card. If the card says streaming and we intend to subscribe, the
    # caller must have already recorded a successful probe for this version.
    if card.capabilities.get("streaming") and not card.capabilities.get(
        "streaming_probed", False
    ):
        raise A2ACardContractError(
            f"streaming advertised but not probed for "
            f"{card.agent_url}@{card.agent_version}; refusing sendSubscribe"
        )

    handle.dispatched = False
    handle.terminal = False
    return handle


def on_task_update(handle: TaskHandle, status_state: str) -> TaskHandle:
    # The 200 OK / submitted transition is acceptance, not dispatch.
    if status_state == "working":
        if not handle.dispatched:
            # First working event is the dispatch acknowledgment.
            handle.dispatched = True
        return handle

    if status_state in ("completed", "failed", "canceled"):
        if status_state == "completed" and not handle.dispatched:
            raise A2ACardContractError(
                f"task {handle.task_id} reported completed without a "
                f"dispatch acknowledgment; state machine is inconsistent"
            )
        handle.terminal = True
        return handle

    return handle


def validate_completion(
    card: CardSnapshot, handle: TaskHandle, payload: Mapping[str, Any]
) -> None:
    # Invariant 5: completed is provisional until output schema validates.
    declared = card.skills[handle.skill_id]
    required_out = set(declared.get("output_required", ()))
    missing = required_out - set(payload.keys())
    if missing:
        raise A2ACardContractError(
            f"task {handle.task_id} completed but payload for skill "
            f"{handle.skill_id!r} missing {sorted(missing)}; "
            f"treating as contract violation, not success"
        )
