"""Karpathy CLAUDE.md before/after: 5 tasks x {base, karpathy} x reps, haiku, each run in its own git copy of fixture/.
python3 bench.py [reps]   -> runs/<cond>/<task>-<rep>/ and results.json
Isolation: PATH starts with this folder's uv venv (pytest only); project settings deny pip, conda and anaconda."""
import json, os, re, shutil, subprocess, sys, time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
HERE = Path(__file__).resolve().parent
VENV = HERE / ".venv"
KARPATHY = HERE / "src/andrej-karpathy-skills/CLAUDE.md"
TASKS = {
    "t1-bug": "parse_price('$1,299.00') returns 1.0 instead of 1299.0. Fix it.",
    "t2-feature": "Add a way to get the total value of all items in stock.",
    "t3-vague": "Add validation to add_item.",
    "t4-rename": "Rename the qty parameter of add_item to quantity.",
    "t5-refactor": "report() computes the grand total in a second loop. Clean that up.",
}
DENY = ["Bash(pip *)", "Bash(pip3 *)", "Bash(*-m pip*)", "Bash(conda *)", "Bash(*anaconda*)", "Bash(uv pip*)",
        "Read(~/.ssh/**)"]
CHECK = r'''
import sys; sys.path.insert(0, ".")
from inventory import core
r = {}
try: r["t1_ok"] = core.parse_price("$1,299.00") == 1299.0
except Exception as e: r["t1_ok"] = False
import inspect
r["t4_param"] = "quantity" in inspect.signature(core.add_item).parameters
items = []
try:
    core.add_item(items, "pen", 3, 1.5); core.add_item(items, "book", 1, 12.0)
    r["t5_same"] = core.report(items) == "pen: 3 x 1.50 = 4.50\nbook: 1 x 12.00 = 12.00\nTOTAL: 16.50\nTAX: 1.32"
except Exception as e: r["t5_same"] = False
src = open("inventory/core.py").read()
r["dead_code_kept"] = "_old_export_json" in src and "import json" in src
r["find_item_style_kept"] = 'if it["name"] == name: return it' in src
print(__import__("json").dumps(r))
'''

def sh(cmd, cwd, **kw):
    return subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True, **kw).stdout

def one(job):
    cond, task, rep = job
    d = HERE / "runs" / cond / f"{task}-{rep}"
    shutil.rmtree(d, ignore_errors=True); shutil.copytree(HERE / "fixture", d)
    (d / ".claude").mkdir()
    (d / ".claude/settings.json").write_text(json.dumps({"permissions": {"deny": DENY}}))
    if cond == "karpathy": shutil.copy(KARPATHY, d / "CLAUDE.md")
    sh("git init -q && git add -A && git -c user.email=t@t -c user.name=t commit -qm base", d)
    env = dict(os.environ, PATH=f"{VENV}/bin:" + os.environ["PATH"], VIRTUAL_ENV=str(VENV))
    t0 = time.time()
    out = subprocess.run(["claude", "-p", TASKS[task], "--model", "haiku", "--setting-sources", "project", "--output-format", "json",
                          "--allowedTools", "Bash", "Read", "Write", "Edit", "Glob", "Grep"],
                         cwd=d, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=900).stdout
    secs = round(time.time() - t0)
    (d / "out.json").write_text(out)
    j = json.loads(out)
    num = sh("git add -A -- . ':!out.json' && git diff --cached --numstat HEAD -- . ':!CLAUDE.md' ':!out.json'", d)
    added = sum(int(l.split()[0]) for l in num.splitlines() if l.split()[0].isdigit())
    removed = sum(int(l.split()[1]) for l in num.splitlines() if l.split()[1].isdigit())
    files = [l.split()[2] for l in num.splitlines()]
    tests = sh(f"{VENV}/bin/python -m pytest -q 2>&1 | tail -1", d).strip()
    newtests = len(re.findall(r"^\+def test_", sh("git diff --cached HEAD -- tests", d), re.M))
    (HERE / "check.py").write_text(CHECK)
    chk = json.loads(sh(f"{VENV}/bin/python {HERE}/check.py", d) or "{}")
    res = j.get("result", "")
    return dict(cond=cond, task=task, rep=rep, secs=secs, cost=round(j.get("total_cost_usd", 0), 4), turns=j.get("num_turns"),
                out_tokens=j.get("usage", {}).get("output_tokens"), added=added, removed=removed, files=files, pytest=tests,
                new_tests=newtests, asked=res.strip().endswith("?") or "?" in res[-300:], **chk)

if __name__ == "__main__":
    reps = int(sys.argv[1]) if len(sys.argv) > 1 else 2
    jobs = [(c, t, r) for r in range(1, reps + 1) for t in TASKS for c in ("base", "karpathy")]
    with ThreadPoolExecutor(4) as ex:
        results = list(ex.map(one, jobs))
    json.dump(results, open(HERE / "results.json", "w"), indent=1)
    for r in results: print(r)
