# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-translate-a-peer-org-s-delegation-policy-during-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-translate-a-peer-org-s-delegation-policy-during-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   4ba8d47c47d6c92ae6735613a7d881e44bd825b6bc9c28bdca36c76934ab3a06
# Code AST SHA-256:   e958bfbb581fea27ee9e9977de0ea00ae2f101be0e788346ea5b7d48b6ad2409
# Verified Classes:   UntranslatableDelegationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UntranslatableDelegationError(RuntimeError):
    """Raised when a foreign delegation cannot be totally and faithfully
    translated into the local authorization model. Refusal is the correct
    outcome; this is not an error path to be swallowed."""
    pass


FIDELITY_CLASSES = {"exact", "narrowed", "widened", "unrepresentable"}


def translate_delegation(foreign_policy, local_model, liability_record):
    # Condition 1: total semantic coverage, equal-or-narrower only.
    unmapped = [tok for tok in foreign_policy.constraints
                if not local_model.can_represent_equal_or_narrower(tok)]
    if unmapped:
        raise UntranslatableDelegationError(
            f"delegation {foreign_policy.id} from {foreign_policy.issuer}: "
            f"unrepresentable constraints {unmapped}; refusing atomically "
            f"rather than dropping constraints (dropping widens authority)"
        )

    # Condition 2: fidelity class must be from the closed set and executable.
    fidelity = local_model.compute_fidelity(foreign_policy)
    if fidelity not in FIDELITY_CLASSES:
        raise UntranslatableDelegationError(
            f"translator emitted unknown fidelity class {fidelity!r}"
        )
    if fidelity in {"widened", "unrepresentable"}:
        raise UntranslatableDelegationError(
            f"delegation {foreign_policy.id}: fidelity={fidelity} is not "
            f"executable; broker must refuse, not best-effort interpret"
        )

    # Condition 3: liability handoff must be countersigned by both orgs.
    if not (liability_record.signed_by_issuer and liability_record.signed_by_local):
        raise UntranslatableDelegationError(
            f"delegation {foreign_policy.id}: liability handoff not "
            f"countersigned by both orgs; unilateral assertion is not a handoff"
        )

    return local_model.issue_grant(foreign_policy, fidelity, liability_record)
