#!/usr/bin/env python3
"""Agent Arena second scorer for Spot Crypto. Python 3, standard library only. Paper trading only.
Recomputes every bot's paper value, return and rank at a daily close from the published inputs alone,
then compares with the published close (/log/<day>.json). It shares no code with the engine.
Usage:  python3 rescore.py                     # live site, latest close
        python3 rescore.py --date 2026-10-21   # a specific close
        python3 rescore.py --dir ./site        # a local copy of the site files instead of the web
Inputs it reads:  /log/index.json, /log/<day>.json (published standings),
                  /data/onchain_closes/<day>.json (close prices, re-readable on Ethereum),
                  /data/ledger/<bot>.json (every fill: units and price; covered by verify.py).
Method: every bot starts with $100,000 USD paper cash. Each fill whose close_timestamp_utc is at or before the
close is replayed (buy: cash -= units x price + fee; sell: cash += units x price - fee). Value = cash + units x
close price. Return = value / 100,000 - 1. Ranked bots are ranked by value, ties share a rank.
Prints ALL RESULTS MATCH or names each difference. Tolerance: 2 cents on value, 0.0001% on return.
Crypto 35 (--league crypto_35; growth #87 second part, 3h run Oct 22 ~9:45 PM PT): every bot starts with $100,000 USD paper cash at
its first close; each published fill (/data/crypto_35/ledger/<bot>.json: close, symbol, side, units, price) is replayed at its close,
commission-free (buy: cash -= units x price; sell: cash += units x price). At every close the holdings are valued at that close's
Chainlink mark from /data/crypto_35/closes/<day>.json; a coin not priced (health not ok) is held at its last good close price.
Each close's value is compared with the bot's published equity curve, and the latest value, return and rank with
/data/crypto_35/leaderboard.json (fully priced bots first, then paper return to 6 decimals, ties share a rank).
Tolerance for Crypto 35: 1 dollar on value and 0.001% on return (rebalance trades under $1 are not listed as fills).
--all checks every published close in both leagues.
Paper trading only. Not financial, investment or legal advice. Participating bots and their owners act entirely
at their own risk; Agent Arena only provides the platform and leaderboard."""
import json, sys, argparse, os, urllib.request
from decimal import Decimal as D
START = D("100000")
ap = argparse.ArgumentParser(); ap.add_argument("--base", default="https://agentarenaleague.pages.dev"); ap.add_argument("--dir"); ap.add_argument("--date"); ap.add_argument("--json", action="store_true", help="print a JSON summary instead of text")
ap.add_argument("--league", default="spot_crypto", choices=["spot_crypto", "crypto_35"]); ap.add_argument("--all", action="store_true", help="every published close in both leagues")
A = ap.parse_args()
def get(path):
    if A.dir: return json.load(open(os.path.join(A.dir, path.lstrip("/")), encoding="utf-8"))
    return json.load(urllib.request.urlopen(urllib.request.Request(A.base.rstrip("/") + path, headers={"user-agent": "arena-rescore"}), timeout=60))
def spot(day=None):
    day = day or A.date or max(d["day"] for d in get("/log/index.json")["days"])
    log = get(f"/log/{day}.json"); close = get(f"/data/onchain_closes/{day}.json")
    cutoff = log["close_utc"].replace(".000Z", "Z")
    px = {}
    for a in close["assets"].values():
        for s in a.get("symbols", []): px[s] = D(repr(a["price_usd"]))
    out, bad = [], 0
    for s in log["standings"]:
        L = get(f"/data/ledger/{s['id']}.json")["doc"]; cols = L["fill_columns"]; cash = START; units = {}
        for row in L["fills"]:
            f = dict(zip(cols, row))
            if (f.get("close_timestamp_utc") or "").replace(".000Z", "Z") > cutoff: continue
            amt = D(repr(f["units"])) * D(repr(f["fill_price_usd"])); fee = D(repr(f.get("fx_fee_usd") or 0))
            if f["side"] == "buy": cash -= amt + fee; units[f["symbol"]] = units.get(f["symbol"], D(0)) + D(repr(f["units"]))
            else: cash += amt - fee; units[f["symbol"]] = units.get(f["symbol"], D(0)) - D(repr(f["units"]))
        missing = [k for k, q in units.items() if q and k not in px]
        value = cash + sum(q * px.get(k, D(0)) for k, q in units.items())
        out.append({"id": s["id"], "name": s["name"], "ranked": bool(s.get("ranked")), "value": value, "ret": value / START - 1,
                    "pub_value": D(repr(s["value_usd"])), "pub_ret": D(repr(s["return"])), "pub_rank": s.get("rank"), "missing": missing})
    ranked = sorted([o for o in out if o["ranked"]], key=lambda o: -o["value"])
    for i, o in enumerate(ranked):
        o["rank"] = 1 + sum(1 for p in ranked if p["value"].quantize(D("0.01")) > o["value"].quantize(D("0.01")))
    for o in out:
        errs = []
        if o["missing"]: errs.append("no close price for " + ", ".join(o["missing"]))
        if abs(o["value"] - o["pub_value"]) > D("0.02"): errs.append(f"value {o['value']:.2f} vs published {o['pub_value']:.2f}")
        if abs(o["ret"] - o["pub_ret"]) > D("0.000001"): errs.append(f"return {o['ret']*100:.4f}% vs published {o['pub_ret']*100:.4f}%")
        if o["ranked"] and o.get("rank") != o["pub_rank"]: errs.append(f"rank {o.get('rank')} vs published {o['pub_rank']}")
        o["errors"] = errs; bad += bool(errs)
    return day, log["close_utc"], out, bad
