#!/usr/bin/env python3
"""Compile and run the pinned sampler test and the field-note fixture probe.

Requires a C compiler, libc/libm, Python 3, and the three source files from
Colibri revision 0a5504a1dc64f86fcd0fe7db298b0448c730e7e6.
No model weights, framework, network request, or package install is involved.
"""
import hashlib
from pathlib import Path
import subprocess
import sys
import tempfile

SOURCE_HASHES = {
    "c/argmax_first.h": "8c7cc8f9b84f04989b5da2ef47520cc1db2eea50f6d64fd9a764c08c64fd02de",
    "c/qwen36_sample.h": "c5ac5a06b3902f07aaaf153796f76c7b77bf92299ccc257bbea033ac8fdd04d4",
    "c/tests/test_qwen36_sample.c": "41d27f10322896c27f33bd2883dad233962c8f910fa257003fbe260a2afeef87",
}


def run(command):
    print("$ " + " ".join(map(str, command)), flush=True)
    result = subprocess.run(list(map(str, command)), check=False)
    print(f"exit={result.returncode}", flush=True)
    if result.returncode:
        raise SystemExit(result.returncode)


def main():
    if len(sys.argv) != 2:
        raise SystemExit("usage: python replay.py /path/to/colibri")
    root = Path(sys.argv[1]).resolve()
    for relative, expected in SOURCE_HASHES.items():
        actual = hashlib.sha256((root / relative).read_bytes()).hexdigest()
        if actual != expected:
            raise SystemExit(f"source digest mismatch: {relative}")
    print("Verified 3 pinned source digests", flush=True)
    run([sys.executable, "--version"])
    run(["cc", "--version"])
    flags = ["-O3", "-std=c11", "-Wall", "-Wextra"]
    with tempfile.TemporaryDirectory(prefix="colibri-sampler-replay-") as tmp:
        upstream = Path(tmp) / "sampler-test"
        probe = Path(tmp) / "sampler-probe"
        run(["cc", *flags, root / "c/tests/test_qwen36_sample.c", "-lm", "-o", upstream])
        run([upstream])
        run(["cc", *flags, "-I", root / "c", Path(__file__).with_name("sampler-probe.c"), "-lm", "-o", probe])
        run([probe])


if __name__ == "__main__":
    main()
