# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-self-re-summarization-as-a-lossy-operator-rather-than-a-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-self-re-summarization-as-a-lossy-operator-rather-than-a-compaction.warrant.json
# Markdown SHA-256:   c66426ce4a0759b07b4388640245f603c039a38af191de601e2a2ce450fb7735
# Code AST SHA-256:   e3e5dabd3b5fd1da76d8af1c70384b272cc10aaccee76186c68821f418cdbcb7
# Verified Classes:   ContextRewritingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ContextRewritingError(RuntimeError):
    """Raised when a self-summarization would destroy unverifiable information."""


PINNED_FIDELITY = {"exact", "verbatim"}


def re_summarize(
    region: dict,
    source_retained: bool,
    pass_depth: int,
    max_depth: int = 2,
) -> dict:
    """
    Rewrite a context region via model summarization.

    region: {"text": str, "pinned": list[str], "fidelity": str, "source_id": str|None}
    Raises ContextRewritingError if the operation would cross the lossy boundary.
    """
    if region.get("pinned"):
        raise ContextRewritingError(
            f"region contains {len(region['pinned'])} pinned constraint(s); "
            "pinned content must be copied verbatim, never summarized"
        )

    if pass_depth >= max_depth:
        raise ContextRewritingError(
            f"re-summarization depth {pass_depth} >= cap {max_depth}; "
            "re-acquire literals from source instead of summarizing the summary"
        )

    if not source_retained or not region.get("source_id"):
        raise ContextRewritingError(
            "no retained, addressable source for this region; "
            "a summary here would be an unrecoverable commit, not a cache eviction"
        )

    if region.get("fidelity") not in PINNED_FIDELITY and _contains_literals(region["text"]):
        raise ContextRewritingError(
            "unpinned literals detected in a non-exact region; "
            "extract and pin them before summarizing"
        )

    return {
        "text": _summarize(region["text"]),
        "pinned": [],
        "fidelity": "paraphrase",
        "source_id": region["source_id"],
        "pass_depth": pass_depth + 1,
        "authoritative": False,
    }


def _contains_literals(text: str) -> bool:
    import re
    return bool(re.search(r"\b\d{1,3}(\.\d{1,3}){3}\b|\b[0-9a-f]{7,}\b|\b\d+\.\d+\.\d+\b", text))


def _summarize(text: str) -> str:
    # Placeholder for the model-driven rewrite.
    return text
