"""Python 3 + matplotlib. Run: python chart.py funding"""
import datetime, email.utils, json, math, sys, time
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
import matplotlib
import matplotlib.pyplot as plt

recipes = {
    "funding": ({"coin":"HYPE", "days":1, "limit":24}, "hour", "fundingPercentHourly", "HYPE hourly funding (%)"),
    "markets": ({"kind":"native", "limit":100}, "id", "openInterestQuote", "Native open interest (USDC)"),
    "ecosystem": ({"limit":100}, "name", "tvlUsd", "Indexed protocol TVL (USD)"),
}
name = sys.argv[1]
query, x, y, title = recipes[name]
def collect():
    receipts, seen = [], set()
    while True:
        request = Request("https://liquid-data.xyz/api/v1/"+name+"?"+urlencode(query), headers={"Accept":"application/json","User-Agent":"LiquidDataChartRecipe/1"})
        for attempt in range(4):
            try:
                with urlopen(request, timeout=20) as response:
                    body = json.load(response)
                break
            except HTTPError as err:
                if err.code not in (429,503) or attempt==3:
                    raise
                raw = err.headers.get("Retry-After")
                delay = 2**attempt
                if raw:
                    try:
                        delay = int(raw) if raw.isdigit() else email.utils.parsedate_to_datetime(raw).timestamp()-time.time()
                    except (ValueError, TypeError):
                        pass
                if delay>120:
                    raise RuntimeError("Retry later according to Retry-After") from err
                time.sleep(max(0,delay)+0.1)
        if not isinstance(body.get("data"),list) or body.get("status")=="unavailable":
            raise RuntimeError("No usable data")
        points=[[str(r[x]),r[y]] for r in body["data"]
                if type(r.get(y)) in (int,float) and math.isfinite(r[y])
                and (name!="markets" or r.get("quote")=="USDC")]
        receipt={k:body.get(k) for k in ("source","asOf","status","coverage","window","limitations","meta","requestId")}
        receipts.append({**receipt,"url":request.full_url,"points":points})
        page = body.get("pagination") or {}
        cursor = page.get("nextCursor")
        if not cursor:
            if page.get("hasMore"): raise RuntimeError("Missing next cursor")
            break
        if cursor in seen: raise RuntimeError("Repeated cursor")
        seen.add(cursor)
        query["cursor"]=cursor
    return receipts

receipt_path = name+".receipts.json"
if sys.argv[2:] == ["--replay"]:
    with open(receipt_path) as source:
        receipts=json.load(source)
else:
    receipts=collect()
    with open(receipt_path,"w") as out:
        json.dump(receipts,out,indent=2)
points=[point for page in receipts for point in page["points"]]
matplotlib.rcParams["svg.hashsalt"]="liquid-data-recipes-v1"
fig,ax=plt.subplots(layout="constrained")
if points and name=="funding":
    ax.scatter([datetime.datetime.fromisoformat(k.replace("Z","+00:00")) for k,_ in points],[v for _,v in points])
    fig.autofmt_xdate()
elif points:
    shown=sorted(points,key=lambda p:p[1],reverse=True)[:10]
    ax.barh([k for k,_ in shown],[v for _,v in shown]); ax.invert_yaxis()
else:
    ax.text(.5,.5,"No returned observations",ha="center",transform=ax.transAxes)
ax.set_title(title)
fig.savefig(name+".svg",metadata={"Date":None})
