# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-signed-agent-card-despite-a-valid-signature-the-manifest-canonicalization-and-skill-scope-diver.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-signed-agent-card-despite-a-valid-signature-the-manifest-canonicalization-and-skill-scope-diver.warrant.json
# Markdown SHA-256:   17b05225b8cc719695d4707ec2906f3205a004e2520ef275c66f269c1a30ef1a
# Code AST SHA-256:   119d1b415293faab49d8e9c7c7e5ef315c32c53d6153b19007a78f5e44ed1241
# Verified Classes:   ManifestAdmissionError, VerifiedCard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class ManifestAdmissionError(RuntimeError):
    """Raised when a signed Agent Card cannot be safely admitted for delegation."""


@dataclass(frozen=True)
class VerifiedCard:
    raw_bytes: bytes          # exact bytes the signature was verified over
    signature_ok: bool
    signer: str


def canonicalize(obj: Any) -> bytes:
    # Pinned canonicalizer: sorted keys, no whitespace, UTF-8.
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def admit_card(
    card: VerifiedCard,
    caller_model_fields: frozenset[str],
    allowlist_prefixes: tuple[str, ...],
    trusted_schema_digests: frozenset[str],
) -> dict:
    if not card.signature_ok:
        raise ManifestAdmissionError(f"signature invalid for signer={card.signer}")

    # Clause 2: re-canonicalization must reproduce the verified bytes.
    try:
        parsed = json.loads(card.raw_bytes.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        raise ManifestAdmissionError(f"verified bytes not parseable: {exc}") from exc

    if canonicalize(parsed) != card.raw_bytes:
        raise ManifestAdmissionError(
            "canonicalization divergence: signer and verifier disagree on byte stream; "
            "all downstream projections are untrusted"
        )

    # Clause 5: fail closed on any field the caller's model cannot represent.
    dropped = set(parsed.keys()) - caller_model_fields
    if dropped:
        raise ManifestAdmissionError(
            f"card contains fields outside caller model: {sorted(dropped)}; "
            "constraints in these fields are invisible to admission and must not be delegated past"
        )

    # Clause 3: skill scope must be a subset of the allowlist, evaluated on verified bytes.
    skills = parsed.get("skills", [])
    if not isinstance(skills, list) or not all(isinstance(s, str) for s in skills):
        raise ManifestAdmissionError("malformed skills block in verified card")

    out_of_scope = [
        s for s in skills if not any(s == p or s.startswith(p.rstrip("*")) for p in allowlist_prefixes)
    ]
    if out_of_scope:
        raise ManifestAdmissionError(
            f"skills outside allowlist: {out_of_scope}; refusing delegation"
        )

    # Clause 4: schema digests must be pre-registered, not inferred at admission time.
    for skill in parsed.get("skill_details", []):
        schema = skill.get("inputSchema")
        if schema is None:
            continue
        digest = hashlib.sha256(canonicalize(schema)).hexdigest()
        if digest not in trusted_schema_digests:
            raise ManifestAdmissionError(
                f"untrusted input schema digest {digest[:16]} for skill {skill.get('id')}; "
                "inline-vs-URI schema representation may widen accepted input domain"
            )

    return parsed
