# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-manifest-s-provenance-chain-has-been-silently-re-rooted-before-signature-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-manifest-s-provenance-chain-has-been-silently-re-rooted-before-signature-verification.warrant.json
# Markdown SHA-256:   9c0db1ff50e83c1d6eec88080feebd55ec958a50afe9cdb56ec0e90b36d9eeb4
# Code AST SHA-256:   eeac1c1d0f371b3a07a036194e7b7181f26dad73ef162bf30c2fa8f0f95c5b73
# Verified Classes:   ProvenanceReRootedError, ChainNode
# Defensive Guards:   10 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceReRootedError(RuntimeError):
    """Raised when a manifest chain is locally signed but not rooted at the pinned key."""
    pass


@dataclass
class ChainNode:
    pubkey: str
    parent: str | None
    parent_signature: str | None
    signed_at: int


def verify_provenance_chain(
    nodes: list[ChainNode],
    pinned_root_pubkey: str,
    max_depth: int = 5,
) -> str:
    """
    Walk a manifest's ancestry and confirm every hop is parent-signed
    and the chain terminates exactly at the out-of-band pinned root.
    Returns the verified skill signer pubkey on success.
    """
    if not nodes:
        raise ProvenanceReRootedError("empty chain: nothing to verify")

    by_pubkey = {n.pubkey: n for n in nodes}
    if len(by_pubkey) != len(nodes):
        raise ProvenanceReRootedError("duplicate pubkey in chain: ambiguous ancestry")

    # Identify the leaf: the node no other node claims as parent.
    claimed_parents = {n.parent for n in nodes if n.parent}
    leaves = [n for n in nodes if n.pubkey not in claimed_parents]
    if len(leaves) != 1:
        raise ProvenanceReRootedError(
            f"expected exactly one leaf, found {len(leaves)}: chain is forked or cyclic"
        )

    current = leaves[0]
    depth = 0
    visited: set[str] = set()

    while True:
        if current.pubkey in visited:
            raise ProvenanceReRootedError("cycle detected in ancestry walk")
        visited.add(current.pubkey)
        depth += 1
        if depth > max_depth:
            raise ProvenanceReRootedError(
                f"chain depth {depth} exceeds max {max_depth}: possible buried re-root"
            )

        if current.parent is None:
            # Terminal node: must be the pinned root, and must be self-consistent.
            if current.pubkey != pinned_root_pubkey:
                raise ProvenanceReRootedError(
                    f"chain terminated at {current.pubkey!r}, "
                    f"not pinned root {pinned_root_pubkey!r}: re-rooted"
                )
            return leaves[0].pubkey

        # Non-terminal: every hop must carry a parent signature.
        if not current.parent_signature:
            raise ProvenanceReRootedError(
                f"node {current.pubkey!r} names parent {current.parent!r} "
                f"but carries no parent_signature: ancestry is asserted, not proven"
            )

        parent_node = by_pubkey.get(current.parent)
        if parent_node is None:
            raise ProvenanceReRootedError(
                f"node {current.pubkey!r} references unknown parent {current.parent!r}"
            )
        if parent_node.signed_at > current.signed_at:
            raise ProvenanceReRootedError(
                f"parent {parent_node.pubkey!r} signed after child "
                f"{current.pubkey!r}: retroactive re-parent"
            )

        current = parent_node


def load_third_party_skill(manifest: dict, pinned_root: str) -> str:
    nodes = [
        ChainNode(
            pubkey=n["pubkey"],
            parent=n.get("parent"),
            parent_signature=n.get("parent_signature"),
            signed_at=n["signed_at"],
        )
        for n in manifest["chain"]
    ]
    signer = verify_provenance_chain(nodes, pinned_root)
    digest = hashlib.sha256(manifest["skill_bytes"]).hexdigest()
    if digest != manifest["skill_digest"]:
        raise ProvenanceReRootedError("skill digest mismatch after chain verification")
    return signer
