# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-unverified-skill-provenance-chain-in-third-party-agent-marketplaces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-unverified-skill-provenance-chain-in-third-party-agent-marketplaces.warrant.json
# Markdown SHA-256:   61229030cc41f6a42dcecc75640f3f25e3ef083623ca7d85b647ed4b89508d6b
# Code AST SHA-256:   30fa8ebe0f4f9f09fa9952f401bbf356eeac88e508dbe6ffafc4406292389106
# Verified Classes:   ProvenanceChainError, Cert
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceChainError(RuntimeError):
    """Raised when a skill provenance chain cannot be verified structurally."""


@dataclass(frozen=True)
class Cert:
    subject: str
    issuer: str
    parent_fingerprint: str  # SHA-256 of parent cert bytes, committed in payload
    scopes: frozenset
    signed_at: int
    epoch: int


def fingerprint(cert: Cert) -> str:
    payload = f"{cert.subject}|{cert.issuer}|{cert.parent_fingerprint}|{sorted(cert.scopes)}|{cert.signed_at}|{cert.epoch}"
    return hashlib.sha256(payload.encode()).hexdigest()


def verify_chain(
    root: Cert,
    leaf_signer_fingerprint: str,
    candidate_certs: dict,  # fingerprint -> Cert, supplied by marketplace
    pinned_revocation_epoch: int,
    max_depth: int,
) -> frozenset:
    """Reconstruct the path from root by parent_fingerprint commitment and
    return the intersected effective scope. Rejects any chain whose links do
    not commit to their parent, exceed depth, or postdate revocation."""
    if root.parent_fingerprint != "":
        raise ProvenanceChainError("root cert must not declare a parent")

    effective_scope = root.scopes
    current = root
    depth = 0
    seen = {fingerprint(root)}

    while True:
        depth += 1
        if depth > max_depth:
            raise ProvenanceChainError(
                f"chain depth {depth} exceeds max_depth {max_depth}"
            )
        if current.epoch > pinned_revocation_epoch:
            raise ProvenanceChainError(
                f"cert {current.subject} epoch {current.epoch} postdates "
                f"pinned revocation epoch {pinned_revocation_epoch}"
            )

        # Leaf reached: the artifact signer must equal the last cert's subject
        # fingerprint we committed to, not a self-declared field.
        if fingerprint(current) == leaf_signer_fingerprint:
            return effective_scope

        # Walk forward by finding a cert that commits to *this* cert as parent.
        next_cert = None
        for fp, cert in candidate_certs.items():
            if cert.parent_fingerprint == fingerprint(current):
                if next_cert is not None:
                    raise ProvenanceChainError(
                        f"ambiguous successors for {current.subject}: "
                        f"{next_cert.subject} vs {cert.subject}"
                    )
                next_cert = cert

        if next_cert is None:
            raise ProvenanceChainError(
                f"no cert commits to parent {current.subject}; "
                f"chain is truncated or reordered"
            )
        if fingerprint(next_cert) in seen:
            raise ProvenanceChainError("cycle detected in provenance chain")
        seen.add(fingerprint(next_cert))

        # Scope intersection, never union.
        effective_scope = effective_scope & next_cert.scopes
        if not effective_scope:
            raise ProvenanceChainError(
                f"scope intersection empty at {next_cert.subject}; "
                f"delegation grants nothing"
            )
        current = next_cert
