# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a2a-capability-negotiation-divergence-when-mcp-tool-schemas-are-re-projected-across-implementations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a2a-capability-negotiation-divergence-when-mcp-tool-schemas-are-re-projected-across-implementations.warrant.json
# Markdown SHA-256:   f3fa0bd5aac345ee343dde88cf8725daca4ff935275c7481c96aefe437a2a504
# Code AST SHA-256:   9dfcfe5e55538a12a1571ffcdb9957444134dbc67ad771346448ef7bbb7431a4
# Verified Classes:   ProjectionSoundnessError, ConstraintDelta
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any, Callable


class ProjectionSoundnessError(RuntimeError):
    """Raised when a projected A2A skill schema is not sound w.r.t. its MCP source."""
    pass


@dataclass(frozen=True)
class ConstraintDelta:
    lost_const: bool
    lost_oneof: bool
    lost_closed_object: bool
    lost_required_under_discriminator: bool

    @property
    def is_lossy(self) -> bool:
        return any([self.lost_const, self.lost_oneof,
                    self.lost_closed_object, self.lost_required_under_discriminator])


def measure_projection_delta(source: dict, projected: dict) -> ConstraintDelta:
    def walk(node: Any, key: str) -> bool:
        if isinstance(node, dict):
            if key in node:
                return True
            return any(walk(v, key) for v in node.values())
        if isinstance(node, list):
            return any(walk(v, key) for v in node)
        return False

    return ConstraintDelta(
        lost_const=walk(source, "const") and not walk(projected, "const"),
        lost_oneof=walk(source, "oneOf") and not walk(projected, "oneOf"),
        lost_closed_object=(
            source.get("additionalProperties") is False
            and projected.get("additionalProperties") is not False
        ),
        lost_required_under_discriminator=(
            walk(source, "discriminator") and not walk(projected, "discriminator")
        ),
    )


def assert_projection_sound(
    source: dict,
    projected: dict,
    behavioral_differential: Callable[[dict, dict], bool] | None = None,
) -> None:
    delta = measure_projection_delta(source, projected)
    if not delta.is_lossy:
        return  # structural round-trip is sound; caller may assert invertibility
    if behavioral_differential is None:
        raise ProjectionSoundnessError(
            f"Lossy projection with no behavioral fallback: {delta}. "
            "Structural round-trip would be unsound; refusing to certify interop."
        )
    if not behavioral_differential(source, projected):
        raise ProjectionSoundnessError(
            f"Behavioral differential failed under lossy projection: {delta}. "
            "Accept/reject sets diverge between source handler and projected client."
        )
    # Lossy but behaviorally equivalent: certify with explicit waiver recorded.
