# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-signed-agent-card-advertises-an-extended-skill-schema-that-its-live-task-executor-cannot-honor-at-push-notification-ti.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-signed-agent-card-advertises-an-extended-skill-schema-that-its-live-task-executor-cannot-honor-at-push-notification-ti.warrant.json
# Markdown SHA-256:   45eb0e744a18b4a3a67a5594c7f5b7e52b2f3db2c1405c7225a91d3cc3c017e2
# Code AST SHA-256:   c84abce9ac0110836ec1e74ea1abd31ad3b0dd6f7987fc3b5a1056dd028369c6
# Verified Classes:   CardWarrantDriftError, SignedAgentCard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CardWarrantDriftError(RuntimeError):
    """Raised when a webhook event's schema does not match the attested Agent Card warrant."""
    pass


@dataclass
class SignedAgentCard:
    raw: dict
    jws: str
    digest: str  # sha256 over canonical JSON of raw

    @classmethod
    def from_bytes(cls, raw: dict, jws: str) -> "SignedAgentCard":
        canonical = json.dumps(raw, sort_keys=True, separators=(",", ":")).encode()
        return cls(raw=raw, jws=jws, digest=hashlib.sha256(canonical).hexdigest())


def verify_webhook_event_against_card(
    event: dict,
    card: SignedAgentCard,
    *,
    strict: bool = True,
) -> None:
    """
    Validate a TaskStatusUpdateEvent against the signed card's extended skill schema.

    Invariant enforced: the event must carry the cardDigest of the card the client
    currently trusts. If the digest differs, the executor has re-signed (drifted)
    and the client must re-fetch before trusting the payload shape.
    """
    event_digest = event.get("cardDigest")
    if event_digest is None:
        if strict:
            raise CardWarrantDriftError(
                "webhook event lacks cardDigest; cannot bind payload to signed warrant"
            )
        return

    if event_digest != card.digest:
        raise CardWarrantDriftError(
            f"event attested to card {event_digest[:12]} but client trusts {card.digest[:12]}; "
            "executor drifted from signed manifest — re-fetch and re-verify card before deserializing"
        )

    # Only now is the extended schema a valid deserialization contract.
    skill_id = event.get("skillId")
    skill = next((s for s in card.raw.get("skills", []) if s.get("id") == skill_id), None)
    if skill is None:
        raise CardWarrantDriftError(f"event references unknown skill {skill_id!r}")

    contract = skill.get("x-param-contract", {})
    result = event.get("result") or {}
    for field, spec in contract.items():
        if spec.get("required") and field not in result:
            raise CardWarrantDriftError(
                f"completed event for {skill_id!r} missing required field {field!r} "
                f"attested by signed card {card.digest[:12]}"
            )
        if "enum" in spec and field in result and result[field] not in spec["enum"]:
            raise CardWarrantDriftError(
                f"field {field!r}={result[field]!r} violates attested enum {spec['enum']}"
            )
