# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-egress-allowlist-enforcement-is-about-to-fail-silently-in-an-mcp-server.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-egress-allowlist-enforcement-is-about-to-fail-silently-in-an-mcp-server.warrant.json
# Markdown SHA-256:   154a72f20c9824c7a106a66958b68e66c4b46d12a7c13bfd5a8530e197a5862a
# Code AST SHA-256:   72087ea969502dc2f4b703c5b4cb7cf215cdc2ac15bf9fa3e5e42e060938a027
# Verified Classes:   EgressDlpCoverageError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EgressDlpCoverageError(RuntimeError):
    """Raised when serialized egress fields are not fully covered by DLP inspection."""
    pass


def enforce_egress(tool_name, serialized_body, inspected_field_paths, allowlisted_destinations):
    destination = serialized_body.get("destination")
    if destination not in allowlisted_destinations:
        raise EgressDlpCoverageError(
            f"tool={tool_name} destination={destination!r} not in allowlist"
        )

    emitted_paths = _flatten_field_paths(serialized_body)
    uninspected = emitted_paths - inspected_field_paths
    if uninspected:
        raise EgressDlpCoverageError(
            f"tool={tool_name} emitted fields not inspected by DLP: {sorted(uninspected)}"
        )
    return True


def _flatten_field_paths(obj, prefix=""):
    paths = set()
    if isinstance(obj, dict):
        for k, v in obj.items():
            path = f"{prefix}.{k}" if prefix else k
            paths.add(path)
            paths |= _flatten_field_paths(v, path)
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            paths |= _flatten_field_paths(v, f"{prefix}[{i}]")
    return paths
