# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-apply-a-context-diff-whose-base-version-it-cannot-prove-it-holds.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-apply-a-context-diff-whose-base-version-it-cannot-prove-it-holds.warrant.json
# Markdown SHA-256:   40ea8af753dfb600d7123fd90ddaa529ab85d5eb8cfca323051034779db6065f
# Code AST SHA-256:   444c7dc40d5eb3bbff3c8cc67b97ba43baa361cd5f4a04128ef62a85c5f464bd
# Verified Classes:   UnprovenBaseVersionError, AuditEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnprovenBaseVersionError(RuntimeError):
    """Raised when a context-diff's claimed base cannot be proven against the live context."""
    pass


@dataclass
class AuditEntry:
    version: int
    base_hash: str
    result_hash: str
    diff_id: str | None  # None marks a local mutation (compaction, re-summarization)


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


def apply_context_diff(
    live_context: str,
    live_version: int,
    diff: dict,
    audit_trail: list[AuditEntry],
) -> tuple[str, int]:
    claimed_base = diff["base_version"]
    claimed_base_hash = diff["base_hash"]
    position_sensitive = diff.get("position_sensitive", True)

    live_hash = recompute_hash(live_context)

    # 1. Provenance gap check: any version increment between claimed base and live
    #    that lacks a diff_id means the path to the live state is unproven.
    by_version = {e.version: e for e in audit_trail}
    for v in range(claimed_base + 1, live_version + 1):
        entry = by_version.get(v)
        if entry is None or entry.diff_id is None:
            raise UnprovenBaseVersionError(
                f"audit gap at v{v}: no diff_id between claimed base v{claimed_base} "
                f"and live v{live_version}; provenance unproven"
            )

    # 2. Hash proof: the live context must equal the canonical result of the claimed base.
    canonical = by_version[claimed_base].result_hash
    if live_hash != canonical:
        if position_sensitive:
            raise UnprovenBaseVersionError(
                f"base hash mismatch at v{claimed_base}: live={live_hash[:12]} "
                f"canonical={canonical[:12]}; refusing position-sensitive diff "
                f"{diff['diff_id']} (drift would corrupt untouched clauses)"
            )
        # Content-addressed diff: safe to proceed, but log the drift explicitly.
        diff["_drift_warning"] = f"hash mismatch at v{claimed_base}, content-addressed apply"

    if live_hash != claimed_base_hash and position_sensitive:
        raise UnprovenBaseVersionError(
            f"diff {diff['diff_id']} declares base_hash={claimed_base_hash[:12]} "
            f"but live={live_hash[:12]}; author and holder disagree on base content"
        )

    new_context = _apply_hunks(live_context, diff["hunks"])
    return new_context, live_version + 1


def _apply_hunks(context: str, hunks: list[dict]) -> str:
    # Offset-based hunk application; assumes caller has proven the base.
    lines = context.splitlines(keepends=True)
    for hunk in sorted(hunks, key=lambda h: h["offset"], reverse=True):
        lines[hunk["offset"]:hunk["offset"] + hunk["length"]] = [hunk["replacement"]]
    return "".join(lines)
