"""addyosmani/agent-skills (all 25) vs none: 5 tasks x {base, karpathy} x reps, haiku, each run in its own git copy of fixture/.
python3 bench.py [reps] [conds, default addy; base results come from ../karpathy-skills-test]   -> 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.parent / "karpathy-skills-test/.venv"  # same pytest-only uv venv as the Karpathy test
SKILLS = HERE / "src/agent-skills/skills"
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.",
}
NAMED = {"t1-bug": "test-driven-development", "t2-feature": "incremental-implementation", "t3-vague": "interview-me",
         "t4-rename": "deprecation-and-migration", "t5-refactor": "code-simplification"}
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 skills_loaded(d):
    key = str(d).replace("/", "-").replace("_", "-").replace(".", "-")
    fs = sorted(Path.home().glob(f".claude/projects/{key}/*.jsonl"), key=os.path.getmtime)
    used = []
    for l in (fs[-1].read_text().splitlines() if fs else []):
        try: m = json.loads(l)
        except Exception: continue
        for c in (m.get("message", {}).get("content", []) if m.get("type") == "assistant" else []):
            if isinstance(c, dict) and c.get("type") == "tool_use" and c["name"] == "Skill": used.append(c["input"].get("skill"))
    return used

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.startswith("addy"): shutil.copytree(SKILLS, d / ".claude/skills")
    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()
    prompt = (f"Use the {NAMED[task]} skill. " if cond == "addy-named" else "") + TASKS[task]
    out = subprocess.run(["claude", "-p", prompt, "--model", "haiku", "--setting-sources", "project", "--output-format", "json",
                          "--allowedTools", "Bash", "Read", "Write", "Edit", "Glob", "Grep", "Skill"],
                         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' ':!.claude' && git diff --cached --numstat $(git rev-list --max-parents=0 HEAD) -- . ':!CLAUDE.md' ':!out.json' ':!.claude'", 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 $(git rev-list --max-parents=0 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", "")
    skills_used = skills_loaded(d)
    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, skills_used=skills_used, asked=res.strip().endswith("?") or "?" in res[-300:], **chk)

if __name__ == "__main__":
    reps = int(sys.argv[1]) if len(sys.argv) > 1 else 2
    CONDS = sys.argv[2].split(",") if len(sys.argv) > 2 else ["addy"]
    jobs = [(c, t, r) for r in range(1, reps + 1) for t in TASKS for c in CONDS]
    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)
