# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-signed-a2a-agent-card-whose-signature-verifies-but-whose-capability-manifest-was-re-scoped-between-dis.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-signed-a2a-agent-card-whose-signature-verifies-but-whose-capability-manifest-was-re-scoped-between-dis.warrant.json
# Markdown SHA-256:   61f9a30dd6903a299a0e8407114bb45b114c6687d8398d215de33b4ba65b5178
# Code AST SHA-256:   5bcd5870c8e77688a8836095b2bee8bacc7cc7ccd43ce84259e946dcf51d7aad
# Verified Classes:   StaleManifestError, UnwarrantedCapabilityError, CachedCard, FreshCard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class StaleManifestError(RuntimeError):
    """Raised when a cached signed Agent Card no longer binds to the
    manifest the remote endpoint will honor at dispatch time."""


class UnwarrantedCapabilityError(RuntimeError):
    """Raised when a capability is declared in a fresh card but has not
    yet been observed as warranted by the peer's authorization plane."""


@dataclass(frozen=True)
class CachedCard:
    manifest_hash: str          # sha256 of canonical card JSON at discovery
    skill_versions: dict        # skill_id -> skillVersion
    security_schemes: dict      # scheme_name -> set of scopes
    discovered_at: float        # monotonic seconds
    signature_verified: bool


@dataclass(frozen=True)
class FreshCard:
    manifest_hash: str
    skill_versions: dict
    security_schemes: dict
    served_at: float


def canonical_hash(card_json: dict) -> str:
    blob = json.dumps(card_json, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def assert_dispatch_admissible(
    cached: CachedCard,
    fresh: FreshCard,
    skill_id: str,
    credential_scopes: set,
    propagation_window_s: float = 30.0,
    now: float = 0.0,
) -> None:
    """Enforce the triple-bind invariant before dispatching a task.

    Signature validity is assumed checked at discovery; this gate covers
    freshness and authorization continuity, which signatures do not cover.
    """
    if not cached.signature_verified:
        raise StaleManifestError("cached card was never signature-verified")

    # (a) manifest identity must bind
    if cached.manifest_hash != fresh.manifest_hash:
        raise StaleManifestError(
            f"manifest moved: cached={cached.manifest_hash[:12]} "
            f"fresh={fresh.manifest_hash[:12]}; re-discover, do not merge"
        )

    # (b) skill version must bind for the specific skill invoked
    cached_v = cached.skill_versions.get(skill_id)
    fresh_v = fresh.skill_versions.get(skill_id)
    if cached_v is None:
        raise StaleManifestError(f"skill {skill_id} absent from cached card")
    if fresh_v is None:
        raise StaleManifestError(
            f"skill {skill_id} withdrawn by peer; do not dispatch"
        )
    if cached_v != fresh_v:
        raise StaleManifestError(
            f"skill {skill_id} version drift: cached={cached_v} fresh={fresh_v}"
        )

    # (c) credential scope must be present in the fresh card's schemes
    fresh_scopes = set()
    for scopes in fresh.security_schemes.values():
        fresh_scopes |= scopes
    over_scoped = credential_scopes - fresh_scopes
    if over_scoped:
        raise StaleManifestError(
            f"credential carries scopes withdrawn from manifest: {over_scoped}"
        )

    # (d) propagation window: a skill that appeared only in the fresh card
    # has not yet been observed as warranted by the peer's PDP.
    if skill_id not in cached.skill_versions and skill_id in fresh.skill_versions:
        age = now - fresh.served_at
        if age < propagation_window_s:
            raise UnwarrantedCapabilityError(
                f"skill {skill_id} declared {age:.1f}s ago; "
                f"warrant propagation window {propagation_window_s}s not elapsed"
            )
