# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-tool-schema-overhead-as-a-first-class-budget-line-rather-than-a-residual.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-tool-schema-overhead-as-a-first-class-budget-line-rather-than-a-residual.warrant.json
# Markdown SHA-256:   cd9634dfb539d0631d8cf28398e7a0a85922c7b22b1448e53512f4448ead9651
# Code AST SHA-256:   517af8c68dd580ea611d65747d9f5388fd112d32492af7d06141861536d71aec
# Verified Classes:   SchemaBudgetInversion
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaBudgetInversion(RuntimeError):
    """Raised when the live serialized tool-schema block exceeds the
    allocator's reserved schema budget, invalidating the retrieval
    allocation computed from a stale schema constant."""
    pass


def allocate_context(
    window: int,
    scratchpad_reserve: int,
    schema_constant: int,
    live_schema_tokens: int,
    safety_margin: int = 512,
) -> dict:
    """
    Compute segment budgets. Refuses to allocate if the live schema block
    has outgrown the captured constant by more than the safety margin,
    because retrieval_budget would then be silently wrong.
    """
    drift = live_schema_tokens - schema_constant
    if drift > safety_margin:
        raise SchemaBudgetInversion(
            f"live schema block ({live_schema_tokens} tok) exceeds captured "
            f"constant ({schema_constant} tok) by {drift} tok > margin "
            f"{safety_margin}; retrieval allocation is stale. Re-measure "
            f"schemas and recompute before assembly."
        )
    retrieval_budget = window - scratchpad_reserve - live_schema_tokens
    if retrieval_budget <= 0:
        raise SchemaBudgetInversion(
            f"no retrieval budget remains: window={window}, "
            f"scratchpad={scratchpad_reserve}, schema={live_schema_tokens}"
        )
    return {
        "schema": live_schema_tokens,
        "scratchpad": scratchpad_reserve,
        "retrieval": retrieval_budget,
        "window": window,
    }


def assemble(segments: list[tuple[int, int, str]], window: int) -> str:
    """
    segments: (priority, measured_tokens, text), lower priority = evicted first.
    Evict lowest-priority segments until the prompt fits; never truncate by
    string position.
    """
    total = sum(tok for _, tok, _ in segments)
    kept = sorted(segments, key=lambda s: s[0], reverse=True)
    while total > window and kept:
        _, tok, _ = kept.pop()  # drop lowest priority
        total -= tok
    if total > window:
        raise SchemaBudgetInversion(
            f"cannot fit prompt: {total} tok > window {window} even after "
            f"evicting all evictable segments"
        )
    return "".join(text for _, _, text in kept)
