#!/usr/bin/env python3
"""free-agent-ledger — turn the run history into a markdown performance table.

Reads every finished run under ~/.local/state/free-agent/runs/*/status.json and
reports, per model, how often it was tried and how it went. Every *attempt* is an
observation, including failed ones, so a model that needed two tries shows that.

    free-agent-ledger            # markdown tables
    free-agent-ledger --json     # same data, for tooling

Paste the output into the wiki page homelab/reference/clients/free-model-performance
rather than writing numbers from memory; the sample is small and it grows every run.
"""
import json
import os
import statistics
import sys
from collections import defaultdict

RUNS = os.path.expanduser("~/.local/state/free-agent/runs")


def load():
    rows = []
    for name in sorted(os.listdir(RUNS)):
        path = os.path.join(RUNS, name, "status.json")
        if not os.path.exists(path):
            continue
        try:
            d = json.load(open(path))
        except Exception:
            continue
        attempts = d.get("attempts") or []
        if not attempts:
            rows.append({"id": d.get("id", name), "role": d.get("role") or "?",
                         "model": d.get("model") or "?", "ok": d.get("state") == "done",
                         "secs": d.get("secs"), "tries": 0, "rate_limited": False})
            continue
        for a in attempts:
            rows.append({
                "id": d.get("id", name),
                "role": d.get("role") or "?",
                "model": a.get("model") or d.get("model") or "?",
                "ok": bool(a.get("ok")),
                "secs": a.get("secs"),
                "tries": a.get("tries") or 1,
                "rate_limited": bool(a.get("rateLimited")),
            })
    return rows


def main():
    rows = load()
    if "--json" in sys.argv:
        print(json.dumps(rows, indent=1))
        return

    by_model = defaultdict(list)
    for r in rows:
        by_model[r["model"]].append(r)

    print("### Measured attempt history\n")
    print("| Model | Attempts | Succeeded | Failed | Rate-limited | Median time | Roles |")
    print("|---|---|---|---|---|---|---|")
    for model, rs in sorted(by_model.items(), key=lambda kv: -len(kv[1])):
        secs = [r["secs"] for r in rs if isinstance(r["secs"], (int, float))]
        roles = ", ".join(sorted({r["role"] for r in rs}))
        print("| `%s` | %d | %d | %d | %d | %s | %s |" % (
            model, len(rs), sum(r["ok"] for r in rs), sum(not r["ok"] for r in rs),
            sum(r["rate_limited"] for r in rs),
            ("%.0f s" % statistics.median(secs)) if secs else "n/a", roles))

    print("\n### Runs\n")
    print("| Run | Role | Model | Tries | Time | Outcome |")
    print("|---|---|---|---|---|---|")
    for r in sorted(rows, key=lambda x: x["id"]):
        print("| `%s` | %s | `%s` | %d | %s | %s |" % (
            r["id"], r["role"], r["model"], r["tries"],
            ("%.0f s" % r["secs"]) if isinstance(r["secs"], (int, float)) else "n/a",
            "ok" if r["ok"] else ("rate-limited" if r["rate_limited"] else "failed")))

    n = len(by_model)
    print("\n*%d observation(s) across %d model(s). Small samples: treat a single "
          "failure as a hint, not a verdict.*" % (len(rows), n))


if __name__ == "__main__":
    main()
