# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-warrant-whose-issuer-chain-is-cryptographically-valid-but-whose-delegation-depth-was-silently-rebas.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-warrant-whose-issuer-chain-is-cryptographically-valid-but-whose-delegation-depth-was-silently-rebas.warrant.json
# Markdown SHA-256:   b22e396a66fa6c5110069fd1dd2ec056106dc016bc48f49318dac9a795c7192b
# Code AST SHA-256:   f4fee02cafb0512cbafa6daca681a3755cf90c9850279e4c3bb993d44e2947e5
# Verified Classes:   DelegationDepthRebaseError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationDepthRebaseError(RuntimeError):
    """Raised when a delegated warrant's effective depth cannot be reconciled
    with the origin's attested hop count under any consistent interpretation."""
    pass


def effective_depth(warrant: dict, verifier_trusted_anchors: set[str]) -> int:
    """
    Compute the maximum delegation depth the presenter may still exercise,
    clamped to the minimum implied by all interpretations the verifier can
    justify from the token alone.

    warrant fields (all origin-signed):
      origin            : org id of the trust anchor
      origin_max_depth  : depth budget as asserted by origin
      hops_from_origin  : absolute hops traversed (origin-attested, +1 per hop)
      claimed_depth     : depth as re-asserted by the last issuer (UNTRUSTED)
      issuer_chain      : ordered list of org ids, [origin, ..., presenter]
    """
    origin = warrant["origin"]
    if origin not in verifier_trusted_anchors:
        raise DelegationDepthRebaseError(
            f"origin {origin!r} is not a trusted anchor; cannot establish depth semantics"
        )

    origin_max = warrant["origin_max_depth"]
    hops = warrant["hops_from_origin"]
    chain = warrant["issuer_chain"]

    # The origin-attested hop count must equal the chain length minus one.
    # A mismatch means an intermediate rewrote the chain or the counter.
    if hops != len(chain) - 1:
        raise DelegationDepthRebaseError(
            f"hops_from_origin={hops} inconsistent with issuer_chain length "
            f"{len(chain)} (expected {len(chain) - 1}); chain was rewritten in transit"
        )

    # Depth remaining under origin semantics.
    origin_remaining = origin_max - hops

    # Depth remaining under the last issuer's (possibly rebased) semantics.
    claimed_remaining = warrant["claimed_depth"]

    # Any interpretation the verifier can justify: take the minimum.
    # If the last issuer claims MORE than the origin allows, that is a rebase.
    if claimed_remaining > origin_remaining:
        # Clamp. Do not raise yet: clamping is safe, but flag the rebase.
        clamped = origin_remaining
    else:
        clamped = claimed_remaining

    if clamped < 0:
        raise DelegationDepthRebaseError(
            f"warrant exhausted: origin_max={origin_max}, hops={hops}, "
            f"chain={chain}; no delegation budget remains"
        )

    return clamped


def delegate(warrant: dict, trusted_anchors: set[str], next_issuer: str) -> dict:
    """Re-issue a warrant to `next_issuer` with strict attenuation only."""
    remaining = effective_depth(warrant, trusted_anchors)
    if remaining <= 0:
        raise DelegationDepthRebaseError(
            f"cannot delegate to {next_issuer!r}: zero remaining depth"
        )

    # Pure function of incoming warrant. No local ledger read. No rebasing.
    return {
        "origin": warrant["origin"],
        "origin_max_depth": warrant["origin_max_depth"],   # immutable
        "hops_from_origin": warrant["hops_from_origin"] + 1,  # monotonic +1
        "claimed_depth": remaining - 1,                    # attenuation only
        "issuer_chain": warrant["issuer_chain"] + [next_issuer],
    }
