# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-is-a-strict-subset-of-its-own-authority-but-whose-issuer-chain-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-is-a-strict-subset-of-its-own-authority-but-whose-issuer-chain-t.warrant.json
# Markdown SHA-256:   171b5ed10de2383efdfae7275397975b1a66c33a5e7b0216d04824a1a4f2d3e5
# Code AST SHA-256:   503f6a2aab8396bd324bbcbdee771a71736cdf974cba195a92168e7638ae138a
# Verified Classes:   AAIFChainError, Scope, Credential, TrustStore
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AAIFChainError(RuntimeError):
    """Raised when a delegated AAIF credential fails chain or scope soundness."""
    pass


@dataclass(frozen=True)
class Scope:
    actions: frozenset
    namespace: str

    def subset_of(self, other: "Scope") -> bool:
        return self.namespace == other.namespace and self.actions <= other.actions


@dataclass(frozen=True)
class Credential:
    issuer: str
    subject: str
    scope: Scope
    parent_warrant: Optional["Credential"]
    chain: tuple  # ordered issuer identities, leaf-issuer first, root last


@dataclass
class TrustStore:
    # trust is a relation (root, namespace) -> bool, NOT a flat set
    trusted: dict = field(default_factory=dict)

    def trusts(self, root: str, namespace: str) -> bool:
        return self.trusted.get((root, namespace), False)


def validate(cred: Credential, store: TrustStore) -> None:
    parent = cred.parent_warrant
    if parent is None:
        raise AAIFChainError("delegated credential missing parent warrant")

    # 1. scope containment (structural)
    if not cred.scope.subset_of(parent.scope):
        raise AAIFChainError(
            f"scope {cred.scope} not subset of parent {parent.scope}"
        )

    # 2. parent warrant MUST be reachable on the presented chain
    #    chain[0] == cred.issuer; the parent's issuer must be the next hop.
    if len(cred.chain) < 2:
        raise AAIFChainError("chain too short to anchor parent warrant")
    if cred.chain[0] != cred.issuer:
        raise AAIFChainError("chain head does not match credential issuer")
    if parent.issuer != cred.chain[1]:
        # This is the re-rooting defect: parent copied by reference,
        # but the chain does not actually pass through the parent's issuer.
        raise AAIFChainError(
            f"ChainDiscontinuity: parent issuer {parent.issuer!r} "
            f"is not chain[1]={cred.chain[1]!r}"
        )

    # 3. monotonic attenuation along the whole chain
    #    (each hop's scope must be a subset of its predecessor)
    cur = cred
    seen = 0
    while cur.parent_warrant is not None:
        nxt = cur.parent_warrant
        if not cur.scope.subset_of(nxt.scope):
            raise AAIFChainError(
                f"AttenuationViolation at hop {seen}: {cur.scope} !⊆ {nxt.scope}"
            )
        cur = nxt
        seen += 1

    # 4. rooted termination in a namespace-scoped trusted root
    root = cred.chain[-1]
    if not store.trusts(root, cred.scope.namespace):
        raise AAIFChainError(
            f"RootNotTrustedForNamespace: root {root!r} not trusted for "
            f"namespace {cred.scope.namespace!r}"
        )


# --- reproduction of the observed failure ---
if __name__ == "__main__":
    w_a = Credential(
        issuer="R_org", subject="A",
        scope=Scope(frozenset({"read:repo", "write:pr"}), "repo:org"),
        parent_warrant=None, chain=("R_org",),
    )
    # M re-roots the delegation to its own partner root, scope preserved
    re_rooted = Credential(
        issuer="M", subject="C",
        scope=Scope(frozenset({"read:repo:path=/src"}), "repo:org"),
        parent_warrant=w_a,                 # copied by reference
        chain=("M", "R_partner"),           # M's root, NOT R_org
    )
    store = TrustStore(trusted={("R_partner", "partner:shared"): True})
    try:
        validate(re_rooted, store)
    except AAIFChainError as e:
        # Expected: ChainDiscontinuity (and would also fail namespace trust)
        print(f"REJECTED: {e}")
        raise AAIFChainError(f"delegated credential rejected: {e}") from e
