#!/usr/bin/env python3
"""make-runs.py: builds runs.csv for the 2026-10-18 runs from the result files in raw/.

Two steps, so the answers are read before anyone sees which model, way or runtime wrote them.

  python3 -B make-runs.py sheet [quiz|tasks]
                                  writes the next blind batch: blind/sheet.csv and blind/key.json for
                                  the first, blind/sheet-2.csv and blind/key-2.json for the second,
                                  and so on. A batch holds the answers no earlier batch covers, in a
                                  shuffled order, with only the question id and the answer on it.
                                  quiz or tasks limits it to the six questions or to the real tasks
                                  (tasks/tasks.json), which are read against tasks/task-rubric.txt.
  python3 -B make-runs.py merge   reads every batch's two readings, blind/read-a[-N].csv and
                                  blind/read-b[-N].csv (id, right, note), each filled in against
                                  ../2026-10-07/grading-rubric.txt by a reader who saw only that
                                  batch's sheet, and writes runs.csv

An answer that is an error, a timeout or "no final answer" is not put on a sheet: it is wrong
without reading, and its read_note says so. From the second batch on, an answer whose text is
exactly that of an answer already read (a repeat run at temperature 0 often gives the same words)
is not put on the sheet either: it takes that answer's readings, and sheet_id names it.
"""
import csv, glob, json, os, random, re, secrets, sys
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
RAW, BLIND = os.path.join(HERE, "raw"), os.path.join(HERE, "blind")
TASKS = {t["id"] for t in json.load(open(os.path.join(HERE, "tasks", "tasks.json"), encoding="utf-8"))}


def answers():
    """Every answer in raw/, with its run number: the nth file holding a runtime, model and way is
    run n of that way (a queue may write the tool ways and the brief to separate files)."""
    seen = defaultdict(int)
    for path in sorted(glob.glob(os.path.join(RAW, "results-*.json"))):
        d = json.load(open(path, encoding="utf-8"))
        reps = {}
        for k in sorted({(r["model"], r["mode"]) for r in d["results"]}):
            seen[(d["run"]["runtime"],) + k] += 1
            reps[k] = seen[(d["run"]["runtime"],) + k]
        for i, r in enumerate(d["results"]):
            yield os.path.relpath(path, HERE), i, d["run"], r, reps[(r["model"], r["mode"])]


def unread(ans):
    return ans.startswith("(error") or ans.startswith("(no final answer")


def raw_call(ans):
    """The answer is a tool call the runtime handed back as text, never run: Llama's JSON, or gpt-oss's own
    markup with a call to a function in it and no final answer after."""
    a = ans.strip()
    if a.startswith(("<|python_tag|>", "{")) and '"name"' in a[:200]:
        return True
    return "to=functions." in a and "<|channel|>final" not in a


def batch_names(n):
    s = "" if n == 1 else f"-{n}"
    return f"sheet{s}.csv", f"key{s}.json", f"read-a{s}.csv", f"read-b{s}.csv"


def keys():
    """{batch number: key}. Batch 1's key maps id to [file, index]; later keys map id to a list of
    [file, index] (identical texts in one batch share an id) and record repeats of read answers."""
    out, n = {}, 1
    while os.path.exists(os.path.join(BLIND, batch_names(n)[1])):
        out[n] = json.load(open(os.path.join(BLIND, batch_names(n)[1])))
        n += 1
    return out


def covered(ks):
    """{(file, index): sheet id} for every answer some batch already covers, and the text of each id."""
    where = {}
    for n, k in ks.items():
        if n == 1:
            for bid, fi in k.items():
                where[tuple(fi)] = bid
        else:
            for bid, fis in k["ids"].items():
                for fi in fis:
                    where[tuple(fi)] = bid
            for fi, bid in k["same"].items():
                path, i = fi.rsplit("|", 1)
                where[(path, int(i))] = bid
    return where


def norm(q, a):
    return q + "\n" + re.sub(r"\s+", " ", a.strip())


