#!/usr/bin/env python3
"""Run tokcheck.py over the fault-injection matrix and write results.jsonl.
Resumable: a case whose BUILD__CASE.json already exists is not run again, only summarised.

  run_matrix.py <llama.cpp dir> <refs dir> <work dir> <py for BPE refs> <py with transformers 4.57.6> BUILD=path/to/llama-tokenize ...
"""
import json, os, subprocess, sys
here = os.path.dirname(os.path.abspath(__file__))
src, refs, work, py5, py4 = sys.argv[1:6]
builds = dict(a.split("=", 1) for a in sys.argv[6:])
V = lambda n: os.path.join(src, "models", "ggml-vocab-%s.gguf" % n)
QN = ["--token-text", "151665=<tool_response>", "--token-text", "151666=</tool_response>",
      "--token-text", "151667=<think>", "--token-text", "151668=</think>"]  # the names Qwen3 gives these ids
# id, vocab, patch, reference, slow?, what was changed
CASES = [
    ("qwen-clean", "qwen2", QN, "qwen2", 0, "nothing (Qwen2 vocabulary with Qwen3's four added tokens named)"),
    ("qwen-no-pre", "qwen2", QN + ["--remove", "tokenizer.ggml.pre"], "qwen2", 0, "tokenizer.ggml.pre removed"),
    ("qwen-pre-default", "qwen2", QN + ["--set", "tokenizer.ggml.pre=str:default"], "qwen2", 0, "tokenizer.ggml.pre = default"),
    ("qwen-pre-llama-bpe", "qwen2", QN + ["--set", "tokenizer.ggml.pre=str:llama-bpe"], "qwen2", 0, "tokenizer.ggml.pre = llama-bpe"),
    ("qwen-im-start-normal", "qwen2", QN + ["--token-type", "151644=1"], "qwen2", 0, "<|im_start|> typed NORMAL instead of CONTROL"),
    ("qwen-think-normal", "qwen2", QN + ["--token-type", "151667=1", "--token-type", "151668=1"], "qwen2", 0,
     "<think> and </think> typed NORMAL instead of USER_DEFINED"),
    ("qwen-add-bos", "qwen2", QN + ["--set", "tokenizer.ggml.add_bos_token=bool:true"], "qwen2", 0, "add_bos_token = true"),
    ("qwen-vocab-edit", "qwen2", QN + ["--token-text", "9707=Hullo"], "qwen2", 0, "text of token 9707 changed"),
    ("llama3-as-shipped", "llama-bpe", [], "llama-bpe", 0, "nothing (vocab file has no add_bos_token key)"),
    ("llama3-add-bos", "llama-bpe", ["--set", "tokenizer.ggml.add_bos_token=bool:true"], "llama-bpe", 0, "add_bos_token = true"),
    ("llama3-pre-smaug", "llama-bpe", ["--set", "tokenizer.ggml.add_bos_token=bool:true", "--set", "tokenizer.ggml.pre=str:smaug-bpe"],
     "llama-bpe", 0, "tokenizer.ggml.pre = smaug-bpe"),
    ("llama3-pre-qwen2", "llama-bpe", ["--set", "tokenizer.ggml.add_bos_token=bool:true", "--set", "tokenizer.ggml.pre=str:qwen2"],
     "llama-bpe", 0, "tokenizer.ggml.pre = qwen2"),
    ("spm-as-shipped", "llama-spm", [], "llama-spm-legacy-true", 1, "nothing"),
    ("spm-no-space-prefix", "llama-spm", ["--set", "tokenizer.ggml.add_space_prefix=bool:false"], "llama-spm-legacy-true", 1,
     "add_space_prefix = false"),
]
os.makedirs(work, exist_ok=True)
out = open(os.path.join(work, "results.jsonl"), "w")
ORDER = ["vocab", "special-type", "pre-missing", "pre-tokenizer", "normalizer", "unicode-normalization", "bos-eos",
         "space-after-special", "other"]  # the order tokcheck.py prints causes in
for build, binary in builds.items():
    for cid, vocab, patch, ref, slow, what in CASES:
        g = os.path.join(work, cid + ".gguf")
        j = os.path.join(work, "%s__%s.json" % (build, cid))
        if not os.path.exists(j):
            subprocess.run([sys.executable, os.path.join(here, "gguf_patch.py"), V(vocab), g] + patch, check=True)
            cmd = [py4 if slow else py5, os.path.join(here, "..", "tokcheck.py"), "--gguf", g, "--hf", os.path.join(refs, ref),
                   "--llama-tokenize", binary, "--json", j + ".tmp"] + (["--slow"] if slow else [])
            p = subprocess.run(cmd, capture_output=True, text=True)
            if p.returncode not in (0, 1):
                print(p.stdout[-2000:], p.stderr[-2000:]); raise SystemExit("tokcheck failed on %s %s" % (build, cid))
            with open(os.path.join(work, "%s__%s.txt" % (build, cid)), "w") as fh:
                fh.write(p.stdout)
            os.replace(j + ".tmp", j)
        r = json.load(open(j))
        cats = {}
        for c in r["cases"]:
            a = cats.setdefault(c["category"], [0, 0]); a[0] += 1; a[1] += 0 if c["match"] else 1
        main = sorted(r["causes"], key=lambda c: (c == "unicode-normalization", ORDER.index(c)))[:1]
        # the example shown is the first string whose difference has the main cause
        first = next((c for c in r["cases"] if not c["match"] and [c["cause"]] == main), None)
        rec = {"build": build, "case": cid, "vocab": vocab, "changed": what, "exit": 1 if r["causes"] else 0, "verdict": r["verdict"],
               "causes": r["causes"], "header_findings": [f for f in r["findings"] if f["level"] != "NOTE"],
               "categories": cats, "first": first and {k: first[k] for k in ("text", "llama_cpp", "hf", "first_diff", "cause")}}
        out.write(json.dumps(rec, ensure_ascii=False) + "\n"); out.flush()
        print(build, cid, r["verdict"], r["causes"], {k: "%d/%d" % (v[0] - v[1], v[0]) for k, v in cats.items()}, flush=True)
