# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-agent-card-as-a-versioned-capability-lease-rather-than-a-static-manifest-when-peer-runtimes-mutate-their-advertise.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-agent-card-as-a-versioned-capability-lease-rather-than-a-static-manifest-when-peer-runtimes-mutate-their-advertise.warrant.json
# Markdown SHA-256:   bc69bb6f76d0a5b555433795c40e20cfd15322bbb4d27e34dd18751436a16ea4
# Code AST SHA-256:   d201d06a2bf3f82f225a6bc673b3b836b1084cb22f031c91190fc3240924626e
# Verified Classes:   CardLeaseViolation, CardLease
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class CardLeaseViolation(RuntimeError):
    """Raised when a task artifact was emitted under a card version
    different from the one pinned at dispatch, with no recoverable echo."""
    pass


@dataclass(frozen=True)
class CardLease:
    version: str
    skill_id: str
    skill_fingerprint: str  # sha256 of the skill sub-object at discovery

    @classmethod
    def from_card(cls, card: dict[str, Any], skill_id: str) -> "CardLease":
        skill = next((s for s in card.get("skills", []) if s.get("id") == skill_id), None)
        if skill is None:
            raise CardLeaseViolation(f"skill {skill_id} not present in card {card.get('version')}")
        fp = hashlib.sha256(
            json.dumps(skill, sort_keys=True).encode()
        ).hexdigest()
        return cls(version=card["version"], skill_id=skill_id, skill_fingerprint=fp)


def dispatch_with_pin(lease: CardLease, params: dict[str, Any]) -> dict[str, Any]:
    """Build task metadata that pins the card lease for the peer to echo."""
    return {
        "skill": lease.skill_id,
        "params": params,
        "metadata": {
            "pinned_card_version": lease.version,
            "pinned_skill_fingerprint": lease.skill_fingerprint,
        },
    }


def validate_artifact(lease: CardLease, task_status: dict[str, Any],
                      artifact: dict[str, Any]) -> None:
    """Enforce the invariant: emitted artifact must be attributable to the
    pinned lease. Raises if the peer drifted mid-task without echo."""
    echoed_version = task_status.get("metadata", {}).get("executed_card_version")
    echoed_fp = task_status.get("metadata", {}).get("executed_skill_fingerprint")

    if echoed_version is None or echoed_fp is None:
        # Peer cannot pin; result is unattributable. Refuse to commit.
        raise CardLeaseViolation(
            f"peer did not echo card version for skill {lease.skill_id}; "
            f"artifact cannot be attributed to pinned lease {lease.version}"
        )

    if echoed_version != lease.version or echoed_fp != lease.skill_fingerprint:
        # Mid-task card mutation detected. Artifact is provisional.
        raise CardLeaseViolation(
            f"card drift during task: pinned {lease.version}/{lease.skill_fingerprint[:8]}, "
            f"executed {echoed_version}/{echoed_fp[:8]} for skill {lease.skill_id}"
        )
