# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-provenance-chain-it-cannot-cryptographically-re-derive.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-provenance-chain-it-cannot-cryptographically-re-derive.warrant.json
# Markdown SHA-256:   11b2b572102f4f069308cad7c816a519de9a33bb79c8dd0870a95a3f13b2c3cc
# Code AST SHA-256:   cbdd3d4ba0a5c4e415bb2759cd26f08c2ae3420d89faad2604b906e2089ae8ae
# Verified Classes:   ProvenanceReDerivationError, Verdict, ProvenanceRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ProvenanceReDerivationError(RuntimeError):
    """Raised when a provenance chain passes link verification but fails
    independent re-derivation of an ancestor hash."""
    pass


class Verdict(Enum):
    VALID = "valid"
    UNVERIFIABLE = "unverifiable"
    TAMPERED = "tampered"


# The only canonicalization procedure this auditor supports. A record
# declaring anything else is UNVERIFIABLE, never TAMPERED.
SUPPORTED_CANONICALIZATION = "json-sorted-utf8-nfc-v1"


@dataclass
class ProvenanceRecord:
    record_id: str
    issuer: str
    content: dict
    canonicalization: Optional[str]
    content_hash: str
    parent_hash: Optional[str] = None
    signature_valid: bool = True


def canonicalize(content: dict, procedure: str) -> bytes:
    if procedure != SUPPORTED_CANONICALIZATION:
        raise ValueError(f"unsupported canonicalization: {procedure}")
    # Byte-pin: do NOT normalize free-text fields. sort_keys gives stable
    # key order; ensure_ascii=False preserves exact code points.
    return json.dumps(
        content, sort_keys=True, ensure_ascii=False, separators=(",", ":")
    ).encode("utf-8")


def re_derive_hash(record: ProvenanceRecord) -> str:
    if record.canonicalization != SUPPORTED_CANONICALIZATION:
        raise ValueError("cannot re-derive with unsupported procedure")
    return hashlib.sha256(
        canonicalize(record.content, record.canonicalization)
    ).hexdigest()


def audit_chain(records: list[ProvenanceRecord]) -> Verdict:
    by_hash = {r.content_hash: r for r in records}

    for rec in records:
        # Layer 1: link verification.
        if not rec.signature_valid:
            return Verdict.TAMPERED
        if rec.parent_hash is not None and rec.parent_hash not in by_hash:
            return Verdict.TAMPERED

        # Layer 2: re-derivation. The invariant that actually matters.
        if rec.canonicalization != SUPPORTED_CANONICALIZATION:
            # We cannot re-derive, but we also cannot conclude tampering.
            return Verdict.UNVERIFIABLE

        try:
            derived = re_derive_hash(rec)
        except ValueError as exc:
            raise ProvenanceReDerivationError(
                f"re-derivation failed for {rec.record_id}: {exc}"
            ) from exc

        if derived != rec.content_hash:
            # Declared procedure matches ours, yet hash diverges: the
            # content was mutated after signing, or the emitter hashed
            # non-canonical bytes. This is a tamper signal.
            raise ProvenanceReDerivationError(
                f"hash divergence on {rec.record_id}: "
                f"declared={rec.content_hash} derived={derived}"
            )

    return Verdict.VALID


if __name__ == "__main__":
    # A record whose rationale contains a non-breaking space that a
    # transport normalized to a regular space before re-derivation.
    original = ProvenanceRecord(
        record_id="plan-001",
        issuer="planner",
        content={"rationale": "step 1\u00a0-> step 2", "n": 3},
        canonicalization=SUPPORTED_CANONICALIZATION,
        content_hash="",  # filled below
    )
    original.content_hash = re_derive_hash(original)

    mutated = ProvenanceRecord(
        record_id="plan-001",
        issuer="planner",
        content={"rationale": "step 1 -> step 2", "n": 3},  # NBSP normalized
        canonicalization=SUPPORTED_CANONICALIZATION,
        content_hash=original.content_hash,  # signature still "valid"
    )

    audit_chain([mutated])  # raises ProvenanceReDerivationError
