#!/usr/bin/env python3
"""Lab 06 blind regrade, step 2: a second model grades each prepared hand-off, twice, without knowing who wrote
it or what Claude said.

The reader is z.ai glm-5.3 on the flat-rate Coding Plan, called through agent-smith's own gemini.py so every call
is tagged and logged like any other hand-off. It is shown the kind of job, a one line description, the names of the
input files, and the answer. It is NOT shown the original instructions or the inputs (the ledger does not keep
them), so it can judge what it can see and nothing it would have to check against a source.

Two passes per item, in different orders, so GLM's agreement with ITSELF can be measured: a yardstick that does
not repeat cannot say much about Claude. At most 4 calls are in flight (z.ai 429s past about 6).

    python3 -I -B grade.py WORK_DIR [--limit N]

Reads WORK_DIR/items.jsonl, appends to WORK_DIR/responses.jsonl (and skips what is already there, so it can be
stopped and started).
"""
import argparse
import json
import os
import random
import re
import subprocess
import sys
import threading
from concurrent.futures import ThreadPoolExecutor

GEMINI = os.path.expanduser("~/.claude/skills/agent-smith/scripts/gemini.py")
BASE = "https://api.z.ai/api/coding/paas/v4"
SYSTEM = ("You review work that one AI model handed back. You are shown what kind of job it was, a one line "
          "description, and the answer. You are not shown the original instructions or the input files, so judge "
          "only what you can see, and say so when that is not enough.")
RUBRIC = """Grade the answer below the way the person who handed the job off would.

good = usable as it stands, or with small fixes.
bad = wrong in a way that mattered: wrong or made up facts, missing the point, broken or unusable output, or off task.
cannot tell = you cannot judge it from what you can see.

Reply with JSON only, no other text:
{"verdict": "good" or "bad" or "cannot tell", "why": "one sentence"}"""


def prompt(item):
    inputs = ", ".join(item["inputs"]) if item["inputs"] else "none named"
    return (f"Kind of job: {item['kind'] or 'not stated'}\nOne line description: {item['purpose'] or 'not stated'}\n"
            f"Input files named: {inputs}\n\nThe answer to review:\n<<<\n{item['answer']}\n>>>")


def parse(raw):
    """The verdict is read by its key, not by matching the whole object: GLM's one line reason can hold braces
    (a reply that mentioned {{SHOT1}} hid its own verdict from the first version of this parser)."""
    m = re.search(r"\"verdict\"\s*:\s*\"(good|bad|cannot tell)\"", raw, flags=re.I)
    if not m:
        return None, ""
    w = re.search(r"\"why\"\s*:\s*\"(.*)", raw, flags=re.S)
    return m.group(1).lower(), (w.group(1).rsplit('"', 1)[0] if w else "")[:400]


def call(item, which):
    cmd = [sys.executable, "-I", "-B", GEMINI, "--backend", "openai", "--base-url", BASE, "--model", "glm-5.3",
           "--tag", "classify", "--purpose", f"Lab 06 blind regrade, pass {which}, item {item['id']}",
           "--system", SYSTEM, "--max-tokens", "32000", RUBRIC]
    p = subprocess.run(cmd, input=prompt(item), capture_output=True, text=True, timeout=900)
    return p.stdout, p.returncode, p.stderr[-300:]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("work")
    ap.add_argument("--limit", type=int)
    a = ap.parse_args()
    items = [json.loads(l) for l in open(os.path.join(a.work, "items.jsonl"), encoding="utf-8")]
    if a.limit:
        items = items[: a.limit]
    path = os.path.join(a.work, "responses.jsonl")
    done = set()
    if os.path.exists(path):
        done = {(r["id"], r["pass"]) for r in map(json.loads, open(path, encoding="utf-8")) if r.get("verdict")}
    order_b = list(items)
    random.Random(7).shuffle(order_b)
    jobs = [(it, "A") for it in items] + [(it, "B") for it in order_b]
    jobs = [(it, w) for it, w in jobs if (it["id"], w) not in done]
    lock = threading.Lock()
    print(f"{len(jobs)} calls to make, {len(done)} already done", flush=True)

    def work(job):
        it, w = job
        for attempt in range(3):                            # an empty or unparseable reply is tried again
            out, rc, err = call(it, w)
            verdict, why = parse(out)
            if verdict:
                break
        rec = {"id": it["id"], "pass": w, "verdict": verdict, "why": why, "raw": out[-1500:], "rc": rc, "attempts": attempt + 1}
        with lock:
            with open(path, "a", encoding="utf-8") as f:
                f.write(json.dumps(rec, ensure_ascii=False) + "\n")
        return rec

    n = 0
    with ThreadPoolExecutor(max_workers=4) as ex:
        for rec in ex.map(work, jobs):
            n += 1
            if n % 10 == 0 or not rec["verdict"]:
                print(f"  {n}/{len(jobs)}  last: {rec['id']} {rec['pass']} -> {rec['verdict']}", flush=True)
    print("done")


if __name__ == "__main__":
    main()
