# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-capability-grant-whose-policy-translation-silently-widens-scope-across-an-org-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-capability-grant-whose-policy-translation-silently-widens-scope-across-an-org-boundary.warrant.json
# Markdown SHA-256:   c830713f4f117f297d43a00125e0b40cdbcf0c7d9b9e3c797c0dbec25f52e2be
# Code AST SHA-256:   65a162579843e0ce645d91660da69b2e50453b57dc8227fe5418851a848bde9d
# Verified Classes:   TranslationWideningError, Grant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class TranslationWideningError(RuntimeError):
    """Raised when a translated grant's enforced scope is not a subset of the source grant's."""
    pass


@dataclass
class Grant:
    subject: str
    resource_glob: str
    enforced_constraints: Dict[str, Set[str]] = field(default_factory=dict)


# Reviewed equivalence assertions: source primitive -> (target primitive, is_total)
# is_total=False means the target dialect cannot faithfully express the source constraint.
EQUIVALENCE_TABLE: Dict[str, tuple] = {
    "resource_selector": ("resource_glob", True),
    "field_mask": ("attribute_allowlist", True),
    "rate_limit": ("quota_window", True),
    "geo_fence": (None, False),  # no target primitive: must fail closed
}


def translate_grant(src: Grant, target_dialect: str) -> Grant:
    translated_constraints: Dict[str, Set[str]] = {}
    for primitive, values in src.enforced_constraints.items():
        mapping = EQUIVALENCE_TABLE.get(primitive)
        if mapping is None:
            raise TranslationWideningError(
                f"no equivalence entry for source primitive {primitive!r}; "
                f"refusing to translate (would silently drop enforcement)"
            )
        target_primitive, is_total = mapping
        if not is_total or target_primitive is None:
            raise TranslationWideningError(
                f"source primitive {primitive!r} has no faithful target in {target_dialect!r}; "
                f"fail closed rather than degrade to advisory"
            )
        translated_constraints[target_primitive] = set(values)

    translated = Grant(
        subject=src.subject,
        resource_glob=src.resource_glob,
        enforced_constraints=translated_constraints,
    )

    # Subset invariant: every source constraint must be represented, none widened.
    for src_prim, src_vals in src.enforced_constraints.items():
        tgt_prim = EQUIVALENCE_TABLE[src_prim][0]
        tgt_vals = translated.enforced_constraints.get(tgt_prim, set())
        if not src_vals.issubset(tgt_vals):
            raise TranslationWideningError(
                f"widening detected: {src_prim}={src_vals} not subset of "
                f"{tgt_prim}={tgt_vals}"
            )
    return translated


def admit_federated_call(src_grant: Grant, target_dialect: str, payload_fields: Set[str]) -> Grant:
    translated = translate_grant(src_grant, target_dialect)
    allowlist = translated.enforced_constraints.get("attribute_allowlist")
    if allowlist is not None and not payload_fields.issubset(allowlist):
        raise TranslationWideningError(
            f"payload mutates fields {payload_fields - allowlist} outside translated allowlist"
        )
    return translated
