# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconstruct-provenance-when-an-a2a-handoff-chain-is-cryptographically-valid-but-semantically-severed-at-a-lossy-summarization-b.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconstruct-provenance-when-an-a2a-handoff-chain-is-cryptographically-valid-but-semantically-severed-at-a-lossy-summarization-b.warrant.json
# Markdown SHA-256:   001fa01b44e2d2637eee1df45dabd6742218f42236bd893482fd2dddec8ede58
# Code AST SHA-256:   604ccfcba92e67b75a3c2afe77937e71309ff027f5250ba6457d25421b7bb7eb
# Verified Classes:   TransformKind, AttributionError, Binding, Envelope
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TransformKind(Enum):
    VERBATIM = "verbatim"
    NUMERIC_NORMALIZATION = "numeric_normalization"
    PARAPHRASE = "paraphrase"
    SYNTHESIS = "synthesis"  # no single source; requires explicit multi_source


class AttributionError(RuntimeError):
    """Raised when a provenance chain is integrity-valid but attribution-insufficient."""


@dataclass
class Binding:
    claim_id: str
    source_ref: Optional[str]          # record id / receipt hash / span offset
    transform: TransformKind
    multi_source: tuple[str, ...] = field(default_factory=tuple)


@dataclass
class Envelope:
    envelope_id: str
    parents: tuple[str, ...]
    signature_ok: bool
    payload_contains_tainted_span: bool
    bindings: dict[str, Binding] = field(default_factory=dict)  # claim_id -> Binding


def validate_edge_admissible(env: Envelope, claims_in_payload: set[str]) -> None:
    """
    A lossy hop is admissible as forensic evidence only if every atomic claim
    in its payload has a binding with a declared transform kind, and any
    'synthesis' binding carries an explicit multi_source set.
    """
    if not env.signature_ok:
        raise AttributionError(f"envelope {env.envelope_id}: signature invalid")

    missing = claims_in_payload - set(env.bindings.keys())
    if missing:
        raise AttributionError(
            f"envelope {env.envelope_id}: provenance hole — claims {sorted(missing)} "
            f"have no discriminator binding; chain is integrity-valid but "
            f"attribution-insufficient at this hop"
        )

    for claim_id in claims_in_payload:
        b = env.bindings[claim_id]
        if b.transform is TransformKind.SYNTHESIS and not b.multi_source:
            raise AttributionError(
                f"envelope {env.envelope_id}: claim {claim_id} tagged synthesis "
                f"with no multi_source set — unattributable by construction"
            )
        if b.transform is not TransformKind.SYNTHESIS and not b.source_ref:
            raise AttributionError(
                f"envelope {env.envelope_id}: claim {claim_id} transform "
                f"{b.transform.value} requires a source_ref, got None"
            )


def attribute_tainted_span(
    chain: list[Envelope], tainted_claim_id: str
) -> tuple[str, str]:
    """
    Walk terminal->root, resolve the claim's binding, and return
    (verdict, accountable_envelope_id_or_UNDETERMINED).
    Verdict is one of: DETERMINATE, PROBABILISTIC, UNATTRIBUTABLE.
    """
    for env in reversed(chain):
        if tainted_claim_id not in env.bindings:
            continue
        b = env.bindings[tainted_claim_id]
        if b.transform in (TransformKind.VERBATIM, TransformKind.NUMERIC_NORMALIZATION):
            return ("DETERMINATE", env.envelope_id)
        if b.transform is TransformKind.PARAPHRASE:
            # semantic-diff required; never collapse to a binary here
            return ("PROBABILISTIC", env.envelope_id)
        if b.transform is TransformKind.SYNTHESIS:
            if not b.multi_source:
                raise AttributionError(
                    f"claim {tainted_claim_id}: synthesis binding at "
                    f"{env.envelope_id} lacks multi_source; refusing to "
                    f"fabricate a determinate attribution"
                )
            return ("UNATTRIBUTABLE", "MULTI_SOURCE_SET")

    # No binding anywhere in the chain: this is the failure the article warns about.
    raise AttributionError(
        f"claim {tainted_claim_id}: no discriminator binding found in chain "
        f"of {len(chain)} envelopes — chain is integrity-valid but "
        f"attribution-insufficient; verdict must be UNATTRIBUTABLE, not "
        f"'nearest upstream envelope'"
    )
