# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-agent-card-as-a-stale-capability-claim-rather-than-a-live-contract-during-a2a-v1-0-cross-vendor.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-agent-card-as-a-stale-capability-claim-rather-than-a-live-contract-during-a2a-v1-0-cross-vendor.warrant.json
# Markdown SHA-256:   fa6cf9cb43254b2ce6f553ec633ecc82b6313fbe4bd3f33ccc90bdb987046626
# Code AST SHA-256:   fa370fe96c6ac6a9ca11e31f64eaa4a4c9c8d42bd4f8b04d15ff7230b85f3c33
# Verified Classes:   StaleAgentCardError, AgentCard, CachedCard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class StaleAgentCardError(RuntimeError):
    """Raised when a cached Agent Card no longer underwrites the delegation."""
    pass


@dataclass
class AgentCard:
    etag: str
    skills: dict          # skill_id -> {"canonical": str, "input_schema_hash": str}
    security_schemes: dict
    fetched_at: float


@dataclass
class CachedCard:
    card: AgentCard
    freshness_window_s: float = 900.0

    def is_fresh(self, now: float | None = None) -> bool:
        now = now if now is not None else time.time()
        return (now - self.card.fetched_at) < self.freshness_window_s


def confirm_delegation(
    cached: CachedCard,
    requested_skill_id: str,
    expected_schema_hash: str,
    expected_scheme: str,
    task_expected_duration_s: float,
    refetch,  # callable(etag) -> AgentCard | None (None means 304 Not Modified)
) -> AgentCard:
    """
    Enforce the A2A v1.0 reconfirmation invariant before tasks/send.
    Returns the card that is valid to delegate against, or raises.
    """
    now = time.time()
    card = cached.card

    # Boundary: task duration vs freshness window.
    if task_expected_duration_s >= cached.freshness_window_s or not cached.is_fresh(now):
        refreshed = refetch(card.etag)
        if refreshed is not None:
            card = refreshed
            cached.card = card
            cached.card.fetched_at = now
        else:
            cached.card.fetched_at = now  # 304: refresh freshness clock

    skill = card.skills.get(requested_skill_id)
    if skill is None:
        raise StaleAgentCardError(
            f"skill {requested_skill_id!r} absent from current card (etag={card.etag})"
        )

    # Canonical-id pinning: reject deprecated aliases that route to fallback executors.
    if skill["canonical"] != requested_skill_id:
        raise StaleAgentCardError(
            f"skill {requested_skill_id!r} is a deprecated alias for "
            f"{skill['canonical']!r}; refusing to delegate on a downgraded route"
        )

    if skill["input_schema_hash"] != expected_schema_hash:
        raise StaleAgentCardError(
            f"inputSchema for {requested_skill_id!r} changed "
            f"({expected_schema_hash} -> {skill['input_schema_hash']}); "
            "re-negotiate payload before submission"
        )

    if expected_scheme not in card.security_schemes:
        raise StaleAgentCardError(
            f"securityScheme {expected_scheme!r} no longer advertised; "
            "auth-scope may have rotated silently"
        )

    return card


def verify_artifact_against_card(
    card: AgentCard,
    skill_id: str,
    artifact_text: str,
    promised_output_budget: int,
) -> None:
    """Post-completion guard: a 'completed' state is not proof of contract adherence."""
    if len(artifact_text) >= promised_output_budget:
        # Truncation at the promised cap is a card-drift signal, not a success.
        raise StaleAgentCardError(
            f"artifact for {skill_id!r} hit {len(artifact_text)} chars against "
            f"promised budget {promised_output_budget}; peer may be serving a "
            "fallback executor behind the cached card"
        )
