# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-signed-skill-sbom-whose-prompt-bundle-hash-was-computed-over-a-normalized-form-the-runtime-never-reproduces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-signed-skill-sbom-whose-prompt-bundle-hash-was-computed-over-a-normalized-form-the-runtime-never-reproduces.warrant.json
# Markdown SHA-256:   cdd7ea3457744d166f6ce2a0fa350b3e5129b3a5b329253ed28ce20707859c9e
# Code AST SHA-256:   30d03c0fa9340e736c7c2bdad85d754bfa42fe316da3dc44c9aa1c389a011f9d
# Verified Classes:   ProvenanceMismatch, UnknownCanonicalization
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib

CANONICALIZATIONS = {
    "urn:corpusfetch:canon:v1:utf8-nfc-lf-trailws": lambda b: b.decode("utf-8").encode("utf-8"),
}

INSTRUCTION_BEARING_PREFIXES = ("prompts/", "tools/code/")


class ProvenanceMismatch(RuntimeError):
    """Raised when a recomputed digest does not match the signed SBOM digest."""


class UnknownCanonicalization(ProvenanceMismatch):
    """Raised when the SBOM names a canonicalization the runtime cannot reproduce."""


def attest_prompt_bundle(sbom: dict, fetched_files: dict[str, bytes]) -> str:
    subject = sbom["subject"]
    canon_urn = subject["canonicalization"]
    if canon_urn not in CANONICALIZATIONS:
        # Fail-closed: never hash with a guess, never fall back to raw bytes.
        raise UnknownCanonicalization(
            f"runtime cannot reproduce canonicalization {canon_urn!r}; "
            f"refusing to attest {subject['name']}"
        )
    canon = CANONICALIZATIONS[canon_urn]

    # Deterministic serialization: sorted paths, length-prefixed segments.
    h = hashlib.sha256()
    for path in sorted(subject["files"]):
        if path not in fetched_files:
            raise ProvenanceMismatch(f"declared file missing from bundle: {path}")
        segment = canon(fetched_files[path])
        h.update(len(segment).to_bytes(8, "big"))
        h.update(path.encode("utf-8"))
        h.update(segment)

    digest = h.hexdigest()
    if digest != subject["digest"]:
        # Instruction-bearing content: no degrade path exists.
        raise ProvenanceMismatch(
            f"prompt bundle digest mismatch for {subject['name']}@{subject['version']}: "
            f"signed={subject['digest']} recomputed={digest}"
        )
    return digest
