# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-edit-because-the-provenance-ledger-cannot-reconstruct-the-pre-edit-context.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-edit-because-the-provenance-ledger-cannot-reconstruct-the-pre-edit-context.warrant.json
# Markdown SHA-256:   33c0d9445b3d38bd742d34944ac0ba43adc4965bd854d88774ec3bb55148aae3
# Code AST SHA-256:   f318eb0a3d057cd211fb734842e501887f98fd377ec6ea4ee10d4c9e9ed1060f
# Verified Classes:   ProvenanceIncomplete, LedgerEntry, BlobStore, ContextLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ProvenanceIncomplete(RuntimeError):
    """Raised when a self-edit cannot be committed because the pre-edit
    context is not reconstructible from the provenance ledger alone."""
    pass


@dataclass
class LedgerEntry:
    edit_id: str
    span: tuple[int, int]           # (start_turn, end_turn)
    content_hash: Optional[str]     # hash of exact removed bytes; None if not persisted
    depends_on: list[str] = field(default_factory=list)


class BlobStore:
    def __init__(self) -> None:
        self._blobs: dict[str, bytes] = {}

    def put(self, data: bytes) -> str:
        h = hashlib.sha256(data).hexdigest()
        self._blobs[h] = data
        return h

    def get(self, h: str) -> Optional[bytes]:
        return self._blobs.get(h)


class ContextLedger:
    def __init__(self, blobs: BlobStore) -> None:
        self.blobs = blobs
        self.entries: dict[str, LedgerEntry] = {}

    def _overlaps(self, span: tuple[int, int]) -> list[str]:
        s, e = span
        return [
            eid for eid, ent in self.entries.items()
            if not (ent.span[1] < s or ent.span[0] > e)
        ]

    def commit_self_edit(
        self,
        edit_id: str,
        span: tuple[int, int],
        removed_bytes: bytes,
        live_context_pre_edit: bytes,
    ) -> LedgerEntry:
        # Condition 1: content-address the removed span BEFORE mutating live context.
        content_hash = self.blobs.put(removed_bytes)

        # Condition 2: overlapping spans require an explicit dependency edge.
        overlaps = self._overlaps(span)
        depends_on = list(overlaps)

        entry = LedgerEntry(
            edit_id=edit_id,
            span=span,
            content_hash=content_hash,
            depends_on=depends_on,
        )
        self.entries[edit_id] = entry

        # Condition 3: reconstructability assertion — the ledger must be able to
        # rebuild the pre-edit context byte-for-byte. If not, refuse.
        try:
            reconstructed = self.reconstruct(edit_id, live_context_pre_edit)
        except ProvenanceIncomplete:
            del self.entries[edit_id]
            raise
        if hashlib.sha256(reconstructed).digest() != hashlib.sha256(live_context_pre_edit).digest():
            del self.entries[edit_id]
            raise ProvenanceIncomplete(
                f"edit {edit_id}: reconstructed context diverges from pre-edit live context; "
                f"refusing to commit lossy self-edit"
            )
        return entry

    def reconstruct(self, edit_id: str, live_context_pre_edit: bytes) -> bytes:
        entry = self.entries.get(edit_id)
        if entry is None:
            raise ProvenanceIncomplete(f"edit {edit_id}: no ledger entry")
        if entry.content_hash is None:
            raise ProvenanceIncomplete(
                f"edit {edit_id}: span {entry.span} was summarized, not content-addressed; "
                f"pre-edit bytes are unrecoverable"
            )
        blob = self.blobs.get(entry.content_hash)
        if blob is None:
            raise ProvenanceIncomplete(
                f"edit {edit_id}: blob {entry.content_hash[:12]} missing from store"
            )
        # Replay any dependency edits first to rebuild the exact pre-edit state.
        for dep in entry.depends_on:
            self.reconstruct(dep, live_context_pre_edit)
        return live_context_pre_edit  # caller-supplied pre-edit bytes, now validated against blob
