# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-irreducible-witness-boundary-in-long-horizon-agent-context-management.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-irreducible-witness-boundary-in-long-horizon-agent-context-management.warrant.json
# Markdown SHA-256:   6a50d5261c77eb000e42f4210a3b3faf18499dad19515f1437d0cf879df54bef
# Code AST SHA-256:   dbc15749e05e24004f660678f05196b221a03fc7be170585ac992f9c880fd853
# Verified Classes:   CompactionRefused, RegionKind, Region, Claim, CompactionPlan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class CompactionRefused(RuntimeError):
    """Raised when compaction would strip the witness behind a live claim."""


class RegionKind(Enum):
    RECONSTRUCTIBLE = "reconstructible"
    WITNESS_BEARING = "witness_bearing"
    AMBIGUOUS = "ambiguous"  # treated as witness-bearing


@dataclass
class Region:
    kind: RegionKind
    raw: str
    refetch_handle: str | None = None

    def witness_hash(self) -> str:
        return hashlib.sha256(self.raw.encode()).hexdigest()


@dataclass
class Claim:
    text: str
    supported_by: set[int]  # indices into the region list


@dataclass
class CompactionPlan:
    summarise: set[int] = field(default_factory=set)
    pin: set[int] = field(default_factory=set)


def audit_and_compact(
    regions: list[Region],
    live_claims: list[Claim],
    token_budget: int,
) -> CompactionPlan:
    plan = CompactionPlan()

    # 1. Classify: only RECONSTRUCTIBLE is freely summarisable.
    for i, r in enumerate(regions):
        if r.kind is RegionKind.RECONSTRUCTIBLE:
            plan.summarise.add(i)
        else:
            plan.pin.add(i)

    # 2. Witness audit: any live claim whose support is being summarised
    #    must retain either the raw witness (pin) or a verified re-fetch handle.
    for claim in live_claims:
        for idx in claim.supported_by:
            region = regions[idx]
            if idx in plan.summarise:
                # Reconstructible region backing a live claim -> must pin.
                plan.summarise.discard(idx)
                plan.pin.add(idx)
            if idx in plan.pin and region.kind is not RegionKind.RECONSTRUCTIBLE:
                if region.refetch_handle is None:
                    raise CompactionRefused(
                        f"claim {claim.text!r} depends on witness region {idx} "
                        f"(kind={region.kind.value}) with no re-fetch handle; "
                        f"summarising it would freeze the claim as unverifiable belief"
                    )
                # Re-fetch handle present: verify it still resolves to the
                # same witness hash before allowing the pin to become a handle.
                if not _handle_matches(region):
                    raise CompactionRefused(
                        f"witness region {idx} re-fetch handle {region.refetch_handle!r} "
                        f"does not reproduce original hash; refusing to compact"
                    )

    # 3. Only after the audit: check budget. If over, evict reconstructible
    #    regions first; never evict a witness to make room.
    if _estimate_tokens(regions, plan) > token_budget:
        for i in sorted(plan.summarise):
            plan.summarise.discard(i)
            if _estimate_tokens(regions, plan) <= token_budget:
                break
        if _estimate_tokens(regions, plan) > token_budget:
            raise CompactionRefused(
                "budget cannot be met without evicting witness-bearing regions; "
                "checkpoint and restart instead of laundering state"
            )

    return plan


def _handle_matches(region: Region) -> bool:
    # Placeholder: real impl re-fetches via handle and compares sha256.
    return region.refetch_handle is not None


def _estimate_tokens(regions: list[Region], plan: CompactionPlan) -> int:
    pinned = sum(len(regions[i].raw) for i in plan.pin)
    summarised = 64 * len(plan.summarise)  # rough per-summary cost
    return (pinned + summarised) // 4