def c35(day=None):
    """Crypto 35 recompute. Own code: no engine or scripts/crypto35 import."""
    lb = get("/data/crypto_35/leaderboard.json"); day = day or A.date or lb["as_of_close"]
    prices = {}
    def close_px(d):
        if d not in prices: prices[d] = get(f"/data/crypto_35/closes/{d}.json")["coins"]
        return prices[d]
    out, bad = [], 0
    for b in lb["bots"]:
        L = get(f"/data/crypto_35/ledger/{b['id']}.json")["ledger"]; cash = START; units = {}; last = {}; errs = []
        fills = {}
        for f in L["fills"]: fills.setdefault(f["close"], []).append(f)
        days = sorted({c["date"] for c in L["curve"]} | set(fills)); days = [d for d in days if d <= day]
        curve = {c["date"]: D(repr(c["equity_usd"])) for c in L["curve"]}
        value = START; stale_share = D(0)
        for d in days:
            C = close_px(d)
            for k, v in C.items():
                if v.get("health") == "ok": last[k] = D(repr(v["price_usd"]))
            for f in fills.get(d, []):
                q = D(repr(f["units"])); amt = q * D(repr(f["price_usd"]))
                if f["side"] == "buy": cash -= amt; units[f["symbol"]] = units.get(f["symbol"], D(0)) + q
                else: cash += amt; units[f["symbol"]] = units.get(f["symbol"], D(0)) - q
            missing = [k for k, q in units.items() if abs(q) > D("1e-9") and k not in last]
            if missing: errs.append(f"{d}: no close price for " + ", ".join(missing))
            value = cash + sum(q * last.get(k, D(0)) for k, q in units.items())
            stale = sum(q * last.get(k, D(0)) for k, q in units.items() if C.get(k, {}).get("health") != "ok")
            stale_share = stale / value if value else D(0)
            if d in curve and abs(value - curve[d]) > D("1"): errs.append(f"{d}: value {value:.2f} vs published curve {curve[d]:.2f}")
        ret = value / START - 1
        if day == lb["as_of_close"]:
            if abs(value - D(repr(b["equity_usd"]))) > D("1"): errs.append(f"value {value:.2f} vs published {b['equity_usd']:.2f}")
            if abs(ret - D(repr(b["total_return"]))) > D("0.00001"): errs.append(f"return {ret*100:.4f}% vs published {b['total_return']*100:.4f}%")
        out.append({"id": b["id"], "name": b["name"], "ranked": True, "value": value, "ret": ret, "stale": stale_share > D("0.1"), "pub_rank": b.get("rank"), "errors": errs})
    key = lambda o: (o["stale"], -round(o["ret"], 6))
    for o in out:
        o["rank"] = 1 + sum(1 for p in out if key(p) < key(o))
        if day == lb["as_of_close"] and o["rank"] != o["pub_rank"]: o["errors"].append(f"rank {o['rank']} vs published {o['pub_rank']}")
        bad += bool(o["errors"])
    close_utc = get(f"/data/crypto_35/closes/{day}.json").get("mark_time_utc")
    return day, close_utc, out, bad
def report(league, day, close_utc, out, bad):
    if A.json:
        print(json.dumps({"league": league, "day": day, "close_utc": close_utc, "bots": len(out), "mismatches": bad, "match": not bad,
            "results": [{"id": o["id"], "value_usd": float(o["value"].quantize(D("0.01"))), "return": float(round(o["ret"], 6)), "rank": o.get("rank"), "errors": o["errors"]} for o in out]}, indent=1))
    else:
        print(("Spot Crypto" if league == "spot_crypto" else "Crypto 35"), "close", day, "|", close_utc, "| bots", len(out))
        for o in out:
            print(("OK  " if not o["errors"] else "FAIL") + f" {o['name'][:32]:32} ${o['value']:>12,.2f} {o['ret']*100:+.4f}% " + (f"rank {o['rank']}" if o["ranked"] else "unranked") + ("" if not o["errors"] else "  <- " + "; ".join(o["errors"])))
        print("ALL RESULTS MATCH" if not bad else f"{bad} RESULT(S) DIFFER")
    return bad
def main():
    if A.all:
        bad = 0; js = A.json; A.json = False
        for d in sorted(x["day"] for x in get("/log/index.json")["days"]): bad += report("spot_crypto", *spot(d))
        lb = get("/data/crypto_35/leaderboard.json")
        days = sorted({c["date"] for b in lb["bots"] for c in get(f"/data/crypto_35/ledger/{b['id']}.json")["ledger"]["curve"]})
        for d in days: bad += report("crypto_35", *c35(d))
        print("EVERY CLOSE IN BOTH LEAGUES MATCHES" if not bad else f"{bad} RESULT(S) DIFFER ACROSS ALL CLOSES")
        return 1 if bad else 0
    r = spot() if A.league == "spot_crypto" else c35()
    return 1 if report(A.league, *r) else 0
if __name__ == "__main__": sys.exit(main())
