# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-eviction-eligibility-from-raw-turn-provenance-rather-than-trusting-a-cached-protected-span-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-eviction-eligibility-from-raw-turn-provenance-rather-than-trusting-a-cached-protected-span-manifest.warrant.json
# Markdown SHA-256:   6f03cd77068c9fe2a90283b378055c28baf1b37b35e6343b4ed98991e32f2c56
# Code AST SHA-256:   6a8b6c6fddab316db384221e7429994e6b70eab31446e1bcd7ecd0eee296122a
# Verified Classes:   StaleProtectionManifestError, Turn, ProtectedSpan, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class StaleProtectionManifestError(RuntimeError):
    """Raised when a protected-span manifest no longer aligns with the live buffer."""


@dataclass
class Turn:
    turn_id: str          # immutable identity
    content: str
    generation: int       # bumped on any mutation of this turn


@dataclass
class ProtectedSpan:
    turn_id: str
    content_hash: str     # sha256 of protected bytes at derivation time


@dataclass
class Manifest:
    generation: int
    spans: list[ProtectedSpan] = field(default_factory=list)


def _hash(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def derive_manifest(buffer: list[Turn], protected_ids: set[str]) -> Manifest:
    gen = max((t.generation for t in buffer), default=0)
    spans = [
        ProtectedSpan(turn_id=t.turn_id, content_hash=_hash(t.content))
        for t in buffer
        if t.turn_id in protected_ids
    ]
    return Manifest(generation=gen, spans=spans)


def validate_manifest(manifest: Manifest, buffer: list[Turn]) -> None:
    """Fail closed if the manifest is stale relative to the live buffer."""
    live_gen = max((t.generation for t in buffer), default=0)
    if manifest.generation != live_gen:
        raise StaleProtectionManifestError(
            f"manifest generation {manifest.generation} != buffer generation {live_gen}"
        )
    by_id = {t.turn_id: t for t in buffer}
    for span in manifest.spans:
        turn = by_id.get(span.turn_id)
        if turn is None:
            raise StaleProtectionManifestError(
                f"protected turn {span.turn_id} no longer present in buffer"
            )
        if _hash(turn.content) != span.content_hash:
            raise StaleProtectionManifestError(
                f"protected turn {span.turn_id} content drifted from derivation hash"
            )


def evict(buffer: list[Turn], manifest: Manifest, protected_ids: set[str],
          target_tokens: int, token_cost) -> tuple[list[Turn], Manifest]:
    """Evict non-protected turns; re-derive manifest if stale. Never evict on a stale manifest."""
    try:
        validate_manifest(manifest, buffer)
    except StaleProtectionManifestError:
        # Re-derive from raw turn provenance before any destructive pass.
        manifest = derive_manifest(buffer, protected_ids)

    survivors: list[Turn] = []
    for turn in buffer:
        if turn.turn_id in protected_ids:
            survivors.append(turn)
        elif token_cost(turn.content) <= target_tokens:
            survivors.append(turn)

    # Any eviction mutates provenance: bump generations and re-derive.
    for t in survivors:
        t.generation += 1
    manifest = derive_manifest(survivors, protected_ids)
    return survivors, manifest
