# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-and-the-rewrite-silently-invalidates-the-invariants-it-was-meant-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-and-the-rewrite-silently-invalidates-the-invariants-it-was-meant-to-preserve.warrant.json
# Markdown SHA-256:   b0d5977b1c4239839f17c199a2f1a796fde31d65bb2748dced9f515bf08d0b11
# Code AST SHA-256:   7baa990b9b9e5969e0039c3028822e4f601d16e167fda50a82b6b5568a841a1d
# Verified Classes:   InvariantViolation, ProtectedSpan, FrozenInvariants, ContextPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class InvariantViolation(RuntimeError):
    """Raised when a self-authored context-policy rewrite fails preservation
    against the frozen pre-rewrite invariant set."""


@dataclass(frozen=True)
class ProtectedSpan:
    span_id: str
    content_hash: str
    modality: str  # "PROHIBIT" | "REQUIRE" | "PERMIT" | "FACT"


@dataclass(frozen=True)
class FrozenInvariants:
    """Derived from P0. Read-only for the duration of any rewrite."""
    protected: tuple[ProtectedSpan, ...]
    class_map: dict[str, str]  # P0 class -> P1 class, externally supplied

    def digest(self) -> str:
        h = hashlib.sha256()
        for s in sorted(self.protected, key=lambda x: x.span_id):
            h.update(f"{s.span_id}:{s.content_hash}:{s.modality}".encode())
        for k in sorted(self.class_map):
            h.update(f"{k}->{self.class_map[k]}".encode())
        return h.hexdigest()


@dataclass
class ContextPolicy:
    name: str
    retained: set[str] = field(default_factory=set)
    summarizer: Callable[[str], str] | None = None
    # NOTE: intentionally NO self-declared protected_classes field.
    # A policy that can declare its own protected set can weaken it.


def _recover_span(span: ProtectedSpan, policy: ContextPolicy) -> str | None:
    if span.span_id not in policy.retained:
        return None
    text = policy.retained_text.get(span.span_id, "")
    return policy.summarizer(text) if policy.summarizer else text


def _modality_preserved(original: ProtectedSpan, recovered: str | None) -> bool:
    if recovered is None:
        return False
    markers = {
        "PROHIBIT": ("never", "must not", "forbidden", "do not"),
        "REQUIRE": ("must", "required", "always"),
        "PERMIT": ("may", "allowed"),
        "FACT": ("is", "was", "has"),
    }
    return any(m in recovered.lower() for m in markers[original.modality])


def accept_rewrite(
    p0: ContextPolicy,
    p1: ContextPolicy,
    frozen: FrozenInvariants,
    checkpoint_written: bool,
) -> None:
    if not checkpoint_written:
        raise InvariantViolation(
            "pre-rewrite checkpoint missing; a rewrite accepted without a "
            "P0-state checkpoint cannot be replayed or rolled back"
        )

    for span in frozen.protected:
        recovered = _recover_span(span, p1)
        if recovered is None:
            raise InvariantViolation(
                f"P0-protected span {span.span_id} ({span.modality}) evicted "
                f"under rewrite {p1.name}; class_map={frozen.class_map}"
            )
        if not _modality_preserved(span, recovered):
            raise InvariantViolation(
                f"span {span.span_id} retained but modality {span.modality} "
                f"lost under {p1.name}: recovered={recovered!r}"
            )

    # The check consulted only `frozen`, never p1's self-declared claims.
    p1.retained_text = getattr(p1, "retained_text", {})
