# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-brokered-capability-grant-whose-policy-envelope-has-been-transitively-narrowed-by-an-intermediate-org.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-brokered-capability-grant-whose-policy-envelope-has-been-transitively-narrowed-by-an-intermediate-org.warrant.json
# Markdown SHA-256:   ac6bce1cdc04bf94577c5d7b60b691f05aede76eeb880efaa4e9ba83a6a538b1
# Code AST SHA-256:   0afc596647ab5293cd8c7cd57eae7c76d6715af2e4988cf8e5c0fd918694b4be
# Verified Classes:   EnvelopeIncompleteError
# Defensive Guards:   10 fail-closed invariants (zero external deps)

class EnvelopeIncompleteError(RuntimeError):
    """Raised when a brokered capability grant cannot have its effective
    policy computed because an envelope constraint was dropped, defaulted,
    or narrowed without a signed subset proof."""
    pass


REQUIRED_ENVELOPE_FIELDS = frozenset({
    "max_data_class",
    "max_calls_per_min",
    "delegation_depth_remaining",
})

# Sentinels: ABSENT means the field was never present (hard error).
# NULL means the issuer explicitly set no constraint (legal, means unbounded).
ABSENT = object()
NULL = object()


def compute_effective_envelope(chain):
    """
    chain: list of hop dicts, ordered issuer -> ... -> leaf.
    Each hop: {"issuer": str, "envelope": dict, "narrowed_from": str|None,
               "signature": str}
    Returns the intersected envelope. Raises EnvelopeIncompleteError on any
    hop whose envelope is missing a required field, or whose narrowing is
    not provably a subset of its parent.
    """
    if not chain:
        raise EnvelopeIncompleteError("empty capability chain")

    effective = {}
    issuer_env = chain[0]["envelope"]

    for field in REQUIRED_ENVELOPE_FIELDS:
        val = issuer_env.get(field, ABSENT)
        if val is ABSENT:
            raise EnvelopeIncompleteError(
                f"issuer envelope missing required field {field!r}; "
                f"cannot establish baseline for intersection"
            )
        effective[field] = val

    for hop_index, hop in enumerate(chain[1:], start=1):
        env = hop["envelope"]
        parent_id = hop.get("narrowed_from")

        if parent_id is None:
            raise EnvelopeIncompleteError(
                f"hop {hop_index} ({hop['issuer']}) declares no parent; "
                f"a narrowing hop must reference the envelope it narrowed"
            )

        for field in REQUIRED_ENVELOPE_FIELDS:
            child_val = env.get(field, ABSENT)
            if child_val is ABSENT:
                # The exact failure observed: a lossy broker schema drops
                # a field, and the leaf cannot tell "no constraint" from
                # "constraint lost". Refuse to default.
                raise EnvelopeIncompleteError(
                    f"hop {hop_index} ({hop['issuer']}) dropped envelope "
                    f"field {field!r}; absence is not a default and the "
                    f"intersection is not computable at the leaf"
                )

            parent_val = effective[field]

            if field == "max_data_class":
                # Lower class number = stricter. Child must be <= parent.
                if child_val is not NULL and parent_val is not NULL:
                    if child_val > parent_val:
                        raise EnvelopeIncompleteError(
                            f"hop {hop_index} widened max_data_class "
                            f"{parent_val}->{child_val} without authorization"
                        )
                effective[field] = (
                    child_val if parent_val is NULL
                    else parent_val if child_val is NULL
                    else min(child_val, parent_val)
                )

            elif field == "max_calls_per_min":
                if child_val is not NULL and parent_val is not NULL:
                    if child_val > parent_val:
                        raise EnvelopeIncompleteError(
                            f"hop {hop_index} widened max_calls_per_min "
                            f"{parent_val}->{child_val} without authorization"
                        )
                effective[field] = (
                    child_val if parent_val is NULL
                    else parent_val if child_val is NULL
                    else min(child_val, parent_val)
                )

            elif field == "delegation_depth_remaining":
                if parent_val is not NULL and child_val is not NULL:
                    if child_val >= parent_val:
                        raise EnvelopeIncompleteError(
                            f"hop {hop_index} did not decrement "
                            f"delegation_depth_remaining "
                            f"({parent_val}->{child_val}); a relay hop must "
                            f"consume depth"
                        )
                effective[field] = child_val

    if effective["delegation_depth_remaining"] is not NULL:
        if effective["delegation_depth_remaining"] < 0:
            raise EnvelopeIncompleteError(
                "delegation depth exhausted; grant cannot be honored"
            )

    return effective


def authorize_invocation(chain, requested_data_class, requested_calls_per_min):
    env = compute_effective_envelope(chain)

    if env["max_data_class"] is not NULL:
        if requested_data_class > env["max_data_class"]:
            raise EnvelopeIncompleteError(
                f"requested data class {requested_data_class} exceeds "
                f"effective ceiling {env['max_data_class']}"
            )

    if env["max_calls_per_min"] is not NULL:
        if requested_calls_per_min > env["max_calls_per_min"]:
            raise EnvelopeIncompleteError(
                f"requested rate {requested_calls_per_min}/min exceeds "
                f"effective ceiling {env['max_calls_per_min']}/min"
            )

    return env
