# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-agent-card-s-declared-capabilities-as-advisory-rather-than-binding-at-delegation-time.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-agent-card-s-declared-capabilities-as-advisory-rather-than-binding-at-delegation-time.warrant.json
# Markdown SHA-256:   ddd5f0b8e37919bf1c9d51e42d9fad8e826065a0f210a1fb184ed99a45b89e61
# Code AST SHA-256:   6f4696fabe8993fb2812e1d2673d8ba08b5d4e79cec303a03d66f45316c75283
# Verified Classes:   CardDivergenceError, CardConfidence, AgentCard, DelegationState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class CardDivergenceError(RuntimeError):
    """Raised when a card-consistent payload fails at the runtime,
    proving the manifest and the handler have diverged."""
    pass


class CardConfidence(Enum):
    TRUSTED = "trusted"
    SUSPECT = "suspect"
    DIVERGED = "diverged"


@dataclass
class AgentCard:
    version: str
    skills: dict  # skill_id -> {"inputModes": [...], "outputModes": [...]}
    capabilities: dict
    manifest_hash: str

    @staticmethod
    def hash_manifest(raw: bytes) -> str:
        return hashlib.sha256(raw).hexdigest()


@dataclass
class DelegationState:
    card: AgentCard
    confidence: CardConfidence = CardConfidence.TRUSTED
    last_refresh: float = field(default_factory=time.time)
    ttl_seconds: int = 3600


def delegate_task(
    state: DelegationState,
    skill_id: str,
    parts: list,
    fetch_card,
    send_rpc,
) -> dict:
    """Dispatch a task, treating the card as advisory.

    On a card-consistent -32603, force a re-fetch before any retry.
    On a -32602, the card is confirmed divergent for this skill.
    """
    card = state.card
    skill = card.skills.get(skill_id)
    if skill is None:
        raise CardDivergenceError(
            f"skill {skill_id!r} absent from card {card.manifest_hash[:8]}"
        )

    # Construct from the card, but do not locally reject on mode mismatch.
    request = {"skill": skill_id, "parts": parts}
    response = send_rpc(request)

    if response.get("error", {}).get("code") == -32602:
        # Remote says our payload violated its contract. Refresh and compare.
        state.confidence = CardConfidence.DIVERGED
        fresh = fetch_card(no_cache=True)
        if fresh.manifest_hash == card.manifest_hash:
            raise CardDivergenceError(
                f"card {card.manifest_hash[:8]} still advertises "
                f"{skill['inputModes']} but remote rejected payload; "
                f"skill {skill_id!r} is unusable, failing closed"
            )
        state.card = fresh
        state.confidence = CardConfidence.TRUSTED
        raise CardDivergenceError(
            f"card refreshed {card.manifest_hash[:8]} -> "
            f"{fresh.manifest_hash[:8]}; re-derive payload before retry"
        )

    if response.get("error", {}).get("code") == -32603:
        # Card-consistent internal error: the specific divergence signature.
        if state.confidence is CardConfidence.SUSPECT:
            raise CardDivergenceError(
                f"second card-consistent -32603 on {card.manifest_hash[:8]}; "
                f"runtime diverged from manifest, refusing to retry"
            )
        state.confidence = CardConfidence.SUSPECT
        fresh = fetch_card(no_cache=True)
        if fresh.manifest_hash == card.manifest_hash:
            raise CardDivergenceError(
                f"re-fetched card identical ({card.manifest_hash[:8]}) but "
                f"handler failed on card-consistent payload; "
                f"divergence is in runtime, not manifest"
            )
        state.card = fresh
        state.confidence = CardConfidence.TRUSTED
        raise CardDivergenceError(
            f"card changed under us {card.manifest_hash[:8]} -> "
            f"{fresh.manifest_hash[:8]}; re-derive and retry once"
        )

    if response.get("error", {}).get("code") == 406:
        # Capability advertised but transport refused. Downgrade for session.
        state.card.capabilities["streaming"] = False
        return {"downgraded": "streaming", "response": response}

    return response
