# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-hierarchical-summarization-layer-has-crossed-from-lossy-compression-into-irreversible-semantic-collapse.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-hierarchical-summarization-layer-has-crossed-from-lossy-compression-into-irreversible-semantic-collapse.warrant.json
# Markdown SHA-256:   41f98b530c5db429cb4261db7acaefed3625505d05a12709ce73e5a62c62e8c8
# Code AST SHA-256:   286c4a1223ca3d756bb57157db645de5e2c0e1a6bb688e6d40d5f071f5634664
# Verified Classes:   SemanticCollapseError, Node
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

NEGATION_TOKENS = ("not", "prohibited", "must not", "frozen", "blocked", "forbidden", "never")


class SemanticCollapseError(RuntimeError):
    """Raised when a hierarchical merge would drop or invert a constraint edge."""


@dataclass
class Node:
    text: str
    negations: int = 0
    named_entities: int = 0
    polarity: int = 0          # +1 affirmative, -1 prohibition
    pinned: bool = False
    children: list["Node"] = field(default_factory=list)


def _count_negations(text: str) -> int:
    low = text.lower()
    return sum(low.count(tok) for tok in NEGATION_TOKENS)


def merge_children(children: Iterable[Node], candidate_text: str) -> Node:
    children = list(children)
    child_neg = sum(c.negations for c in children)
    child_ent = sum(c.named_entities for c in children)
    child_polarity = {c.polarity for c in children if c.polarity != 0}

    parent = Node(
        text=candidate_text,
        negations=_count_negations(candidate_text),
        named_entities=sum(1 for w in candidate_text.split() if w[:1].isupper()),
        polarity=-1 if _count_negations(candidate_text) else 1,
        children=children,
    )

    # Invariant 1: negations are incompressible; any drop is collapse.
    if parent.negations < child_neg:
        raise SemanticCollapseError(
            f"merge dropped negations: children={child_neg} parent={parent.negations} "
            f"— constraint-bearing content must be pinned, not summarized"
        )

    # Invariant 2: polarity must not invert across the merge boundary.
    if -1 in child_polarity and parent.polarity == 1:
        raise SemanticCollapseError(
            "merge inverted prohibition into affirmation (e.g. 'prohibited' -> 'gated on')"
        )

    # Invariant 3: named-entity retention floor.
    if child_ent > 0 and parent.named_entities / child_ent < 0.8:
        raise SemanticCollapseError(
            f"named-entity retention {parent.named_entities}/{child_ent} below 0.8 floor"
        )

    # Invariant 4: a pinned child may never be re-summarized.
    if any(c.pinned for c in children):
        raise SemanticCollapseError(
            "attempted to re-summarize a pinned node — pin scope must cover node lifetime"
        )

    return parent


def compact(nodes: list[Node]) -> Node:
    for n in nodes:
        if n.negations > 0:
            n.pinned = True  # constraint nodes are incompressible by construction
    try:
        return merge_children(nodes, "Agent is coordinating a production migration.")
    except SemanticCollapseError:
        # Correct response: pin and retain verbatim, do not fall through to a looser merge.
        raise
