# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-it-cannot-re-derive-at-replay-time.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-it-cannot-re-derive-at-replay-time.warrant.json
# Markdown SHA-256:   6ef04f1f373684cc1ac20c4f906d4ad01428e556d639cc8fbbd6c721717caf58
# Code AST SHA-256:   924c7c740038f7572e4882f6193e334382f2286f659643d6cc09c6a6e09a935a
# Verified Classes:   ReplayIntegrityError, ReplayMode, CapabilityToken, PolicyBundle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ReplayIntegrityError(RuntimeError):
    """Raised when a derivation-mode capability token cannot be replayed
    to a byte-identical decision from its pinned witness."""


class ReplayMode(Enum):
    ATTESTATION = "attestation"
    DERIVATION = "derivation"


@dataclass(frozen=True)
class CapabilityToken:
    grantee_org: str
    capability: str
    issuer_org: str
    policy_digest: str
    replay_mode: ReplayMode
    witness: dict | None  # dynamic inputs consumed by the decision, signed


@dataclass(frozen=True)
class PolicyBundle:
    digest: str
    rules: list[str]


def fetch_policy_by_digest(archive: dict[str, PolicyBundle], digest: str) -> PolicyBundle | None:
    return archive.get(digest)


def evaluate(policy: PolicyBundle, witness: dict) -> bool:
    # Toy decision procedure: allow if grantee org is in the witness's
    # trusted_orgs snapshot at decision time. Real engines are richer,
    # but the invariant is identical: the decision must be a pure
    # function of (policy bytes, witness).
    return witness.get("grantee_org") in witness.get("trusted_orgs", ())


def replay(token: CapabilityToken, archive: dict[str, PolicyBundle]) -> bool:
    if token.replay_mode is ReplayMode.ATTESTATION:
        # Attestation tokens are not derivable; auditors verify signature
        # and expiry only, elsewhere. Refuse to derive.
        raise ReplayIntegrityError(
            f"token for {token.grantee_org} is attestation-mode; "
            "derivation replay is a category error"
        )

    policy = fetch_policy_by_digest(archive, token.policy_digest)
    if policy is None:
        raise ReplayIntegrityError(
            f"policy bytes for digest {token.policy_digest} not retrievable; "
            "digest without content is an attestation trap"
        )

    if token.witness is None:
        raise ReplayIntegrityError(
            "derivation-mode token missing decision witness; "
            "dynamic inputs (e.g. trusted_orgs) cannot be reconstructed"
        )

    recomputed = hashlib.sha256(
        repr((policy.rules, sorted(token.witness.items()))).encode()
    ).hexdigest()
    if recomputed != token.policy_digest:
        raise ReplayIntegrityError(
            f"witness does not reproduce pinned digest {token.policy_digest}; "
            "either witness incomplete or policy mutated under pinned pointer"
        )

    return evaluate(policy, token.witness)


def audit(token: CapabilityToken, archive: dict[str, PolicyBundle]) -> str:
    try:
        authorized = replay(token, archive)
    except ReplayIntegrityError as e:
        # The correct third state: do not emit an authorization verdict.
        return f"INDETERMINATE_INTEGRITY: {e}"
    return "AUTHORIZED" if authorized else "UNAUTHORIZED"
