# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-graph-contamination-when-a-context-segment-inherits-a-forged-parent-edge-after-mid-window-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-graph-contamination-when-a-context-segment-inherits-a-forged-parent-edge-after-mid-window-compaction.warrant.json
# Markdown SHA-256:   c35e9b7e11ccd3fc57de29d8264d04b49998624b9518903d468152161872aebf
# Code AST SHA-256:   93fbc1f91fe49ac9770508502c5b9c9cb881b6ef73fc716342f627e95fc8a03f
# Verified Classes:   ProvenanceContaminationError, Segment
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceContaminationError(RuntimeError):
    """Raised when a segment's ancestry cannot justify its content."""
    pass


@dataclass
class Segment:
    seg_id: str
    text: str
    source_class: str          # user | tool | retrieved | distilled | peer
    parent_ids: frozenset
    compaction_input_ids: frozenset = frozenset()  # range actually fed to summarizer
    content_hash: Optional[str] = None
    derivation: str = "exact"  # exact | lossy

    def __post_init__(self):
        if self.content_hash is None:
            self.content_hash = hashlib.sha256(self.text.encode()).hexdigest()


TRUST_RANK = {"user": 0, "tool": 1, "retrieved": 2, "peer": 3, "distilled": 4}


def validate_ancestry(seg: Segment, registry: dict[str, Segment]) -> str:
    """
    Return the trust tier the segment is allowed to claim, or raise on
    content/ancestry disagreement. Trust is the *weakest* class in the
    recorded compaction input range, not the declared parent set.
    """
    if seg.derivation == "exact":
        reconstruction = "".join(registry[p].text for p in sorted(seg.parent_ids))
        recon_hash = hashlib.sha256(reconstruction.encode()).hexdigest()
        if recon_hash != seg.content_hash:
            raise ProvenanceContaminationError(
                f"segment {seg.seg_id}: stored hash {seg.content_hash[:12]} "
                f"!= reconstruction {recon_hash[:12]} from parents {sorted(seg.parent_ids)}"
            )
        contributing = seg.parent_ids
    else:
        # lossy derivation: cannot reconstruct; must bound by recorded input range
        if not seg.compaction_input_ids:
            raise ProvenanceContaminationError(
                f"segment {seg.seg_id}: lossy derivation with no recorded "
                f"compaction_input_ids cannot be trust-bounded"
            )
        contributing = seg.compaction_input_ids

    missing = contributing - set(registry)
    if missing:
        raise ProvenanceContaminationError(
            f"segment {seg.seg_id}: ancestry references unknown segments {sorted(missing)}"
        )

    weakest = max(TRUST_RANK[registry[s].source_class] for s in contributing)
    return next(k for k, v in TRUST_RANK.items() if v == weakest)


def clear_for_privileged_action(seg: Segment, registry: dict[str, Segment],
                                required_tier: str = "user") -> bool:
    tier = validate_ancestry(seg, registry)
    if TRUST_RANK[tier] > TRUST_RANK[required_tier]:
        raise ProvenanceContaminationError(
            f"segment {seg.seg_id}: trust tier '{tier}' insufficient for "
            f"privileged action requiring '{required_tier}'"
        )
    return True
