# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-hierarchical-compaction-has-silently-inverted-its-own-evidence-hierarchy.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-hierarchical-compaction-has-silently-inverted-its-own-evidence-hierarchy.warrant.json
# Markdown SHA-256:   2005cd3d4c32e51f5fa01ffc57441708113a6b2d731c9bd9e58d8bbeb77fb121
# Code AST SHA-256:   20d4ab7169befa3cfe730deffb3a10153cc2de68f23108bc4e6a813092e303ac
# Verified Classes:   HierarchyInversionError, Tier, Node, Claim
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum
from typing import Optional


class HierarchyInversionError(RuntimeError):
    """Raised when a summary node outranks or overrides its own supporting evidence."""
    pass


class Tier(IntEnum):
    SPAN = 0     # raw evidence
    MID = 1      # tier-1 summary
    ROOT = 2     # tier-2 summary


@dataclass
class Node:
    node_id: str
    tier: Tier
    text: str
    supports: list[str]          # span ids this node was distilled from
    resolves_ambiguity: bool      # did the summarizer resolve what the source left open?


@dataclass
class Claim:
    text: str
    grounded_in: str              # node_id
    is_causal_or_temporal: bool


def verify_claim(claim: Claim, nodes: dict[str, Node],
                 descent: dict[str, Optional[str]]) -> None:
    """
    Enforce: a summary may locate evidence but never conclude over it.
    `descent` maps node_id -> resolved tier-0 span text (or None if unresolvable).
    """
    node = nodes[claim.grounded_in]

    # Invariant 1: causal/temporal claims require tier-0 support.
    if claim.is_causal_or_temporal and node.tier != Tier.SPAN:
        span_text = descent.get(node.node_id)
        if span_text is None:
            raise HierarchyInversionError(
                f"Claim '{claim.text}' is causal/temporal but grounded only in "
                f"tier-{node.tier.name} node {node.node_id} with no resolvable span."
            )
        # Invariant 2: the summary must not have resolved source ambiguity.
        if node.resolves_ambiguity:
            raise HierarchyInversionError(
                f"Node {node.node_id} resolved ambiguity absent from span; "
                f"summary authority exceeds source for claim '{claim.text}'."
            )

    # Invariant 3: a non-span node must have provenance to every child it stands for.
    if node.tier != Tier.SPAN and not node.supports:
        raise HierarchyInversionError(
            f"Node {node.node_id} at tier {node.tier.name} has no span provenance; "
            f"cannot certify monotone authority for '{claim.text}'."
        )


def assert_monotone_ranking(query: str, scores: dict[str, float],
                            nodes: dict[str, Node]) -> None:
    """A parent may not outrank the strongest child that directly answers the query."""
    for node in nodes.values():
        if node.tier == Tier.SPAN:
            continue
        parent_score = scores.get(node.node_id, 0.0)
        for child_id in node.supports:
            child_score = scores.get(child_id, 0.0)
            if parent_score > child_score:
                raise HierarchyInversionError(
                    f"Hierarchy inversion on query '{query}': parent {node.node_id} "
                    f"({parent_score:.3f}) outranks supporting span {child_id} "
                    f"({child_score:.3f}). Rebuild with tier-normalized scoring."
                )
