# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-signed-agentcard-after-a-peer-s-capability-manifest-is-re-signed-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-signed-agentcard-after-a-peer-s-capability-manifest-is-re-signed-mid-task.warrant.json
# Markdown SHA-256:   ab5fdc89a043058bb60af7abc26a7aee47924287f68e2ba10828c746100aa170
# Code AST SHA-256:   8ddf24b1871548b7993064bc3a359601cab1182bd72fa1b03abff34aa42e8790
# Verified Classes:   ManifestCurrencyError, TaskState, AgentCard, CachedCard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ManifestCurrencyError(RuntimeError):
    """Raised when a cached AgentCard no longer describes the peer's live manifest."""


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


@dataclass
class AgentCard:
    agent_id: str
    signature_valid: bool
    expires_at: float                      # epoch seconds; 0 == no expiry published
    streaming: bool
    skills: frozenset[str]
    manifest_version: int = 0              # monotonic if peer publishes one


@dataclass
class CachedCard:
    card: AgentCard
    fetched_at: float = field(default_factory=time.time)

    def is_expired(self, max_age: float) -> bool:
        if self.card.expires_at and time.time() >= self.card.expires_at:
            return True
        return (time.time() - self.fetched_at) > max_age


def assert_card_admissible_for_transition(
    cached: CachedCard,
    observed_state: TaskState,
    observed_streaming: bool,
    max_age: float,
) -> None:
    """
    Gate the next tasks/send on both cryptographic trust AND manifest currency.
    Signature validity is necessary but not sufficient.
    """
    if not cached.card.signature_valid:
        raise ManifestCurrencyError(
            f"AgentCard for {cached.card.agent_id} failed signature verification; "
            "refusing to issue tasks/send."
        )

    if cached.is_expired(max_age):
        raise ManifestCurrencyError(
            f"AgentCard for {cached.card.agent_id} is expired or older than "
            f"max_age={max_age}s; re-discover before proceeding."
        )

    # Contradiction check: the observed lifecycle transition must be producible
    # by the capabilities the cached card asserts.
    if observed_streaming and not cached.card.streaming:
        raise ManifestCurrencyError(
            f"Observed streaming update from {cached.card.agent_id} but cached card "
            "declares capabilities.streaming=false; manifest is stale."
        )

    if observed_state is TaskState.FAILED:
        # A terminal failure referencing an unsupported skill is a currency signal,
        # not a transient error — do not blindly retry against the same card.
        raise ManifestCurrencyError(
            f"Peer {cached.card.agent_id} entered FAILED under a lifecycle transition "
            "the cached manifest cannot explain; re-fetch and re-verify AgentCard."
        )


def issue_task(cached: CachedCard, required_skill: str, max_age: float) -> None:
    if required_skill not in cached.card.skills:
        raise ManifestCurrencyError(
            f"Skill {required_skill!r} absent from cached manifest for "
            f"{cached.card.agent_id}; cached card is stale relative to live peer."
        )
    # ... proceed with tasks/send only after the admissibility gate passes ...
