# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-policy-translation-drift-when-a-brokered-trust-chain-silently-widens-its-authority-across-orgs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-policy-translation-drift-when-a-brokered-trust-chain-silently-widens-its-authority-across-orgs.warrant.json
# Markdown SHA-256:   693ea6fcb0a5d7738c74d090cbbb02e4f5179b92c7f2e4eb4c20c062cc3ca1bf
# Code AST SHA-256:   69242ea4939b06a1fa56f937959ba1d5cab8a1fe0351f03c502b29ba319f2281
# Verified Classes:   TranslationWideningError, Constraint, TranslationAttestation, TranslatedWarrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TranslationWideningError(RuntimeError):
    """Raised when a brokered warrant admits more authority than its source."""
    pass


@dataclass
class Constraint:
    kind: str                 # "numeric" | "enum" | "deny"
    field_name: str
    value: object
    unit: Optional[str] = None


@dataclass
class TranslationAttestation:
    gateway_id: str
    source_dialect: str
    target_dialect: str
    mapped: dict = field(default_factory=dict)      # source_field -> target_field
    tightened: dict = field(default_factory=dict)   # source_field -> delta description
    dropped: list = field(default_factory=list)     # source fields with NO target
    signature_valid: bool = True


@dataclass
class TranslatedWarrant:
    source_constraints: list
    target_constraints: list
    attestation: TranslationAttestation


def check_narrowing(warrant: TranslatedWarrant) -> str:
    """
    Returns "accept" | "accept-with-tightening".
    Raises TranslationWideningError on any silent widening.
    """
    att = warrant.attestation

    if not att.signature_valid:
        raise TranslationWideningError(
            f"attestation from {att.gateway_id} failed signature verification; "
            "cannot prove narrowing, refusing to admit"
        )

    # Rule 1: unmappable denies must fail closed, never be elided.
    for src in warrant.source_constraints:
        if src.kind == "deny" and src.field_name in att.dropped:
            raise TranslationWideningError(
                f"deny on '{src.field_name}' was dropped by {att.gateway_id} "
                f"({att.source_dialect}->{att.target_dialect}); "
                "no target representation and no fail-closed tightening recorded"
            )

    # Rule 2: numeric constraints must carry unit through translation.
    for src in warrant.source_constraints:
        if src.kind == "numeric":
            tgt_field = att.mapped.get(src.field_name)
            if tgt_field is None and src.field_name not in att.tightened:
                raise TranslationWideningError(
                    f"numeric constraint on '{src.field_name}' has no mapped "
                    f"target and no recorded tightening; unit '{src.unit}' may be lost"
                )
            if src.unit and src.field_name in att.mapped:
                tgt = next((t for t in warrant.target_constraints
                            if t.field_name == tgt_field), None)
                if tgt is not None and tgt.unit != src.unit and \
                        src.field_name not in att.tightened:
                    raise TranslationWideningError(
                        f"unit drift on '{src.field_name}': source unit "
                        f"'{src.unit}' -> target unit '{tgt.unit}' with no "
                        "tightening delta; numeric bound may be loosened"
                    )

    # Rule 3: enum-valued constraints require declared homomorphism, not lexical match.
    for src in warrant.source_constraints:
        if src.kind == "enum":
            tgt_field = att.mapped.get(src.field_name)
            if tgt_field is None:
                continue
            if src.field_name not in att.tightened:
                # Lexical identity is not proof of set inclusion.
                raise TranslationWideningError(
                    f"enum '{src.field_name}' mapped to '{tgt_field}' without "
                    "declared homomorphism or tightening; lexical identity is "
                    "not semantic identity"
                )

    if att.tightened:
        return "accept-with-tightening"
    return "accept"


def admit(warrant: TranslatedWarrant) -> str:
    decision = check_narrowing(warrant)
    # downstream execution would proceed only on "accept" or "accept-with-tightening"
    return decision
