#!/usr/bin/env python3
"""Export what Lab 05 reports from Agent Gym's own run files.

Agent Gym is private (its run transcripts quote private notes), so the post publishes a
narrow copy of it, made by this script and nothing else:

  history.csv   one row per graded answer: run, model, task, capability, condition,
                outcome. No notes, no transcripts, no prompts. L2 rows are left out:
                they repeat the L0 row unless a repair round ran, and counting both would
                count one answer twice.
  case.csv      every run of the 54 section document task on gpt-oss 20B, with the
                grader's note, the machine's load and Ollama version, and what became
                of the answer file.
  answers/      the answer files that are still the model's first answer. When the gym's
                repair step ran, it wrote the repaired answer over the first one, and that
                file is NOT exported as if it were the first answer.
  task/         the task and grader exactly as they ran (task.json, build.py, check.py,
                manifest.json, public/check.py).
  meta.json     where this came from: the gym commit, the export time, the case filter.

Usage:
    python3 -I export-gym.py ~/Developer/agent-gym runs/history-YYYY-MM-DD
"""
import csv
import datetime
import glob
import hashlib
import json
import os
import shutil
import subprocess
import sys

CASE_MODEL, CASE_TASK = "gpt-oss-20b", "doc_fidelity_html_long"
# The task's first cut had 22 sections and was scaled to 54 before the next run the same
# evening (the task's build.py names this run as the one every model passed). Its row is
# kept and labelled, never counted with the 54 section runs.
FIRST_CUT_RUNS = {"20260718-202558"}
# The gym's own list (gym.py UNMEASURABLE_MARKERS, 2026-09-05). Older rows have no
# `outcome` field, so it is derived the way gym.py derives it today.
UNMEASURABLE = ("http-500", "mlx runner", "GPU Timeout", "signal: killed", "agent-crash",
                "task-timeout", "gen-error", "gen-timeout", "grade-timeout", "harness-error",
                "gen-empty")


def outcome(r):
    if r.get("outcome"):
        return r["outcome"]
    if r["pass"]:
        return "pass"
    return "unmeasurable" if any(m in (r.get("note") or "") for m in UNMEASURABLE) else "fail"


def main(gym, out):
    gym, out = os.path.abspath(os.path.expanduser(gym)), os.path.abspath(out)
    if os.path.exists(out):
        sys.exit(f"{out} exists; export to a new folder")
    os.makedirs(os.path.join(out, "answers"))
    commit = subprocess.run(["git", "-C", gym, "rev-parse", "HEAD"], capture_output=True,
                            text=True, check=True).stdout.strip()

    history, case = [], []
    for path in sorted(glob.glob(os.path.join(gym, "runs", "*", "results.jsonl"))):
        run = os.path.basename(os.path.dirname(path))
        mpath = os.path.join(os.path.dirname(path), "machine.json")
        machine = json.load(open(mpath)) if os.path.exists(mpath) else {}
        rows = [json.loads(l) for l in open(path, encoding="utf-8") if l.strip()]
        for r in rows:
            if r["condition"] == "L2":
                continue
            history.append(dict(run=run, model=r["model"], task=r["task"],
                                capability=r["capability"], condition=r["condition"],
                                outcome=outcome(r)))
        for r in rows:
            if (r["model"], r["task"], r["condition"]) != (CASE_MODEL, CASE_TASK, "L0"):
                continue
            l2 = next((x for x in rows if (x["model"], x["task"], x["condition"])
                       == (CASE_MODEL, CASE_TASK, "L2") and x.get("rep") == r.get("rep")), {})
            art = os.path.join(gym, "runs", run, CASE_MODEL, CASE_TASK, "work", "output.html")
            repaired = bool(l2.get("repairs"))
            kept, sha, size = "no", "", ""
            if os.path.exists(art):
                data = open(art, "rb").read()
                if repaired:
                    kept = "overwritten by the repair"
                else:
                    kept = "yes"
                    sha, size = hashlib.sha256(data).hexdigest(), len(data)
                    open(os.path.join(out, "answers", f"{run}.html"), "wb").write(data)
            # The run id is the time the run started; the row's ts is when the answer was graded.
            case.append(dict(run=run, finished=r.get("ts", ""),
                             sections=22 if run in FIRST_CUT_RUNS else 54,
                             ollama=machine.get("ollama", ""),
                             loadavg=machine.get("loadavg", ""), outcome=outcome(r),
                             seconds=round(r["seconds"]), answer_kept=kept, sha256=sha,
                             bytes=size, grader_note=(r.get("note") or "")[:400]))

    with open(os.path.join(out, "history.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=list(history[0]))
        w.writeheader()
        w.writerows(history)
    with open(os.path.join(out, "case.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=list(case[0]))
        w.writeheader()
        w.writerows(case)

    tdir = os.path.join(gym, "tasks", CASE_TASK)
    os.makedirs(os.path.join(out, "task", "public"))
    for rel in ("task.json", "build.py", "grade/check.py", "grade/manifest.json", "public/check.py"):
        dest = os.path.join(out, "task", rel if rel.startswith("public/") else os.path.basename(rel))
        shutil.copy(os.path.join(tdir, rel), dest)

    meta = dict(source="Agent Gym, a private repository", gym_commit=commit,
                exported=datetime.datetime.now().isoformat(timespec="seconds"),
                case=dict(model=CASE_MODEL, model_tag="gpt-oss:20b", task=CASE_TASK,
                          condition="L0, the first answer, temperature 0"),
                history_rows=len(history), case_rows=len(case))
    json.dump(meta, open(os.path.join(out, "meta.json"), "w"), indent=2)
    shutil.copy(os.path.abspath(__file__), os.path.join(out, "export-gym.py"))  # what made this folder
    print(f"history.csv {len(history)} rows, case.csv {len(case)} rows, "
          f"{len(os.listdir(os.path.join(out, 'answers')))} answers kept")


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit(__doc__)
    main(sys.argv[1], sys.argv[2])
