# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-chain-despite-a-valid-signature-at-every-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-chain-despite-a-valid-signature-at-every-hop.warrant.json
# Markdown SHA-256:   6853ebeaa452f9b2e4a2302b3d3ec9ad56b4b90273a7748bf0cb15bae53dbe28
# Code AST SHA-256:   ef76642dbc6502c0c6e311e4e1abeecbc80b2066612dd95d2d36305f7933c207
# Verified Classes:   DelegationScopeViolation, EpochSuperseded
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class DelegationScopeViolation(RuntimeError):
    """Raised when a hop's scope exceeds the delegable scope carried from its issuer."""
    pass


class EpochSuperseded(RuntimeError):
    """Raised when a hop's epoch predates the issuer's current rotation floor."""
    pass


def verify_chain(chain, requested_action, rotation_floors):
    # chain: list of hops root->leaf, each dict with keys:
    #   issuer, scope (set), may_delegate (set or None), epoch, signature_ok
    if not chain:
        raise DelegationScopeViolation("empty delegation chain")

    # Hop 0 is the root principal; its delegable scope is its full scope.
    permitted = set(chain[0]["scope"])
    if chain[0]["may_delegate"] is not None:
        permitted &= set(chain[0]["may_delegate"])

    for i in range(1, len(chain)):
        hop = chain[i]
        issuer = chain[i - 1]["issuer"]

        if not hop.get("signature_ok", False):
            raise DelegationScopeViolation(f"hop {i} signature invalid")

        floor = rotation_floors.get(issuer, 0)
        if hop["epoch"] < floor:
            raise EpochSuperseded(
                f"hop {i} epoch {hop['epoch']} predates rotation floor {floor} for {issuer}"
            )

        hop_scope = set(hop["scope"])
        if not hop_scope <= permitted:
            raise DelegationScopeViolation(
                f"hop {i} scope {hop_scope} exceeds delegable scope {permitted} from {issuer}"
            )

        # Carry the intersection forward: what this hop may further delegate.
        if hop["may_delegate"] is not None:
            permitted = hop_scope & set(hop["may_delegate"])
        else:
            permitted = set()  # no further delegation permitted

    leaf_scope = set(chain[-1]["scope"])
    if requested_action not in leaf_scope:
        raise DelegationScopeViolation(
            f"requested action {requested_action!r} not in leaf scope {leaf_scope}"
        )
    return True
