# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-reversible-context-edit-log-has-silently-become-non-reversible-under-budget-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-reversible-context-edit-log-has-silently-become-non-reversible-under-budget-pressure.warrant.json
# Markdown SHA-256:   10c03e526545ce46c37f743fe1e249b6ca602a6288213539f232ca3c2b75a8fc
# Code AST SHA-256:   70270b45a30f3e6514563a24e174cf6bd7c43ed06edeca3072e08335c4139ff4
# Verified Classes:   NonReversibleLogError, BudgetExhaustedError, LogEntry, ReversibleEditLog
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class NonReversibleLogError(RuntimeError):
    """Raised when an undo is attempted on a log entry whose reconstruction
    payload no longer reproduces the original span (silent lossy downgrade)."""
    pass


class BudgetExhaustedError(RuntimeError):
    """Raised when a fold would require compressing an immutable log payload."""
    pass


@dataclass
class LogEntry:
    edit_id: str
    original_digest: str          # O(1) fidelity witness, immutable partition
    reconstruction: Optional[str]  # verbatim span; None if downgraded
    downgraded: bool = False


@dataclass
class ReversibleEditLog:
    soft_budget: int
    used: int = 0
    immutable: dict = field(default_factory=dict)   # edit_id -> LogEntry (never compressed)
    compressible_content: int = 0                    # ordinary context, may be folded

    def _digest(self, span: str) -> str:
        return hashlib.sha256(span.encode()).hexdigest()

    def append_verbatim(self, edit_id: str, span: str) -> None:
        entry = LogEntry(edit_id, self._digest(span), span)
        # Payload enters immutable partition; NOT counted against compressible pool.
        self.immutable[edit_id] = entry

    def fold_content(self, span_tokens: int, summary_tokens: int) -> None:
        """Budget pressure relieved ONLY by folding content, never the log."""
        projected = self.used - span_tokens + summary_tokens
        if projected > self.soft_budget and self._log_would_need_compression():
            raise BudgetExhaustedError(
                f"fold would require log-payload compression at used={self.used}; "
                "refusing fold to preserve reversibility."
            )
        self.used = projected

    def _log_would_need_compression(self) -> bool:
        # True iff the only way to fit is to touch immutable payloads.
        log_tokens = sum(len(e.reconstruction or "") for e in self.immutable.values())
        return self.used + log_tokens > self.soft_budget

    def undo(self, edit_id: str) -> str:
        entry = self.immutable.get(edit_id)
        if entry is None:
            raise NonReversibleLogError(f"edit {edit_id} not in immutable partition")
        if entry.downgraded or entry.reconstruction is None:
            raise NonReversibleLogError(
                f"edit {edit_id} payload was downgraded; cannot reconstruct original"
            )
        if self._digest(entry.reconstruction) != entry.original_digest:
            # Fidelity witness fails: membership was true but reversal is lossy.
            raise NonReversibleLogError(
                f"edit {edit_id} digest mismatch: log claims reversible, is not"
            )
        return entry.reconstruction


def attempt_budget_compression(log: ReversibleEditLog, edit_id: str) -> None:
    """The exact forbidden move: a budget subroutine rewriting a log payload."""
    entry = log.immutable.get(edit_id)
    if entry is None:
        raise NonReversibleLogError(f"edit {edit_id} absent")
    # Simulate the budget-checker "saving space" by abstracting the payload.
    entry.reconstruction = entry.reconstruction[:90] if entry.reconstruction else None
    entry.downgraded = True
    # Note: original_digest is untouched, so the lie is now detectable — but only
    # if undo() checks the digest, which the naive membership test did not.
