# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-capability-grant-when-the-peer-s-schema-digest-disagrees-with-the-digest-embedded-in-its-own-signed-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-capability-grant-when-the-peer-s-schema-digest-disagrees-with-the-digest-embedded-in-its-own-signed-warrant.warrant.json
# Markdown SHA-256:   a77bfa9a19484ca1b7a65de0bf1653eca4ffffb256063c849c7ac23537560355
# Code AST SHA-256:   dcf65fcaf3d92e1947fbb255cba57a25689a90fdd111e2ba9f9c241161116cb9
# Verified Classes:   FederatedSchemaDriftError, WarrantSemanticsViolation, CapabilityWarrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class FederatedSchemaDriftError(RuntimeError):
    """Raised when the live peer schema digest diverges from the warrant-embedded digest."""
    pass


class WarrantSemanticsViolation(RuntimeError):
    """Raised when a warrant-bound call would require coercion or field elision to validate."""
    pass


@dataclass(frozen=True)
class CapabilityWarrant:
    grantee_org: str
    tool_name: str
    arg_schema_digest: str
    ret_schema_digest: str
    ttl_seconds: int


def _digest(schema: dict) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return "sha256:" + hashlib.sha256(canonical.encode()).hexdigest()


def invoke_federated(
    warrant: CapabilityWarrant,
    peer_live_arg_schema: dict,
    peer_live_ret_schema: dict,
    args: dict,
    transport,
) -> dict:
    # Invariant 1: the warrant, not the live card, is the schema authority.
    live_arg = _digest(peer_live_arg_schema)
    live_ret = _digest(peer_live_ret_schema)

    if live_arg != warrant.arg_schema_digest or live_ret != warrant.ret_schema_digest:
        raise FederatedSchemaDriftError(
            f"peer {warrant.grantee_org} schema drift on {warrant.tool_name}: "
            f"warrant_arg={warrant.arg_schema_digest} live_arg={live_arg} "
            f"warrant_ret={warrant.ret_schema_digest} live_ret={live_ret}; "
            f"quarantine warrant and re-negotiate"
        )

    # Invariant 2: no coercion, no optional-field elision on the warrant-bound path.
    required = set(peer_live_arg_schema.get("required", []))
    provided = set(args.keys())
    allowed = set(peer_live_arg_schema.get("properties", {}).keys())

    if not required.issubset(provided):
        raise WarrantSemanticsViolation(
            f"missing required fields {required - provided} for {warrant.tool_name}"
        )
    if not provided.issubset(allowed):
        raise WarrantSemanticsViolation(
            f"unknown fields {provided - allowed} would be silently dropped for {warrant.tool_name}"
        )

    # Invariant 3: return shape is verified against the warrant, not trusted.
    result = transport(warrant.tool_name, args)
    if _digest(_infer_schema(result)) != warrant.ret_schema_digest:
        raise WarrantSemanticsViolation(
            f"return shape for {warrant.tool_name} does not match warrant return digest; "
            f"refusing to record as success"
        )
    return result


def _infer_schema(obj: dict) -> dict:
    return {
        "type": "object",
        "properties": {k: {"type": type(v).__name__} for k, v in obj.items()},
        "required": sorted(obj.keys()),
    }
