# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-silently-deleting-the-only-copy-of-a-live-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-silently-deleting-the-only-copy-of-a-live-obligation.warrant.json
# Markdown SHA-256:   ae9cd0284a3ec545e5e0ab1f22311f4c73752fd791d744fd344ad4852b76273b
# Code AST SHA-256:   6fedae63d1a0b1877fd6f99b06d6269e79687c31c5e694bf992e5f1bbe42a77a
# Verified Classes:   ObligationLaunderingError, ObligationState, Obligation, Leaf, ParentSummary, ObligationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ObligationLaunderingError(RuntimeError):
    """Raised when a compaction would drop or paraphrase an open obligation."""
    pass


class ObligationState(Enum):
    OPEN = "open"
    RESOLVED = "resolved"


@dataclass
class Obligation:
    obligation_id: str
    text: str                      # verbatim, never paraphrased
    state: ObligationState = ObligationState.OPEN
    pinned_leaf: Optional[str] = None


@dataclass
class Leaf:
    leaf_id: str
    obligation_ids: list[str] = field(default_factory=list)


@dataclass
class ParentSummary:
    parent_id: str
    source_leaf_ids: list[str]
    carried_obligations: list[str] = field(default_factory=list)
    contains_open_obligation: bool = False


class ObligationLedger:
    def __init__(self) -> None:
        self._obligations: dict[str, Obligation] = {}

    def open(self, obligation_id: str, text: str, leaf_id: str) -> None:
        self._obligations[obligation_id] = Obligation(
            obligation_id=obligation_id, text=text, pinned_leaf=leaf_id
        )

    def resolve(self, obligation_id: str) -> None:
        if obligation_id not in self._obligations:
            raise ObligationLaunderingError(
                f"cannot resolve unknown obligation {obligation_id}"
            )
        self._obligations[obligation_id].state = ObligationState.RESOLVED

    def open_for_leaves(self, leaf_ids: list[str]) -> list[Obligation]:
        return [
            o for o in self._obligations.values()
            if o.state is ObligationState.OPEN and o.pinned_leaf in leaf_ids
        ]


MAX_PIN_DEPTH = 3


def compact(
    leaf_ids: list[str],
    leaves: dict[str, Leaf],
    ledger: ObligationLedger,
    summarizer,
    pin_depth: int = 0,
) -> ParentSummary:
    open_obls = ledger.open_for_leaves(leaf_ids)

    if open_obls and pin_depth >= MAX_PIN_DEPTH:
        # Escape valve: reduce to pointers, never prose retelling.
        summary = ParentSummary(
            parent_id=f"P-{'-'.join(leaf_ids)}",
            source_leaf_ids=list(leaf_ids),
            carried_obligations=[o.obligation_id for o in open_obls],
            contains_open_obligation=True,
        )
        return summary

    if open_obls:
        # Promote verbatim; do not let the summarizer paraphrase.
        summary = ParentSummary(
            parent_id=f"P-{'-'.join(leaf_ids)}",
            source_leaf_ids=list(leaf_ids),
            carried_obligations=[o.obligation_id for o in open_obls],
            contains_open_obligation=True,
        )
        # Summarizer output is accepted ONLY for the non-obligation portion.
        summarizer(leaf_ids, exclude_obligations=[o.obligation_id for o in open_obls])
        return summary

    return ParentSummary(
        parent_id=f"P-{'-'.join(leaf_ids)}",
        source_leaf_ids=list(leaf_ids),
        carried_obligations=[],
        contains_open_obligation=False,
    )


def evict(leaf_ids: list[str], ledger: ObligationLedger) -> None:
    open_obls = ledger.open_for_leaves(leaf_ids)
    if open_obls:
        raise ObligationLaunderingError(
            "refusing to evict leaves carrying open obligations: "
            + ", ".join(o.obligation_id for o in open_obls)
        )
    # eviction proceeds only when ledger reports zero open obligations
