# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-self-pruned-context-window-as-a-lossy-non-invertible-projection-rather-than-a-reversible-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-self-pruned-context-window-as-a-lossy-non-invertible-projection-rather-than-a-reversible-cache.warrant.json
# Markdown SHA-256:   d5911df89260424672ed01f2a755a223ce42e4523d1bb826840747224ecd9e00
# Code AST SHA-256:   0b54ddacfe2fefe1652ac3a05a7841da6138ff95e8f825d2df6b905837658349
# Verified Classes:   UnverifiedProjectionError, ContextEntry, Window
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnverifiedProjectionError(RuntimeError):
    """Raised when an action depends on a value that was rewritten without a surviving provenance pointer."""


@dataclass
class ContextEntry:
    entry_id: str
    literal: Optional[str]          # None once rewritten
    summary: Optional[str]          # set when rewritten
    provenance: Optional[str]       # pointer to durable source; must survive pruning
    is_pointer: bool = False


@dataclass
class Window:
    entries: dict = field(default_factory=dict)

    def rewrite(self, entry_id: str, summary: str, source_ptr: Optional[str]) -> None:
        e = self.entries[entry_id]
        e.literal = None
        e.summary = summary
        e.provenance = source_ptr
        # pointer entry is exempt from relevance scoring; created here explicitly
        if source_ptr is not None:
            self.entries[f"ptr:{entry_id}"] = ContextEntry(
                entry_id=f"ptr:{entry_id}",
                literal=None,
                summary=None,
                provenance=source_ptr,
                is_pointer=True,
            )

    def resolve_literal(self, entry_id: str, fetch) -> str:
        e = self.entries[entry_id]
        if e.literal is not None:
            return e.literal
        if e.provenance is None:
            raise UnverifiedProjectionError(
                f"entry {entry_id} was rewritten with no provenance pointer; "
                f"literal is unrecoverable and must be treated as unknown, not summarized"
            )
        return fetch(e.provenance)


def act_on_value(window: Window, entry_id: str, fetch, action) -> None:
    """Any action depending on a possibly-rewritten value must re-verify the literal first."""
    literal = window.resolve_literal(entry_id, fetch)  # raises if unprovable
    action(literal)
