"""Print OpenRouter key usage (USD) for the key in OPENROUTER_API_KEY. Never prints the key.
  python spend.py            -> prints current usage
  python spend.py --since X  -> prints usage and usage minus X"""
import json, os, sys, urllib.request
req = urllib.request.Request("https://openrouter.ai/api/v1/key",
                             headers={"Authorization": "Bearer " + os.environ["OPENROUTER_API_KEY"]})
d = json.load(urllib.request.urlopen(req, timeout=30))["data"]
u = float(d.get("usage") or 0.0)
out = {"usage": round(u, 6), "limit": d.get("limit"), "limit_remaining": d.get("limit_remaining")}
if len(sys.argv) > 2 and sys.argv[1] == "--since":
    out["delta"] = round(u - float(sys.argv[2]), 6)
print(json.dumps(out))
