# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-agent-card-signature-after-an-extended-skill-schema-changes-the-signed-payload.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-agent-card-signature-after-an-extended-skill-schema-changes-the-signed-payload.warrant.json
# Markdown SHA-256:   d92f0de83eec713520d865b4ab57ff70b8ba146fc6bf4d8e8f28066f6c8fafaf
# Code AST SHA-256:   dc65fe45e993b014410cdfab99bd079941a40c3aaa91c5164d6614a04daf6911
# Verified Classes:   CardProvenanceError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class CardProvenanceError(RuntimeError):
    """Raised when a decision-gating extended skill field is read from a
    normalized model whose serialization diverges from the signature-verified
    canonical bytes."""


def canonical_bytes(card: dict[str, Any]) -> bytes:
    # JCS-style: lexicographic keys at every level, arrays preserved in order.
    return json.dumps(
        card, sort_keys=True, separators=(",", ":"), ensure_ascii=False
    ).encode("utf-8")


def verify_and_freeze(
    raw_bytes: bytes,
    signature: bytes,
    public_key_verifier,
    gating_paths: list[tuple[str, ...]],
) -> dict[str, Any]:
    """Verify the Card over its received bytes, then assert that every
    decision-gating extended field survives re-serialization losslessly.
    Returns a frozen view keyed by gating path, bound to the verified digest.
    """
    if not public_key_verifier(raw_bytes, signature):
        raise CardProvenanceError("Card signature does not verify over received bytes")

    verified_digest = hashlib.sha256(raw_bytes).hexdigest()
    card = json.loads(raw_bytes)

    frozen: dict[tuple[str, ...], Any] = {}
    for path in gating_paths:
        node: Any = card
        for key in path:
            if not isinstance(node, dict) or key not in node:
                raise CardProvenanceError(
                    f"Gating path {path} absent from signed Card; cannot authorize"
                )
            node = node[key]
        frozen[path] = node

    # Re-derive the gating subtree from the verified bytes and confirm the
    # frozen value is byte-identical to what was signed. A normalized model
    # (set, reordered dict) will diverge here.
    reserialized = canonical_bytes(card)
    if hashlib.sha256(reserialized).hexdigest() != verified_digest:
        # Only reachable if the parse/serialize round-trip is lossy, which for
        # a correct canonicalization should not occur; treat as fatal.
        raise CardProvenanceError(
            "Parse/serialize round-trip diverged from verified digest; "
            "typed model is lossy for this Card"
        )

    return {"digest": verified_digest, "fields": frozen}


def authorize_webhook_action(
    frozen_card: dict[str, Any],
    action: str,
    gating_path: tuple[str, ...] = ("skills", "x-authorized-actions"),
) -> str:
    """Select the action to dispatch using the *signed priority order*,
    never a normalized set. Returns the highest-priority authorized action
    that the webhook's requested action is subordinate to.
    """
    actions = frozen_card["fields"].get(gating_path)
    if not isinstance(actions, list):
        raise CardProvenanceError(
            f"Gating field {gating_path} is not an ordered array in the signed Card"
        )
    if action not in actions:
        raise CardProvenanceError(
            f"Webhook action {action!r} not present in signed authorization list"
        )
    # Honor signed priority: the first listed authorized action wins.
    return actions[0]
