# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-pairwise-did-handshake-predicate-witness-divergence-and-the-unlinkable-identity-trap-in-federated-agent-identity-resolu.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-pairwise-did-handshake-predicate-witness-divergence-and-the-unlinkable-identity-trap-in-federated-agent-identity-resolu.warrant.json
# Markdown SHA-256:   f872b72f3191b76c5cb8a926cb1fd23a895ec255a3250b41e981fdc82bbc2943
# Code AST SHA-256:   592e42c57629254a2e3c444aa641510458554e09831985f87324dae4a94bd623
# Verified Classes:   PredicateWitnessDivergence, PolicyClause, DisclosedProjection
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet, Mapping


class PredicateWitnessDivergence(RuntimeError):
    """Raised when disclosed fields underdetermine the verifier's policy clause
    under pairwise pseudonymity, making the mismatch undetectable post-hoc."""
    pass


@dataclass(frozen=True)
class PolicyClause:
    required_scope: FrozenSet[str]
    issuer_class_required: bool


@dataclass(frozen=True)
class DisclosedProjection:
    fields: Mapping[str, str]          # what the prover actually revealed
    bucket_map: Mapping[str, FrozenSet[str]]  # scope_class -> scope set, per issuer class
    issuer_class_commitment: str | None  # session-scoped hash, not the issuer DID


def enforce_clause_identity(
    clause: PolicyClause,
    disclosed: DisclosedProjection,
    accepted_issuer_classes: FrozenSet[str],
) -> None:
    # Reconstruct the policy clause from disclosed fields alone.
    scope_class = disclosed.fields.get("scope_class")
    if scope_class is None:
        raise PredicateWitnessDivergence(
            "policy consumes scope but prover disclosed no scope_class; "
            "witness withheld and unlinkable — cannot reconstruct clause"
        )

    preimage = disclosed.bucket_map.get(scope_class)
    if preimage is None:
        raise PredicateWitnessDivergence(
            f"scope_class={scope_class!r} has no bucket preimage; "
            "disclosure lattice coarser than policy lattice"
        )

    # Injectivity check on the policy decision boundary: the bucket must
    # determine the required scope set exactly, for every accepted issuer class.
    if clause.issuer_class_required and disclosed.issuer_class_commitment is None:
        raise PredicateWitnessDivergence(
            "policy is issuer-class-sensitive but issuer_linkage withheld; "
            "bucket map is many-to-one across accepted issuers — refuse"
        )

    if not clause.required_scope.issubset(preimage):
        raise PredicateWitnessDivergence(
            f"bucket {scope_class!r} preimage {sorted(preimage)} does not "
            f"contain required scope {sorted(clause.required_scope)}; "
            "prover proved a weaker clause than policy consumes"
        )

    # Bind the reconstructed clause into the challenge so the SD proof is
    # checked against C_v, not against the prover's C_p.
    challenge = hashlib.sha256(
        repr(sorted(clause.required_scope)).encode()
        + (disclosed.issuer_class_commitment or "").encode()
    ).hexdigest()
    disclosed.fields["__challenge__"] = challenge


def handshake(clause: PolicyClause, disclosed: DisclosedProjection,
              accepted: FrozenSet[str]) -> str:
    enforce_clause_identity(clause, disclosed, accepted)
    return disclosed.fields["__challenge__"]
