#!/usr/bin/env python3
"""Alpha Arena season 1 under prop-firm challenge rules: would any of the six accounts have passed?

Served at https://oaia.fun/recompute_alpha_prop.py. Python 3, standard library only.

Input: alpha_arena_anchor.json (served beside this script), which holds Nof1's own reading of each
model's account equity about once an hour, from the Internet Archive's 2025-11-06 02:27:15Z capture
of https://nof1.ai/api/account-totals. Readings after the bell (2025-11-03 22:00:00Z) are dropped.

Rules, the common shape of a one-step challenge, not any one firm's current terms:
  start      $10,000
  total loss the challenge fails when equity is at or below $9,000 (10% of the start)
  daily loss the challenge fails when equity is at or below 95% of the day's reference: the last
             reading before the day began ($10,000 on the first day)
  target     the challenge passes when equity is at or above the target and at least min_days
             calendar days have held a reading, counting the first day
Each reading is checked in time order, total loss first, then daily loss, then the target. The first
event ends the challenge. Three rule sets (+10% any day, +10% after 4 days, +8% any day), each run
with the day starting at 00:00, 23:00 and 22:00 UTC, because firms reset at their own midnight.

Limits, also on the page: one reading an hour misses every dip and spike between readings, so a
breach or a target inside an hour can be missed, and their order inside the hour is unknown. The
equity includes small transfers from other wallets ($1 to $195 per account), which are not removed.

Usage, in a folder holding alpha_arena_anchor.json and alpha_arena_prop.json:
  python3 recompute_alpha_prop.py          rebuild every row; exit code 0 means all match alpha_arena_prop.json
  python3 recompute_alpha_prop.py --write  rebuild and replace alpha_arena_prop.json
"""
import datetime as dt
import hashlib
import json
import sys

ANCHOR = "alpha_arena_anchor.json"
RESULT = "alpha_arena_prop.json"
BELL = 1762207200  # 2025-11-03 22:00:00Z, the bell recompute_alpha_arena.py and recompute_alpha_anchor.py use
START = 10000.0
DAILY = 0.05
TOTAL = 0.10
RULES = [
    {"id": "t10", "target": 0.10, "min_days": 0},
    {"id": "t10m4", "target": 0.10, "min_days": 4},
    {"id": "t8", "target": 0.08, "min_days": 0},
]
RESETS = [0, 23, 22]  # UTC hour at which a new day begins


def stamp(t):
    return dt.datetime.fromtimestamp(t, dt.timezone.utc).strftime("%Y-%m-%d %H:%MZ")


def day_key(t, reset):
    return dt.datetime.fromtimestamp(t + ((24 - reset) % 24) * 3600, dt.timezone.utc).date().isoformat()


def challenge(readings, target, min_days, reset):
    ref, prev, cur, days = START, START, None, set()
    for t, e in readings:
        d = day_key(t, reset)
        if d != cur:
            ref = prev if cur is not None else START
            cur = d
            days.add(d)
        if e <= START * (1 - TOTAL):
            return {"event": "FAIL total", "at": stamp(t), "equity": round(e, 2), "day": len(days)}
        if e <= ref * (1 - DAILY):
            return {"event": "FAIL daily", "at": stamp(t), "equity": round(e, 2), "day": len(days),
                    "drop_pct": round((ref - e) / ref * 100, 1)}
        if e >= START * (1 + target) and len(days) >= min_days:
            return {"event": "PASS", "at": stamp(t), "equity": round(e, 2), "day": len(days)}
        prev = e
    return {"event": "OPEN", "at": stamp(readings[-1][0]), "equity": round(readings[-1][1], 2), "day": len(days)}


def unstopped(readings, reset):
    """If nobody stopped the account: how many days broke the daily rule, and the worst day."""
    ref, prev, cur, worst, over, n = START, START, None, (0.0, ""), set(), set()
    for t, e in readings:
        d = day_key(t, reset)
        if d != cur:
            ref = prev if cur is not None else START
            cur = d
            n.add(d)
        drop = (ref - e) / ref
        if drop >= DAILY:
            over.add(d)
        if drop > worst[0]:
            worst = (drop, d)
        prev = e
    return {"days": len(n), "days_over": len(over), "worst_pct": round(worst[0] * 100, 1), "worst_day": worst[1]}


def build(raw):
    anchor = json.loads(raw)
    models = {}
    for name, v in anchor["models"].items():
        r = [(x[0], x[1]) for x in v["readings"] if x[0] <= BELL]
        models[name] = {
            "readings": len(r),
            "first": {"at": stamp(r[0][0]), "equity": round(r[0][1], 2)},
            "last": {"at": stamp(r[-1][0]), "equity": round(r[-1][1], 2)},
            "low": round(min(e for _, e in r), 2),
            "high": round(max(e for _, e in r), 2),
            "runs": {f"{rule['id']}@{reset:02d}": challenge(r, rule["target"], rule["min_days"], reset)
                     for reset in RESETS for rule in RULES},
            "unstopped": {f"{reset:02d}": unstopped(r, reset) for reset in RESETS},
        }
    return {"anchor_sha256": hashlib.sha256(raw).hexdigest(), "capture": anchor["capture"],
            "bell": BELL, "start": START, "daily_pct": DAILY * 100, "total_pct": TOTAL * 100,
            "rules": RULES, "resets_utc": RESETS, "models": models}


def main():
    raw = open(ANCHOR, "rb").read()
    doc = build(raw)
    for name, m in doc["models"].items():
        print(f"{name:18} last {m['last']['equity']:>10,.2f}  " +
              "  ".join(f"{k}:{v['event']}@{v['at'][5:]}" for k, v in m["runs"].items() if k.endswith("@00")))
    if "--write" in sys.argv[1:]:
        with open(RESULT, "w") as f:
            json.dump(doc, f, indent=1, sort_keys=True)
            f.write("\n")
        print(f"wrote {RESULT}")
        return 0
    want = json.load(open(RESULT))
    bad = [k for k in sorted(set(want) | set(doc)) if want.get(k) != doc.get(k)]
    if bad:
        print("MISMATCH in " + ", ".join(bad))
        return 1
    print(f"all rows match {RESULT}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
