# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-issues-a-targeted-forget-against-a-provenance-tagged-episodic-store-while-downstream-summaries-still-cite-the-erased-epi.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-issues-a-targeted-forget-against-a-provenance-tagged-episodic-store-while-downstream-summaries-still-cite-the-erased-epi.warrant.json
# Markdown SHA-256:   8b1a0438bab93c547d2e08fde03aff4ea1b8140e7edae9ede36f3f70ca65e028
# Code AST SHA-256:   10a692b984e6b754aaf20a697c9c94c21ae97a13f71ef078f9c8b6f37a412e3f
# Verified Classes:   DanglingProvenanceError, Episode, Summary, ProvenanceTaggedStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DanglingProvenanceError(RuntimeError):
    """Raised when a derived summary cites a tombstoned/absent episode."""


@dataclass
class Episode:
    id: str
    text: str
    content_hash: str
    live: bool = True


@dataclass
class Summary:
    id: str
    text: str
    provenance: list[str]
    source_hashes: dict[str, str] = field(default_factory=dict)
    quarantined: bool = False


class ProvenanceTaggedStore:
    def __init__(self) -> None:
        self.episodes: dict[str, Episode] = {}
        self.summaries: dict[str, Summary] = {}

    def write_episode(self, ep: Episode) -> None:
        self.episodes[ep.id] = ep

    def write_summary(self, s: Summary) -> None:
        # Provenance closure: every cited episode must be live at write time.
        for pid in s.provenance:
            ep = self.episodes.get(pid)
            if ep is None or not ep.live:
                raise DanglingProvenanceError(
                    f"summary {s.id} cites non-live episode {pid}; refusing write"
                )
            s.source_hashes[pid] = ep.content_hash
        self.summaries[s.id] = s

    def forget(self, episode_id: str, *, secret_bearing: bool) -> dict:
        ep = self.episodes.get(episode_id)
        if ep is None or not ep.live:
            return {"deleted": 0, "tombstone": episode_id}

        citing = [s for s in self.summaries.values() if episode_id in s.provenance]
        # Fail closed if reverse index is inconsistent: a citing summary whose
        # source_hashes lack the episode means the index cannot be trusted.
        for s in citing:
            if episode_id not in s.source_hashes:
                raise DanglingProvenanceError(
                    f"reverse index inconsistent for {s.id}; forget aborted"
                )

        ep.live = False
        if secret_bearing:
            # Cascade: secret-bearing summaries cannot be surgically rewritten.
            for s in citing:
                s.quarantined = True
                s.provenance = [p for p in s.provenance if p != episode_id]
        else:
            for s in citing:
                s.provenance = [p for p in s.provenance if p != episode_id]
                if not s.provenance:
                    s.quarantined = True

        # Post-condition: no live summary may cite the tombstone.
        for s in self.summaries.values():
            if episode_id in s.provenance and not s.quarantined:
                raise DanglingProvenanceError(
                    f"forget left dangling tag {episode_id} in {s.id}"
                )
        return {"deleted": 1, "tombstone": episode_id,
                "quarantined": [s.id for s in citing]}

    def read(self, summary_id: str) -> dict:
        s = self.summaries[summary_id]
        intact = all(
            self.episodes.get(p) is not None and self.episodes[p].live
            for p in s.provenance
        )
        if not intact:
            # Never inject a summary with dangling provenance into context.
            raise DanglingProvenanceError(
                f"summary {summary_id} has dangling provenance; veto injection"
            )
        if s.quarantined:
            raise DanglingProvenanceError(
                f"summary {summary_id} is quarantined; not served"
            )
        return {"id": s.id, "text": s.text,
                "provenance_intact": True, "provenance": s.provenance}
