#!/usr/bin/env python3
"""Count what an agent-smith ledger says about delegated work, and how much of it was graded.

agent-smith (github.com/negativetime/agent-smith-plugin) logs one JSON line per delegated
run to data/usage.jsonl, and one more line each time someone reviews a run with
verdict.py good|bad|stale. This script reads that file and writes three files:

    volume.csv   delegated runs per month, task shape and lane (local or cloud)
    graded.csv   one row per good or bad grade: the day it was given, the run it names
                 (its timestamp), lane, model family, model as logged, shape, verdict, whether
                 it is the first time its incident was counted for its route, whether
                 it was given more than a day after the run it names, and whether that
                 run searched the web
    meta.json    the totals, the names this script had to guess, and how it counted

How it counts:

  - every good or bad grade is a grade, including several grades that name one run, the
    rule agent-smith's own reports use since 2026-10-25 (scripts/grades.py). Before that
    they kept only the last grade on each run; meta.json counts that way too, as
    last_grade_rule, so the two can be compared
  - a grade marked duplicate_of is the same judgment written twice, and is skipped
  - a grade that was moved to the run it graded (moved_from in the log) is counted on that
    run; meta.json says how many were moved, and from which runs
  - "stale" means the output was gone before anyone looked; counted apart, never good or bad
  - one bug graded several times is one incident: within a route (shape and model family),
    a grade whose incident id, or note text for grades older than the id, was already
    counted is kept in graded.csv with first=0 and left out of the totals
  - agent-gym benchmark traffic (tag gym-eval, project agent-gym or eval) is test traffic,
    not delegated work, and is left out
  - a grade names its run by run_id when it has one (agent-smith since 2026-10-28). Older
    grades name a timestamp, script and model, and runs of one model that finished in the
    same second share those, so such a grade goes to the first of them

Nothing leaves the Mac. No prompt, output, note or project name is written out.

Usage:
    python3 -I handoff-report.py --out ./out
    python3 -I handoff-report.py --ledger /path/to/usage.jsonl --out ./out
"""
import argparse
import collections
import csv
import datetime
import hashlib
import json
import os
import sys

DEFAULT_LEDGER = os.path.expanduser("~/.claude/skills/agent-smith/data/usage.jsonl")
NOT_RUNS = {"verdict", "witness", "cascade-attempt"}

# Model names as the ledger logged them -> (family, lane). Local means it ran on this Mac.
# Ollama also serves cloud models, and logs some of them with no ":cloud" suffix, so the
# backend alone cannot say. Edit this for your own fleet; names not listed here are
# placed by the rules in place() and listed under "guessed" in meta.json.
MODELS = {
    "gemini-pro-latest": ("Gemini Pro", "cloud"), "pro": ("Gemini Pro", "cloud"),
    "gemini-flash-latest": ("Gemini Flash", "cloud"), "flash": ("Gemini Flash", "cloud"),
    "default": ("Gemini CLI default", "cloud"),
    "glm-5.3": ("GLM", "cloud"), "glm-5.2": ("GLM", "cloud"), "zai-glm-5.2": ("GLM", "cloud"),
    "glm-5.3-flash": ("GLM", "cloud"), "glm-4.5-flash": ("GLM", "cloud"),
    "deepseek-v4.1-flash": ("DeepSeek V4.1 Flash", "cloud"),
    "deepseek-v4.1-flash:cloud": ("DeepSeek V4.1 Flash", "cloud"),
    "openai/gpt-oss-20b:free": ("gpt-oss 20B", "cloud"),
    "@cf/openai/gpt-oss-120b": ("gpt-oss 120B", "cloud"),
    "@cf/llava-hf/llava-1.5-7b-hf": ("LLaVA 1.5 7B", "cloud"),
    "gpt-oss:20b": ("gpt-oss 20B", "local"), "gpt-oss-pilot": ("gpt-oss 20B", "local"),
    "qwen3-coder:30b": ("Qwen3 Coder 30B", "local"), "qwen3-vl:4b": ("Qwen3 VL 4B", "local"),
    "llama3.2:3b": ("Llama 3.2 3B", "local"), "gemma4:26b": ("Gemma 4 26B", "local"),
    "mlx-community/whisper-large-v3-turbo": ("Whisper", "local"),
    "llama3.1:8b": ("Llama 3.1 8B", "local"), "qwen2.5-coder-smith:14b": ("Qwen2.5 Coder 14B tune", "local"),
    "qwen3.6:27b": ("Qwen3.6 27B", "local"), "qwen3.6:35b": ("Qwen3.6 35B", "local"),
    "hf.co/InternScience/Agents-A1-Q4_K_M-GGUF:Q4_K_M": ("Agents A1", "local"),
    "hf.co/empero-ai/Qwythos-9B-Claude-Mythos-5-1M-GGUF:Q4_K_M": ("Qwythos 9B", "local"),
    "gpt-oss:20b-cloud": ("gpt-oss 20B", "cloud"), "openai/gpt-oss-120b": ("gpt-oss 120B", "cloud"),
    "@cf/baai/bge-m3": ("BGE M3", "cloud"), "@cf/baai/bge-reranker-base": ("BGE reranker", "cloud"),
    "typesafe/jev-1.13-20260917": ("Jev", "cloud"),
    "fake:1b": ("test stub", "local"),
}
LOCAL_BACKENDS = {"ollama", "mlx", "lmstudio"}
CLOUD_VIA_OLLAMA = ("glm-", "deepseek-v4", "kimi-")


