# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-an-agent-card-from-a-stale-cache-across-an-a2a-runtime-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-an-agent-card-from-a-stale-cache-across-an-a2a-runtime-boundary.warrant.json
# Markdown SHA-256:   70fd86ed6736261667d2f56932da75e6f493fa6a325722606599a8d4bf202464
# Code AST SHA-256:   b57ae315f0d1e951c30773ed4c65c08a58d0e8fc53423b7f1d1eda73e8767f41
# Verified Classes:   StaleAgentCardError, AgentCard, TaskResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleAgentCardError(RuntimeError):
    """Raised when a task's required skills are not covered by a freshly
    resolved Agent Card, or when the completed task lacks artifacts for a
    required skill. This is the guard against silent capability downgrade
    across an A2A runtime boundary."""
    pass


@dataclass
class AgentCard:
    url: str
    protocol_version: str
    skills: set
    fetched_at: float  # monotonic seconds


@dataclass
class TaskResult:
    task_id: str
    state: str                 # "submitted" | "working" | "completed" | "failed"
    artifacts_by_skill: dict = field(default_factory=dict)
    error_code: Optional[int] = None


def resolve_card_fresh(fetch_card, url: str, max_age_s: float, now: float) -> AgentCard:
    card = fetch_card(url)  # always refetch on submit across heterogeneous peers
    if now - card.fetched_at > max_age_s:
        raise StaleAgentCardError(
            f"card for {url} is {now - card.fetched_at:.1f}s old, exceeds {max_age_s}s"
        )
    return card


def delegate_and_verify(
    fetch_card,
    send_task,
    get_task,
    peer_url: str,
    required_skills: set,
    payload: dict,
    now: float,
    max_card_age_s: float = 30.0,
) -> TaskResult:
    # 1. Refetch-on-submit: never trust a cached card across the boundary.
    card = resolve_card_fresh(fetch_card, peer_url, max_card_age_s, now)

    # 2. Pre-submit capability check against the LIVE card.
    missing = required_skills - card.skills
    if missing:
        raise StaleAgentCardError(
            f"peer {peer_url} no longer advertises required skills {sorted(missing)}; "
            f"live card skills={sorted(card.skills)}. Aborting before task submission."
        )

    # 3. Submit and drive the lifecycle.
    task = send_task(peer_url, payload)
    while task.state in ("submitted", "working"):
        task = get_task(peer_url, task.task_id)

    if task.state == "failed":
        # JSON-RPC -32602 = invalid params, i.e. schema negotiation mismatch.
        if task.error_code == -32602:
            raise StaleAgentCardError(
                f"peer rejected params (schema drift) on task {task.task_id}; "
                f"card advertised protocol {card.protocol_version} but handler schema differs."
            )
        return task

    # 4. Post-completion completeness check: peer's "completed" is not our predicate.
    for skill in required_skills:
        if skill not in task.artifacts_by_skill:
            raise StaleAgentCardError(
                f"task {task.task_id} reached 'completed' but produced no artifact for "
                f"required skill '{skill}'. Silent capability downgrade detected."
            )
    return task
