# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-warrant-whose-credential-binding-drifted-across-a-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-warrant-whose-credential-binding-drifted-across-a-handoff.warrant.json
# Markdown SHA-256:   e4867448768fb02b7b23d3c7a341b8d61a7b5860410d42c0cde0587414b3540b
# Code AST SHA-256:   dfaca15ce85e87767aace0e8650ccbf7ec104ed0466464261727a5defb60f8bf
# Verified Classes:   BindingDriftError, PinnedDocument
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class BindingDriftError(RuntimeError):
    """Raised when a delegated warrant's subject binding cannot be pinned
    to a single identity-document snapshot consistent across the chain."""
    pass


@dataclass(frozen=True)
class PinnedDocument:
    did: str
    version_id: str
    # thumbprint -> is_primary
    verification_methods: dict
    snapshot_hash: str


def pin_document(did: str, resolver) -> PinnedDocument:
    """Resolve once and pin. Must return a versioned document or refuse."""
    doc = resolver.resolve_versioned(did)
    if doc is None or doc.get("versionId") is None:
        raise BindingDriftError(
            f"cannot pin identity document for {did}: resolver returned "
            f"unversioned state; live resolution is not attributable-safe"
        )
    methods = {
        vm["thumbprint"]: bool(vm.get("primary", False))
        for vm in doc.get("verificationMethod", [])
        if not vm.get("deactivated", False)
    }
    canonical = repr(sorted(methods.items())).encode()
    return PinnedDocument(
        did=did,
        version_id=doc["versionId"],
        verification_methods=methods,
        snapshot_hash=hashlib.sha256(canonical).hexdigest(),
    )


def verify_delegated_chain(
    warrants: list,
    resolver,
    attributable: bool,
) -> str:
    """Verify a delegated warrant chain under binding-continuity rules.

    Returns the pinned snapshot hash to persist with the execution record.
    Refuses (raises) when binding continuity cannot be established.
    """
    if not warrants:
        raise BindingDriftError("empty warrant chain")

    pinned = {}
    for i, w in enumerate(warrants):
        issuer = w["iss"]
        if issuer not in pinned:
            pinned[issuer] = pin_document(issuer, resolver)

    for i in range(1, len(warrants)):
        prev, cur = warrants[i - 1], warrants[i]
        # Continuity: cur.iss must equal prev.sub
        if cur["iss"] != prev["sub"]:
            raise BindingDriftError(
                f"hop {i}: issuer {cur['iss']} != prior subject {prev['sub']}"
            )
        doc = pinned[cur["iss"]]
        thumb = prev.get("cnf", {}).get("thumbprint")
        if thumb is None:
            raise BindingDriftError(f"hop {i}: prior warrant lacks cnf binding")
        if thumb not in doc.verification_methods:
            raise BindingDriftError(
                f"hop {i}: cnf thumbprint {thumb} absent from pinned "
                f"snapshot of {doc.did}@{doc.version_id}"
            )
        if not doc.verification_methods[thumb]:
            # Present but superseded: the drift window. Refuse for
            # attributable actions; the old key may belong to a retired
            # instance of the same DID.
            if attributable:
                raise BindingDriftError(
                    f"hop {i}: cnf thumbprint {thumb} is non-primary in "
                    f"{doc.did}@{doc.version_id}; binding drift across "
                    f"handoff — re-mint required"
                )

    # Persist the union of snapshot hashes as the attribution record.
    combined = hashlib.sha256(
        "|".join(sorted(p.snapshot_hash for p in pinned.values())).encode()
    ).hexdigest()
    return combined