def place(model, backend, guessed):
    if model in MODELS:
        return MODELS[model]
    guessed.add(model)
    cloud = (backend not in LOCAL_BACKENDS or model.endswith(":cloud") or "-cloud" in model
             or model.startswith(CLOUD_VIA_OLLAMA))
    return model, "cloud" if cloud else "local"


def is_benchmark(r):
    return r.get("tag") == "gym-eval" or r.get("project") in ("agent-gym", "eval")


def incident_of(v):
    if v.get("incident"):
        return v["incident"]
    note = " ".join((v.get("note") or "").split()).casefold()
    return hashlib.sha1(note.encode()).hexdigest()[:10] if note else None


def count(grades):
    """good, bad over grades whose incident is the first of its route, in grade order."""
    seen, good, bad = set(), 0, 0
    for g in sorted(grades, key=lambda g: g["ts"]):
        key = (g["shape"], g["family"], g["incident"])
        if g["incident"] is not None and key in seen:
            continue
        seen.add(key)
        good += g["verdict"] == "good"
        bad += g["verdict"] == "bad"
    return good, bad


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ledger", default=DEFAULT_LEDGER)
    ap.add_argument("--out", required=True)
    a = ap.parse_args()
    if not os.path.isfile(a.ledger):
        sys.exit(f"no ledger at {a.ledger}")

    runs, by_id, verdicts, unreadable = {}, {}, [], 0
    with open(a.ledger, encoding="utf-8") as f:
        for line in f:
            try:
                r = json.loads(line)
            except ValueError:
                unreadable += 1
                continue
            if not isinstance(r, dict):
                continue
            if r.get("script") == "verdict":
                verdicts.append(r)
            elif r.get("script") not in NOT_RUNS:
                runs.setdefault((r.get("ts"), r.get("script"), r.get("model")), []).append(r)
                if r.get("run_id"):
                    by_id[r["run_id"]] = r
    if not runs:
        sys.exit("the ledger has no runs")

    guessed = set()
    all_runs = [r for rs in runs.values() for r in rs]
    work = [r for r in all_runs if not is_benchmark(r)]
    volume = collections.Counter()
    for r in work:
        fam, ln = place(r.get("model") or "?", r.get("backend"), guessed)
        volume[(r["ts"][:7], r.get("tag") or "untagged", ln)] += 1

    grades, stale, orphans, bench_grades, duplicates = [], 0, 0, 0, 0
    moved = [v for v in verdicts if v.get("moved_from")]
    moved_from = sorted({(v["moved_from"]["ref_ts"], v["moved_from"]["ref_model"]) for v in moved})
    for v in verdicts:
        if v.get("ref_run_id"):
            run = by_id.get(v["ref_run_id"])
        else:
            run = (runs.get((v.get("ref_ts"), v.get("ref_script"), v.get("ref_model"))) or [None])[0]
        if run is None:
            orphans += 1
            continue
        if is_benchmark(run):
            bench_grades += 1
            continue
        if v.get("verdict") == "stale":
            stale += 1
            continue
        if v.get("verdict") not in ("good", "bad"):
            continue
        if v.get("duplicate_of"):
            duplicates += 1
            continue
        model = v.get("ref_model") or "?"
        fam, ln = place(model, run.get("backend"), guessed)
        late = (datetime.datetime.fromisoformat(v["ts"])
                - datetime.datetime.fromisoformat(run["ts"])).total_seconds() > 86400
        grades.append(dict(ts=v["ts"], day=v["ts"][:10], run_ts=run["ts"], lane=ln,
                           family=fam, model=model,
                           shape=v.get("tag") or run.get("tag") or "untagged",
                           verdict=v["verdict"], incident=incident_of(v), late=int(late),
                           search="yes" if run.get("search") else "no",
                           run=(v.get("ref_ts"), v.get("ref_script"), v.get("ref_model")),
                           ident=v.get("ref_run_id") or (v.get("ref_ts"), v.get("ref_script"), v.get("ref_model"))))

    # first=1 marks the grade that counts for its incident on its route.
    seen = set()
    for g in sorted(grades, key=lambda g: g["ts"]):
        key = (g["shape"], g["family"], g["incident"])
        g["first"] = 0 if (g["incident"] is not None and key in seen) else 1
        seen.add(key)

    # The plugin's rule before 2026-10-25, for comparison: the last grade on each run, then
    # the same collapse.
    last = {}
    for g in sorted(grades, key=lambda g: g["ts"]):
        last[g["ident"]] = g
    p_good, p_bad = count(last.values())
    good, bad = count(grades)
    per_run = collections.Counter(g["ident"] for g in grades)

    os.makedirs(a.out, exist_ok=True)
    with open(os.path.join(a.out, "volume.csv"), "w", encoding="utf-8", newline="") as f:
        w = csv.writer(f)
        w.writerow(["month", "shape", "lane", "runs"])
        for k in sorted(volume):
            w.writerow([*k, volume[k]])
    with open(os.path.join(a.out, "graded.csv"), "w", encoding="utf-8", newline="") as f:
        cols = ["day", "run_ts", "lane", "family", "model", "shape", "verdict", "first", "late", "search"]
        w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore")
        w.writeheader()
        w.writerows(sorted(grades, key=lambda g: g["ts"]))

    meta = dict(
        ledger_first=min(r["ts"] for r in all_runs)[:10],
        ledger_last=max(r["ts"] for r in all_runs)[:10],
        runs=len(all_runs), benchmark_runs=len(all_runs) - len(work), delegated_runs=len(work),
        grade_lines=len(verdicts), grades=len(grades), stale=stale, benchmark_grades=bench_grades,
        orphan_grades=orphans, duplicate_grades=duplicates, unreadable_lines=unreadable,
        counted=good + bad, good=good, bad=bad,
        last_grade_rule=dict(counted=p_good + p_bad, good=p_good, bad=p_bad),
        moved_grades=len(moved), moved_from_runs=[dict(ts=t, model=m) for t, m in moved_from],
        still_on_moved_from_runs=sum(1 for g in grades if (g["run"][0], g["run"][2]) in set(moved_from)),
        runs_graded=len(per_run), runs_with_several_grades=sum(1 for n in per_run.values() if n > 1),
        most_grades_on_one_run=max(per_run.values()) if per_run else 0,
        late_grades=sum(g["late"] for g in grades),
        guessed=sorted(guessed),
        counting=("every good or bad grade; stale and duplicate_of apart; one incident counted once "
                  "per (shape, model family); gym-eval and agent-gym/eval project runs left out"),
    )
    with open(os.path.join(a.out, "meta.json"), "w", encoding="utf-8") as f:
        json.dump(meta, f, indent=2)
        f.write("\n")

    print(f"{meta['delegated_runs']} delegated runs; {meta['grades']} grades on {meta['runs_graded']} runs; "
          f"{meta['counted']} incidents counted: {good} good, {bad} bad")
    print(f"keeping only the last grade per run would count {p_good + p_bad}: {p_good} good, {p_bad} bad; "
          f"{len(moved)} grades were moved to the runs they graded")
    by = collections.defaultdict(list)
    for g in grades:
        by[g["shape"]].append(g)
    for shape, gs in sorted(by.items(), key=lambda kv: -len(kv[1])):
        gd, bd = count(gs)
        print(f"  {shape:18} {gd:4} good {bd:4} bad  {gd / (gd + bd):4.0%}")
    if guessed:
        print("names placed by rule, check them:", ", ".join(sorted(guessed)))
    print(f"wrote {a.out}/volume.csv, graded.csv, meta.json")


if __name__ == "__main__":
    main()
