# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-an-authority-scope-inversion-during-cross-domain-warrant-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-an-authority-scope-inversion-during-cross-domain-warrant-exchange.warrant.json
# Markdown SHA-256:   9bcf031db19afb441316c7fd8e0a2018e003d6d5bb0228b954958ba21348003b
# Code AST SHA-256:   07b04a499844cbdc085284784e75ba04dcc29f28d72b55a1c4376b774d762790
# Verified Classes:   DischargeModel, ScopeTranslation, ForeignClaim, ScopeInversionError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Optional


class DischargeModel(Enum):
    CLOSED_AT_ISSUANCE = "closed_at_issuance"   # issuer consumed the evidence; never re-derivable
    OPEN_AT_USE = "open_at_use"                 # relying party must obtain evidence at call time


@dataclass(frozen=True)
class ScopeTranslation:
    issuer_domain: str
    claim: str
    semantics_version: str
    discharge_model: DischargeModel
    local_claim: str


@dataclass
class ForeignClaim:
    issuer_domain: str
    claim: str
    semantics_version: str
    # annotations the issuer attached; may include closed-at-issuance markers
    annotations: Dict[str, str] = field(default_factory=dict)


class ScopeInversionError(RuntimeError):
    """Raised when a foreign claim would be evaluated under local semantics
    without a translation record, or when a closed-at-issuance constraint is
    discharged against a relying-side ledger that cannot contain the evidence."""


def resolve_claim(
    fc: ForeignClaim,
    translations: Dict[tuple, ScopeTranslation],
    local_ledger: Dict[str, bool],
    principal: str,
) -> str:
    key = (fc.issuer_domain, fc.claim, fc.semantics_version)
    tr = translations.get(key)

    # Boundary 1: no translation record -> reject, never name-match.
    if tr is None:
        raise ScopeInversionError(
            f"no scope-algebra translation for {key}; refusing name-match "
            f"of '{fc.claim}' under local semantics"
        )

    # Boundary 2: closed-at-issuance constraints must not be re-derived locally.
    if tr.discharge_model is DischargeModel.CLOSED_AT_ISSUANCE:
        if "oversight" in fc.annotations:
            # The issuer already discharged this gate. The relying party must
            # treat it as satisfied-and-non-re-derivable, NOT consult its ledger.
            return tr.local_claim
        # A closed-at-issuance claim arriving without its discharge marker is
        # malformed: the issuer's model guarantees the marker. Fail closed.
        raise ScopeInversionError(
            f"claim '{fc.claim}' from {fc.issuer_domain} is closed-at-issuance "
            f"but carries no discharge marker; cannot authenticate the gate"
        )

    # Boundary 3: open-at-use claims require real evidence in the local ledger.
    # An empty ledger is absence of evidence -> deny, never 'satisfied'.
    if tr.discharge_model is DischargeModel.OPEN_AT_USE:
        if not local_ledger.get(principal, False):
            raise ScopeInversionError(
                f"open-at-use claim '{fc.claim}' for principal '{principal}' "
                f"has no discharged evidence in local ledger; empty != satisfied"
            )
        return tr.local_claim

    raise ScopeInversionError(f"unhandled discharge model {tr.discharge_model}")


# Minimal exercise of the inversion the article describes.
if __name__ == "__main__":
    translations = {
        ("clinic-a", "act:schedule", "v2"): ScopeTranslation(
            issuer_domain="clinic-a",
            claim="act:schedule",
            semantics_version="v2",
            discharge_model=DischargeModel.CLOSED_AT_ISSUANCE,
            local_claim="act:schedule",
        )
    }
    # Correct path: marker present -> accepted under translated semantics.
    ok = ForeignClaim("clinic-a", "act:schedule", "v2",
                      annotations={"oversight": "human-in-loop-required"})
    assert resolve_claim(ok, translations, {}, "scheduler-7") == "act:schedule"

    # Inversion path: same string, no translation record -> must raise.
    unregistered = ForeignClaim("clinic-a", "act:schedule", "v1")
    try:
        resolve_claim(unregistered, translations, {}, "scheduler-7")
    except ScopeInversionError as e:
        print("blocked:", e)
