# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-the-recovery-pointer-resolves-to-a-summary-of-a-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-the-recovery-pointer-resolves-to-a-summary-of-a-summary.warrant.json
# Markdown SHA-256:   345af4763154d2571e3f6138bfee81c309b5894dddaa13a3d493b5e0b58515e4
# Code AST SHA-256:   0f212805cb1d0975c452a047e2ec7d067ad0b80a39f587881116a2a2a06a2c78
# Verified Classes:   RecoveryPointerViolation, RawSpan, SummaryNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class RecoveryPointerViolation(RuntimeError):
    """Raised when a recovery pointer claims recoverability it cannot honor."""
    pass


@dataclass
class RawSpan:
    span_id: str
    text: str
    def sha(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()


@dataclass
class SummaryNode:
    node_id: str
    text: str
    # leaf pointers: span_ids of raw spans this summary was built from
    source_span_ids: list[str] = field(default_factory=list)
    # child summary nodes folded into this one (re-summarization)
    child_node_ids: list[str] = field(default_factory=list)
    recoverable: bool = True


def deref(
    node: SummaryNode,
    raw_store: dict[str, RawSpan],
    summary_store: dict[str, SummaryNode],
) -> str:
    """
    Dereference a summary node to its raw source.
    Raises if the node is not a leaf-terminating, raw-checksummed pointer.
    """
    if not node.recoverable:
        raise RecoveryPointerViolation(
            f"node {node.node_id} is marked recoverable=false; "
            f"treat as unknown, not summarized"
        )
    if node.child_node_ids:
        # a summary-of-summaries must fan out to child leaves, never
        # claim a flat pointer to a union span
        parts = []
        for cid in node.child_node_ids:
            child = summary_store[cid]
            parts.append(deref(child, raw_store, summary_store))
        return "\n".join(parts)
    # leaf: must resolve to raw spans, and the hash must be over raw bytes
    parts = []
    for sid in node.source_span_ids:
        span = raw_store.get(sid)
        if span is None:
            raise RecoveryPointerViolation(
                f"node {node.node_id} points at evicted span {sid}; "
                f"recoverability frontier shrank — demote to recoverable=false"
            )
        parts.append(span.text)
    return "\n".join(parts)


def resummarize(
    new_id: str,
    children: list[SummaryNode],
    new_text: str,
    raw_store: dict[str, RawSpan],
) -> SummaryNode:
    """
    Fold child summaries into a parent. The parent is a navigation node,
    NOT a recovery guarantee: recoverable is true only if every transitive
    raw span is still in the frontier.
    """
    frontier_ok = True
    for c in children:
        if not c.recoverable:
            frontier_ok = False
            break
        for sid in c.source_span_ids:
            if sid not in raw_store:
                frontier_ok = False
                break
    node = SummaryNode(
        node_id=new_id,
        text=new_text,
        child_node_ids=[c.node_id for c in children],
        recoverable=frontier_ok,
    )
    if not node.recoverable:
        # do not raise here — demotion is the correct, cheap outcome.
        # raise only if a caller later tries to deref it as if recoverable.
        pass
    return node


def safe_deref(node: SummaryNode, raw_store, summary_store) -> str:
    try:
        return deref(node, raw_store, summary_store)
    except RecoveryPointerViolation as e:
        raise RecoveryPointerViolation(
            f"refusing to answer from lossy pointer {node.node_id}: {e}. "
            f"Report 'unknown' and re-derive from tool state, do not invent."
        ) from e
