# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-rehydrate-compacted-context-the-salience-score-inversion-at-the-eviction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-rehydrate-compacted-context-the-salience-score-inversion-at-the-eviction-boundary.warrant.json
# Markdown SHA-256:   d64efe70cedab796d4fed39079e0fc268babcd4abbba3322e9312614416ee377
# Code AST SHA-256:   f20184d677438b9053ac57a35b127d0be94846bb5760a5e67ef7e77eec4ab055
# Verified Classes:   FrameDriftRehydrationError, Segment, RehydrationRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class FrameDriftRehydrationError(RuntimeError):
    """Raised when rehydration would rank by salience scores computed under a
    frame that differs from the active frame, risking confident wrong-context
    rehydration."""
    pass


@dataclass
class Segment:
    seg_id: str
    content: str
    salience: float                 # computed under `scored_frame`
    scored_frame: str               # fingerprint of frame at eviction time
    referenced_by_plan: bool = False


@dataclass
class RehydrationRequest:
    active_frame: str
    plan_referenced_ids: set
    budget: int
    segments: list = field(default_factory=list)


def frame_fingerprint(intent_label: str, inducing_event_id: str) -> str:
    return hashlib.sha256(f"{intent_label}|{inducing_event_id}".encode()).hexdigest()[:16]


def rehydrate(req: RehydrationRequest, rescore_fn) -> list:
    # Invariant 1: plan-referenced segments are frame-invariant dependencies.
    referenced = [s for s in req.segments if s.seg_id in req.plan_referenced_ids]

    drifting = [s for s in req.segments if s.scored_frame != req.active_frame]

    if drifting and any(s.seg_id in req.plan_referenced_ids for s in drifting):
        # A plan-referenced segment was scored under a foreign frame.
        # Ranking by its stale score would drop it. Refuse to proceed silently.
        stale = [s.seg_id for s in drifting if s.seg_id in req.plan_referenced_ids]
        raise FrameDriftRehydrationError(
            f"plan-referenced segments carry stale-frame salience: {stale}; "
            f"active_frame={req.active_frame}; must re-score before ranking"
        )

    # Invariant 2: never rank drifting segments by persisted score.
    if drifting:
        rescored = []
        for s in req.segments:
            if s.scored_frame == req.active_frame:
                rescored.append((s, s.salience))
            else:
                rescored.append((s, rescore_fn(s, req.active_frame)))
        ranked = sorted(rescored, key=lambda pair: pair[1], reverse=True)
    else:
        ranked = sorted(((s, s.salience) for s in req.segments),
                        key=lambda pair: pair[1], reverse=True)

    # Invariant 3: plan-referenced segments are pinned ahead of the ranked tail.
    pinned_ids = {s.seg_id for s in referenced}
    ordered = referenced + [s for s, _ in ranked if s.seg_id not in pinned_ids]

    selected, used = [], 0
    for s in ordered:
        cost = len(s.content.split())
        if used + cost > req.budget:
            if s.seg_id in pinned_ids:
                raise FrameDriftRehydrationError(
                    f"budget exhausted before pinned segment {s.seg_id}; "
                    f"rehydration cannot satisfy active plan"
                )
            continue
        selected.append(s)
        used += cost
    return selected
