# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-to-preserve-the-provenance-invariant-across-pruning-and-re-summarization.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-to-preserve-the-provenance-invariant-across-pruning-and-re-summarization.warrant.json
# Markdown SHA-256:   050730aff2a3e7d75193d000e497bb4d2fa1b16a7464fd5db55a88306ed1dce8
# Code AST SHA-256:   65610634c1fd4068ecc525d4298254b40e36bceffdd1cdddebda69adb429c621
# Verified Classes:   Provenance, Span, Claim, ProvenanceViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class Provenance(IntEnum):
    ASSUMED = 0
    DERIVED = 1
    OBSERVED = 2


@dataclass
class Span:
    span_id: str
    text: str
    provenance: Provenance


@dataclass
class Claim:
    text: str
    source_span_ids: list[str] = field(default_factory=list)


class ProvenanceViolation(RuntimeError):
    """Raised when a model-driven rewrite would launder provenance."""


def _join(classes: list[Provenance]) -> Provenance:
    if not classes:
        return Provenance.ASSUMED
    return Provenance(min(int(c) for c in classes))


def validate_rewrite(
    input_spans: list[Span],
    output_claims: list[Claim],
    *,
    validator,
    spans_garbage_collected: bool = False,
) -> Provenance:
    """
    Enforce: class(rewrite) == weakest-link join of inputs, AND every claim
    is attributed to a real input span that entails it.

    `validator(claim_text, span_text) -> bool` is the entailment check.
    """
    by_id = {s.span_id: s for s in input_spans}

    # Clause 1: the rewrite's own class is the join of its inputs.
    rewrite_class = _join([s.provenance for s in input_spans])

    # Clause 2: claim-level attribution. No claim may float free.
    for claim in output_claims:
        if not claim.source_span_ids:
            if any(s.provenance == Provenance.OBSERVED for s in input_spans):
                raise ProvenanceViolation(
                    f"unattributed claim over OBSERVED spans: {claim.text!r}"
                )
            continue
        for sid in claim.source_span_ids:
            span = by_id.get(sid)
            if span is None:
                raise ProvenanceViolation(
                    f"claim cites nonexistent span {sid!r} (GC'd or fabricated)"
                )
            if not validator(claim.text, span.text):
                raise ProvenanceViolation(
                    f"claim not entailed by cited span {sid!r}: {claim.text!r}"
                )
            # A claim cannot be stronger than its cited evidence.
            if span.provenance < rewrite_class:
                rewrite_class = span.provenance

    # Clause 3: once source spans are gone, the summary is unverifiable.
    if spans_garbage_collected and rewrite_class > Provenance.DERIVED:
        raise ProvenanceViolation(
            "cannot retain OBSERVED class after source spans are garbage-collected; "
            "demote to DERIVED and flag evidence loss"
        )

    return rewrite_class