def sheet(only=None):
    os.makedirs(BLIND, exist_ok=True)
    want = {None: lambda q: True, "quiz": lambda q: q not in TASKS, "tasks": lambda q: q in TASKS}[only]
    ks = keys()
    n = len(ks) + 1
    where = covered(ks)
    text_of = {}
    for f, i, run, r, rep in answers():
        if (f, i) in where:
            text_of.setdefault(norm(r["q"], r["answer"]), where[(f, i)])
    ids, same, rows = {}, {}, {}
    for f, i, run, r, rep in answers():
        if (f, i) in where or unread(r["answer"]) or not want(r["q"]):
            continue
        t = norm(r["q"], r["answer"])
        if n > 1 and t in text_of:
            same[f"{f}|{i}"] = text_of[t]
            continue
        if t not in rows:
            bid = secrets.token_hex(4)
            rows[t] = (bid, r["q"], r["answer"])
            ids[bid] = []
        ids[rows[t][0]].append([f, i])
    assert ids or same, "nothing new to put on a sheet"
    out = list(rows.values())
    random.shuffle(out)
    sname, kname, _, _ = batch_names(n)
    with open(os.path.join(BLIND, sname), "w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh)
        w.writerow(["id", "question_id", "answer"])
        for bid, q, a in out:
            w.writerow([bid, q, a])
    key = {bid: fis[0] for bid, fis in ids.items()} if n == 1 else {"ids": ids, "same": same}
    json.dump(key, open(os.path.join(BLIND, kname), "w"), indent=1)
    print(f"batch {n}: {len(out)} answers on {sname}; {len(same)} repeat the text of an answer already read")


def read(name):
    with open(os.path.join(BLIND, name), newline="", encoding="utf-8") as fh:
        return {r["id"]: r for r in csv.DictReader(fh)}


def merge():
    ks = keys()
    a, b, sheet_ids = {}, {}, set()
    for n in ks:
        sname, _, an, bn = batch_names(n)
        ra, rb = read(an), read(bn)
        s = set(read(sname))
        assert set(ra) == s == set(rb), f"a reading of batch {n} does not cover its whole sheet"
        assert not (s & sheet_ids), "two batches share a sheet id"
        sheet_ids |= s
        a.update(ra); b.update(rb)
    where = covered(ks)
    out = []
    for f, i, run, r, rep in answers():
        bid = where.get((f, i))
        if bid is None and not unread(r["answer"]):
            sys.exit(f"{f} #{i} is on no sheet: run sheet first")
        ra, rb = (a[bid]["right"], b[bid]["right"]) if bid else ("0", "0")
        assert ra in ("0", "1") and rb in ("0", "1"), f"{bid}: a reading is not 0 or 1"
        note = "" if bid else (
            "no answer within the script's 10 minute limit" if "timed out" in r["answer"]
            else "error from the runtime" if r["answer"].startswith("(error") else "no final answer after 6 tool rounds")
        out.append(dict(
            file=f, runtime=run["runtime"], helper=run["helper"].get("version", ""), model=r["model"], rep=rep,
            mode=r["mode"], question_id=r["q"], right_read=ra, right_read_b=rb, right_pattern=int(r["passed"]),
            read_note=note, sheet_id=bid or "", note_a=a[bid]["note"] if bid else "", note_b=b[bid]["note"] if bid else "",
            called_memory=int(bool(r["tools"])), tool_calls=len(r["tools"]), tools=" ".join(r["tools"]),
            wrote_memory=int(any(t in ("memory_write", "memory_propose", "memory_update", "memory_forget") for t in r["tools"])),
            tool_errors=r["errors"], raw_call=int(raw_call(r["answer"])),
            thinking_chars=r.get("thinking_chars", ""), stop=r.get("stop", ""),
            brief_ids=" ".join(str(x) for x in r.get("brief_ids", [])),
            error=r["answer"][:300] if r["answer"].startswith("(error") else "", seconds=r["secs"]))
    with open(os.path.join(HERE, "runs.csv"), "w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, fieldnames=list(out[0]))
        w.writeheader()
        w.writerows(out)
    differ = sum(1 for k in sheet_ids if a[k]["right"] != b[k]["right"])
    print(f"runs.csv: {len(out)} answers, {sum(1 for r in out if r['read_note'])} unread, "
          f"{len(sheet_ids)} read on {len(ks)} sheets; the two readings differ on {differ}")


if __name__ == "__main__":
    {"sheet": sheet, "merge": merge}[sys.argv[1]](*sys.argv[2:])
