# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-scope-token-whose-delegation-chain-is-length-1-but-whose-issuer-key-is-itself-a-scoped-delegate.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-scope-token-whose-delegation-chain-is-length-1-but-whose-issuer-key-is-itself-a-scoped-delegate.warrant.json
# Markdown SHA-256:   424ef6e60c9e35f2f37630e8787963b04eee8e907cf069e9cb4b11012adab607
# Code AST SHA-256:   1308751b09ef0fb448d0e2d40cbf0507bd78d20d9a67468cabff32cbd9e601b1
# Verified Classes:   UnanchoredDelegationError, TrustStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class UnanchoredDelegationError(RuntimeError):
    """Raised when a delegated-scope token's chain cannot be anchored to a trust-store root."""


class TrustStore:
    def __init__(self, roots):
        # roots: dict[did -> {"authority_class": str, "key_fingerprint": str, "realm": str}]
        self._roots = roots

    def lookup(self, did):
        return self._roots.get(did)


def verify_delegated_scope_token(token, trust_store):
    chain = token.get("delegation_chain", [])
    issuer = token["issuer"]
    realm = token["realm"]
    key_fp = token["proof"]["key_fingerprint"]

    if len(chain) == 0:
        raise UnanchoredDelegationError(
            f"delegated-scope token from {issuer} has empty delegation_chain; no anchor"
        )

    if len(chain) >= 2:
        # Chain carries its own anchor; verify first link against trust store.
        root_did = chain[0]["issuer_did"]
        record = trust_store.lookup(root_did)
        if record is None or record["authority_class"] != "root":
            raise UnanchoredDelegationError(
                f"chain head {root_did} is not a trust-store root"
            )
        return root_did

    # len(chain) == 1: the boundary case. Do NOT infer root from length.
    record = trust_store.lookup(issuer)
    if record is None:
        raise UnanchoredDelegationError(
            f"issuer {issuer} absent from trust store; cannot anchor length-1 chain"
        )
    if record["authority_class"] != "root":
        raise UnanchoredDelegationError(
            f"issuer {issuer} is authority_class={record['authority_class']!r}, "
            f"not root; length-1 chain is delegate-minted, not root-anchored"
        )
    if record["key_fingerprint"] != key_fp:
        raise UnanchoredDelegationError(
            f"issuer {issuer} key fingerprint mismatch: token={key_fp} "
            f"trust_store={record['key_fingerprint']}; possible rotation lag or key collision"
        )
    if record["realm"] != realm:
        raise UnanchoredDelegationError(
            f"issuer {issuer} realm mismatch: token={realm} trust_store={record['realm']}; "
            f"cross-realm root collision"
        )
    return issuer
