# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-its-own-context-editing-pass-as-a-state-mutation-requiring-a-pre-image-rather-than-as-a-read-only-summarizati.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-its-own-context-editing-pass-as-a-state-mutation-requiring-a-pre-image-rather-than-as-a-read-only-summarizati.warrant.json
# Markdown SHA-256:   0568d48950c1f7bba00099c1934eb93455551c494ae13327389b6a3f12783ac5
# Code AST SHA-256:   278ed5c3ec9b836c89f2fc780d439ca97dce485dde118c5b22254ba62f440deb
# Verified Classes:   ContextEditViolation, Provenance, MemoryItem
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class ContextEditViolation(RuntimeError):
    """Raised when a self-edit would make 'forgotten' indistinguishable from 'unknown'."""


@dataclass
class Provenance:
    """Header attached to post-edit context so the instance can distinguish
    forgotten-but-recoverable state from genuinely-unknown state."""
    preimage_key: str
    pruned_literals: list[str] = field(default_factory=list)
    pinned_literals: dict[str, str] = field(default_factory=dict)


# Literal classes that MUST be pinned rather than lossy-compressed.
PINNED_CLASSES = ("identifier", "path", "schema_field", "numeric_limit", "negative_constraint")


@dataclass
class MemoryItem:
    text: str
    literal_class: str  # one of PINNED_CLASSES, or "narrative"


def self_edit(
    items: list[MemoryItem],
    preimage_store: dict[str, list[MemoryItem]],
    preimage_key: str,
    summarize,
) -> tuple[str, Provenance]:
    """Perform a model-driven compaction pass with the pre-image invariant enforced.

    - Narrative items are eligible for lossy summarization.
    - Pinned-class items are carried verbatim and recorded in the provenance header.
    - The full pre-edit state is written to preimage_store under preimage_key so the
      instance can later recover any pruned literal by addressable lookup.
    """
    pinned: dict[str, str] = {}
    narrative: list[str] = []
    pruned: list[str] = []

    for item in items:
        if item.literal_class in PINNED_CLASSES:
            # Guardrail: pinned content must never enter the lossy path.
            if item.text in pinned:
                raise ContextEditViolation(
                    f"duplicate pinned literal {item.text!r}; ambiguous provenance"
                )
            pinned[item.text] = item.literal_class
        elif item.literal_class == "narrative":
            narrative.append(item.text)
        else:
            raise ContextEditViolation(
                f"unclassified memory item {item.literal_class!r}; "
                "cannot decide pin-vs-prune, refusing destructive edit"
            )

    # Pre-image must be durable BEFORE the destructive edit is committed.
    if preimage_key in preimage_store:
        raise ContextEditViolation(
            f"pre-image key {preimage_key!r} already occupied; "
            "second compaction would overwrite recoverable state"
        )
    preimage_store[preimage_key] = list(items)

    digest = summarize(narrative)
    # Everything dropped from narrative is recoverable via preimage_key.
    pruned = [t for t in narrative if t not in digest]

    header = Provenance(
        preimage_key=preimage_key,
        pruned_literals=pruned,
        pinned_literals=pinned,
    )

    # Invariant check: any pinned literal absent from the post-edit payload
    # means the guardrail leaked and the edit must not be committed.
    post_edit_payload = digest + "\n" + "\n".join(f"{k} :: {v}" for k, v in pinned.items())
    for literal in pinned:
        if literal not in post_edit_payload:
            raise ContextEditViolation(
                f"pinned literal {literal!r} missing from post-edit context; "
                "would collapse forgotten into unknown"
            )

    return post_edit_payload, header


def recover(header: Provenance, literal: str, preimage_store: dict[str, list[MemoryItem]]) -> MemoryItem:
    """Addressable lookup so the instance can resolve 'forgotten' without re-deriving."""
    if literal in header.pinned_literals:
        return MemoryItem(text=literal, literal_class=header.pinned_literals[literal])
    if literal not in header.pruned_literals:
        raise ContextEditViolation(
            f"{literal!r} not in provenance; instance has no basis to claim it was forgotten"
        )
    preimage = preimage_store.get(header.preimage_key)
    if preimage is None:
        raise ContextEditViolation(
            f"pre-image {header.preimage_key!r} evicted; forgotten state is now unrecoverable"
        )
    for item in preimage:
        if item.text == literal:
            return item
    raise ContextEditViolation(f"provenance claims {literal!r} was pruned but pre-image lacks it")
