# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-delegation-chain-contains-a-re-attested-hop-and-why-non-transitive-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-delegation-chain-contains-a-re-attested-hop-and-why-non-transitive-attestation.warrant.json
# Markdown SHA-256:   184dc9a345b461503293d9ab31deb1f94ed116416e096c5b1cc875a2799434bd
# Code AST SHA-256:   9e4c58159d1c09d3c212d922618d8e2801f013ba184c61d7509b9efc7567f6e2
# Verified Classes:   WarrantChainError, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class WarrantChainError(RuntimeError):
    """Raised when a delegation path violates the transitivity invariant."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    delegate: str
    scope: str
    parent: Optional[str]  # hash of parent warrant, None only for root issuers
    signature: str


ROOT_TRUST_SET = {"orchestrator-A"}


def _hash(w: Warrant) -> str:
    body = f"{w.issuer}|{w.delegate}|{w.scope}|{w.parent}|{w.signature}"
    return hashlib.sha256(body.encode()).hexdigest()


def _verify_signature(w: Warrant) -> None:
    # Placeholder for real key resolution + signature check.
    if not w.signature:
        raise WarrantChainError(f"unsigned attestation from {w.issuer}")


def _is_subscope(child: str, parent: str) -> bool:
    # Path-segment prefix check; real impl uses structured scope algebra.
    return child == parent or child.startswith(parent.rstrip("/") + "/")


def re_attest(warrant: Warrant, new_expiry: int, signer_key: str) -> Warrant:
    """Refresh an existing warrant WITHOUT changing delegate or scope.

    Preserves parent linkage. Cannot widen authority: no scope parameter exists.
    """
    if warrant.parent is None and warrant.issuer not in ROOT_TRUST_SET:
        raise WarrantChainError(
            f"cannot re-attest warrant from non-root issuer {warrant.issuer} "
            f"with null parent; chain would be truncated"
        )
    # new_expiry folded into signature in real impl; parent/scope copied verbatim.
    return Warrant(
        issuer=warrant.issuer,
        delegate=warrant.delegate,
        scope=warrant.scope,
        parent=warrant.parent,
        signature=f"reattest:{signer_key}:{new_expiry}",
    )


def delegate(warrant: Warrant, new_delegate: str, narrowed_scope: str, signer_key: str) -> Warrant:
    """Introduce a new delegate. Must narrow scope and bind to parent hash."""
    if not _is_subscope(narrowed_scope, warrant.scope):
        raise WarrantChainError(
            f"delegation widens scope: {narrowed_scope!r} not within {warrant.scope!r}"
        )
    return Warrant(
        issuer=warrant.issuer,
        delegate=new_delegate,
        scope=narrowed_scope,
        parent=_hash(warrant),
        signature=f"delegate:{signer_key}:{_hash(warrant)}",
    )


def reconstruct_path(leaf: Warrant, lookup: dict[str, Warrant]) -> list[Warrant]:
    """Walk parent hashes to a trusted root. Raise on any truncation."""
    path = [leaf]
    current = leaf
    while current.parent is not None:
        _verify_signature(current)
        parent = lookup.get(current.parent)
        if parent is None:
            raise WarrantChainError(
                f"dangling parent hash {current.parent} at issuer {current.issuer}"
            )
        if not _is_subscope(current.scope, parent.scope):
            raise WarrantChainError(
                f"scope non-monotone: {current.scope!r} not within parent {parent.scope!r}"
            )
        path.append(parent)
        current = parent
    if current.issuer not in ROOT_TRUST_SET:
        raise WarrantChainError(
            f"chain terminates at untrusted issuer {current.issuer} with null parent"
        )
    return path


def effective_scope(leaf: Warrant, lookup: dict[str, Warrant]) -> str:
    path = reconstruct_path(leaf, lookup)
    # Intersection fold; leaf scope is already the narrowest by monotonicity check.
    return path[0].scope


def authorize(leaf: Warrant, requested: str, lookup: dict[str, Warrant]) -> None:
    scope = effective_scope(leaf, lookup)
    if not _is_subscope(requested, scope):
        raise WarrantChainError(
            f"request {requested!r} outside effective path scope {scope!r}"
        )
