"""Estimate spend from logged usage and the AI Gateway list prices in models.json."""
import json,sys,collections
P={m["id"]:m.get("pricing",{}) for m in json.load(open("models.json"))["data"]}
tot=collections.Counter(); n=collections.Counter()
for f in sys.argv[1:]:
    for l in open(f):
        r=json.loads(l); u=r["usage"]; p=P[r["model"]]
        cached=(u.get("prompt_tokens_details") or {}).get("cached_tokens",0) or 0
        c=(u.get("prompt_tokens",0))*float(p["input"])+u.get("completion_tokens",0)*float(p["output"])
        if u.get("cost") is not None: c=float(u["cost"])
        tot[r["model"]]+=c; n[r["model"]]+=1
for m in tot: print(f"{m:40s} calls={n[m]:5d} ${tot[m]:.3f}")
print("TOTAL $%.3f"%sum(tot.values()))
