# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-discovered-a2a-agent-card-as-stale-rather-than-authoritative-at-negotiation-time.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-discovered-a2a-agent-card-as-stale-rather-than-authoritative-at-negotiation-time.warrant.json
# Markdown SHA-256:   0e014605c32a05965d2225347952c64829be70221c95fd42f5bfa8eb3650666e
# Code AST SHA-256:   4dec36ba936fc7b1ef26ea72b0017140dc235b44bd176fc0185f0c70830ef367
# Verified Classes:   StaleAgentCardError, AgentCard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleAgentCardError(RuntimeError):
    """Raised when a discovered A2A card cannot be promoted to commitment authority."""
    pass


@dataclass(frozen=True)
class AgentCard:
    peer_id: str
    card_version: int
    issued_at: float          # unix seconds, peer-signed
    valid_until: float        # unix seconds, peer-signed; NOT registry TTL
    skills: dict              # skill_name -> schema_hash
    signature_verified: bool


def promote_to_commitment_authority(
    card: AgentCard,
    peer_revocation_index_version: int,
    required_skill: str,
    required_schema_hash: str,
    now: float | None = None,
) -> AgentCard:
    """
    Promote a routing-tier card to commitment-tier authority, or raise.

    Authority requires: verified signature, peer-signed freshness window open,
    card_version not behind the peer's revocation index, and the required
    skill present with a matching schema hash.
    """
    now = time.time() if now is None else now

    if not card.signature_verified:
        raise StaleAgentCardError(
            f"peer={card.peer_id}: signature unverified; card is a hint only"
        )

    if now > card.valid_until:
        raise StaleAgentCardError(
            f"peer={card.peer_id}: peer-signed valid_until={card.valid_until} "
            f"passed at now={now}; registry TTL is not a freshness bound"
        )

    if card.card_version < peer_revocation_index_version:
        raise StaleAgentCardError(
            f"peer={card.peer_id}: card_version={card.card_version} behind "
            f"peer revocation index={peer_revocation_index_version}"
        )

    held_hash = card.skills.get(required_skill)
    if held_hash is None:
        raise StaleAgentCardError(
            f"peer={card.peer_id}: required skill={required_skill!r} absent "
            f"from card v{card.card_version}"
        )

    if held_hash != required_schema_hash:
        raise StaleAgentCardError(
            f"peer={card.peer_id}: skill={required_skill!r} schema hash "
            f"{held_hash} != required {required_schema_hash}; "
            f"same skill name, different capability"
        )

    return card


def schema_hash(schema: dict) -> str:
    """Stable hash over a capability schema; the unit of capability identity."""
    canonical = repr(sorted(schema.items()))
    return hashlib.sha256(canonical.encode()).hexdigest()[:16]
