import json,datetime,collections
UTC=datetime.timezone.utc
# verified cards from remakebench-harness (rates_usd_per_million_tokens, verified_live_pricing)
CARD={"claude-opus-5":(5,6.25,10,.5,25), "claude-opus-5-5":(4,5,8,.2,20),
      "claude-fable-5-1":(10,12.5,20,.25,50), "claude-fable-5":(10,12.5,20,1.0,50),
      "claude-sonnet-5":(2,2.5,4,.2,10),
      "claude-haiku-4-5-20251001":(1,1.25,2,.1,5), "claude-haiku-4-5":(1,1.25,2,.1,5)}
recs=json.load(open("recs.json"))
for r in recs: r["dt"]=datetime.datetime.fromisoformat(r["dt"])
def cost(r):
    c=CARD.get(r["model"])
    if not c: return None
    i,w5,w1,rd,o=c
    return (r["inp"]*i+r["w5"]*w5+r["w1"]*w1+r["rd"]*rd+r["out"]*o)/1e6
unpriced=collections.Counter()
for r in recs:
    v=cost(r)
    if v is None: unpriced[r["model"]]+=1; v=0.0
    r["cost"]=v
if unpriced: print("UNPRICED:",dict(unpriced))

RESET=datetime.datetime(2026,10,1,0,59,59,tzinfo=UTC)
START=RESET-datetime.timedelta(days=7)
NOW=max(r["dt"] for r in recs)
cur=[r for r in recs if START<=r["dt"]<RESET]
tot=sum(r["cost"] for r in cur)
fab=sum(r["cost"] for r in cur if r["model"].startswith("claude-fable"))
print(f"\nWINDOW  {START:%Y-%m-%d %H:%M} -> {RESET:%Y-%m-%d %H:%M} UTC   (latest record {NOW:%Y-%m-%d %H:%M})")
print(f"elapsed {(NOW-START).total_seconds()/3600:.1f}h of 168h ({(NOW-START).total_seconds()/3600/168*100:.1f}% of wall clock)")
print(f"measured API-equivalent in window: ${tot:,.2f}   ({len(cur):,} responses)")
print("\nby model:")
bm=collections.defaultdict(lambda:[0.0,0])
for r in cur: bm[r["model"]][0]+=r["cost"]; bm[r["model"]][1]+=1
for k,(v,n) in sorted(bm.items(),key=lambda x:-x[1][0]): print(f"   {k:28s} ${v:9,.2f}  n={n:,}")

print("\n=== ALLOWANCE (Codex method: measured spend / reported quota %) ===")
for lbl,spend,pct in [("Weekly · all models",tot,0.58),("Weekly · Fable",fab,0.06)]:
    full=spend/pct
    print(f"  {lbl:22s} {pct*100:.0f}% used = ${spend:9,.2f}  ->  full week ${full:10,.2f}   remaining ${full*(1-pct):9,.2f}")
    lo,hi=spend/(pct+0.005), spend/(pct-0.005)
    print(f"  {'':22s} display-rounding band: ${lo:,.0f} .. ${hi:,.0f}")
print(f"\n  monthly (x4) all-models: ${tot/0.58*4:,.0f}    vs $200 fee => {tot/0.58*4/200:.0f}x")
json.dump({"window_start":START.isoformat(),"reset":RESET.isoformat(),"measured":tot,
           "fable_measured":fab,"allowance":tot/0.58,"fable_allowance":fab/0.06},open("allowance.json","w"),indent=2)
