# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-audit-attribution-when-a-delegated-capability-is-re-delegated-across-an-org-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-audit-attribution-when-a-delegated-capability-is-re-delegated-across-an-org-boundary.warrant.json
# Markdown SHA-256:   4ae9e25f782078d3e9259fdf8a71e2a62b146cdf81a21b4447bcfd4083a6a1e1
# Code AST SHA-256:   bed02291fceb09cc80aee8942b4474191d9d700a5dbabb3af14afb07eedd8652
# Verified Classes:   AttributionClosureError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttributionClosureError(RuntimeError):
    """Raised when a warrant chain is valid but its leaf action is unattributable."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_id: Optional[str]
    issuer: str            # principal that minted this warrant
    subject: str           # principal authorized to act
    scope: frozenset
    audience: str
    # Signed pointer to the minting record; None means the minter did not
    # propagate a federated attestation (the failure trigger).
    minting_attestation: Optional[str]


def _verify_signature(w: Warrant) -> bool:
    # Placeholder for real signature verification against issuer key.
    return True


def _scope_attenuates(child: Warrant, parent: Warrant) -> bool:
    return child.scope <= parent.scope


def _resolve_attestation(pointer: str, verifier_org: str) -> bool:
    # Placeholder: fetch signed minting record and verify it names issuer+parent.
    # Returns False if the record is unreachable or does not bind issuer->parent.
    return pointer.startswith(f"https://audit.{verifier_org}/")


def enforce_attribution_closure(
    chain: list[Warrant], verifier_org: str
) -> str:
    """
    Walk a warrant chain leaf->root and enforce attribution closure.
    Returns the accountable root principal. Raises AttributionClosureError
    if any hop's minting event is unreachable by the terminal verifier.
    """
    by_id = {w.warrant_id: w for w in chain}
    leaf = chain[0]

    for w in chain:
        if not _verify_signature(w):
            raise AttributionClosureError(
                f"warrant {w.warrant_id}: signature invalid"
            )
        if w.parent_id is None:
            continue
        parent = by_id.get(w.parent_id)
        if parent is None:
            raise AttributionClosureError(
                f"warrant {w.warrant_id}: parent {w.parent_id} missing from chain"
            )
        if not _scope_attenuates(w, parent):
            raise AttributionClosureError(
                f"warrant {w.warrant_id}: scope not attenuated from parent"
            )
        # The closure check: a non-root minting hop must carry a resolvable,
        # verifier-fetchable attestation. Validity alone is insufficient.
        if w.issuer != parent.subject:
            raise AttributionClosureError(
                f"warrant {w.warrant_id}: issuer {w.issuer} is not the "
                f"parent subject {parent.subject}; minting authority unproven"
            )
        if w.minting_attestation is None:
            raise AttributionClosureError(
                f"warrant {w.warrant_id}: minted by {w.issuer} with no "
                f"attestation; attribution unrecoverable by {verifier_org}"
            )
        if not _resolve_attestation(w.minting_attestation, verifier_org):
            raise AttributionClosureError(
                f"warrant {w.warrant_id}: attestation "
                f"{w.minting_attestation} unresolvable by {verifier_org}"
            )

    root = next(w for w in chain if w.parent_id is None)
    return root.issuer
