# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-presents-a-delegated-warrant-after-its-scope-narrowing-chain-has-been-re-signed-upstream.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-presents-a-delegated-warrant-after-its-scope-narrowing-chain-has-been-re-signed-upstream.warrant.json
# Markdown SHA-256:   4b6f1086069cda6abc450d62a33798240722d9c3cfe83906669bc9cbb80c41d2
# Code AST SHA-256:   f9b7bcd755e33d6a8e2c580531ecd3903e2ca2a41dd0f67ba764ddec5e4dba4c
# Verified Classes:   DelegationChainError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional
import hashlib


class DelegationChainError(RuntimeError):
    """Raised when a delegated warrant's path cannot be validated against current registry state."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    scope: frozenset
    parent_digest: Optional[str]   # SHA256 of canonical parent, None for root
    supersedes: Optional[str] = None


def canonical_digest(w: Warrant) -> str:
    # Deliberately excludes signature/issuance_time so re-signing does not change the digest
    # ONLY if the registry models supersession correctly (new ID, supersedes pointer).
    payload = f"{w.warrant_id}|{w.issuer}|{sorted(w.scope)}|{w.parent_digest}|{w.supersedes}"
    return hashlib.sha256(payload.encode()).hexdigest()


def verify_delegation_path(
    leaf: Warrant,
    registry: dict,                # versioned: digest -> Warrant, NOT latest-wins by id
    root_scope: frozenset,
) -> None:
    """
    Walk leaf -> root against CURRENT registry state.
    A digest mismatch is a re-walk trigger, not an immediate reject and not a
    fallback to leaf-only verification.
    """
    chain = [leaf]
    current = leaf
    while current.parent_digest is not None:
        parent = registry.get(current.parent_digest)
        if parent is None:
            raise DelegationChainError(
                f"unreconstructable chain at {current.warrant_id}: "
                f"parent_digest {current.parent_digest} not resolvable to a versioned warrant"
            )
        chain.append(parent)
        current = parent

    # Re-verify attenuation at every hop against live scope.
    for child, parent in zip(chain, chain[1:]):
        if not child.scope.issubset(parent.scope):
            raise DelegationChainError(
                f"scope_no_longer_attenuable: {child.warrant_id} scope {set(child.scope)} "
                f"not subset of current parent {parent.warrant_id} scope {set(parent.scope)}"
            )

    root = chain[-1]
    if not root.scope.issubset(root_scope):
        raise DelegationChainError(
            f"root scope {set(root.scope)} exceeds principal grant {set(root_scope)}"
        )


def present(leaf: Warrant, registry: dict, root_scope: frozenset) -> str:
    try:
        verify_delegation_path(leaf, registry, root_scope)
    except DelegationChainError:
        raise
    # Repair: re-issue leaf with current parent digest so next call is cheap.
    return f"admitted:{leaf.warrant_id}"
