"""Reproduces the numbers in 'One Number: 90%'. Read-only GETs to the public HeLaScan API.
Usage: python3 one_number_sample.py  -> writes sample_<UTC date>.json next to this file and prints the stats.
Uses curl because python urllib gets 403 from helascan.io.
"""
import collections, datetime, json, os, subprocess, urllib.parse

B = "https://helascan.io/api/v2"
A = "0x698069f01C8F986649edBe2ad7f43513FA9C245d"


def get(path):
    out = subprocess.run(["curl", "-s", "-m", "25", B + path], capture_output=True, text=True).stdout
    return json.loads(out)


now = datetime.datetime.now(datetime.timezone.utc)
st = get("/stats")
ct = get("/addresses/" + A + "/counters")
total, mine_all = int(st["total_transactions"]), int(ct["transactions_count"])
print("snapshot_utc", now.strftime("%Y-%m-%d %H:%M"), "| total", total, "| to contract", mine_all, "| share %.1f%%" % (100 * mine_all / total),
      "| transactions_today", st["transactions_today"])

tx, q = [], ""
for _ in range(40):
    d = get("/transactions?filter=validated" + q)
    tx += d["items"]
    n = d.get("next_page_params")
    if not n:
        break
    q = "&" + urllib.parse.urlencode(n)
json.dump({"snapshot_utc": now.isoformat(), "stats": st, "counters": ct, "items": tx},
          open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "sample_%s.json" % now.strftime("%Y-%m-%d")), "w"))

mine = [t for t in tx if ((t["to"] or {}).get("hash") or "").lower() == A.lower()]
empty = [t for t in mine if t.get("raw_input") == "0x"]
zero = [t for t in empty if t["value"] == "0"]
fr = collections.Counter(t["from"]["hash"] for t in empty)
print("sample", len(tx), "from", min(t["timestamp"] for t in tx), "to", max(t["timestamp"] for t in tx))
print("to_contract", len(mine), "| empty_input", len(empty), "| zero_value", len(zero), "| nonzero_value", len(empty) - len(zero))
print("gas_used", sorted(collections.Counter(t["gas_used"] for t in empty).items()))
print("gas_price", collections.Counter(t["gas_price"] for t in empty))
print("sender_is_contract", collections.Counter(t["from"]["is_contract"] for t in empty))
print("distinct_senders", len(fr), "| busiest", fr.most_common(1)[0][1], "| senders with exactly one", sum(1 for v in fr.values() if v == 1))
print("failed", sum(1 for t in tx if t["status"] != "ok"))
print("other", collections.Counter(((t["to"] or {}).get("name"), t.get("method")) for t in tx if t not in mine))
for bn in (50000, 150000, 300000, 450000, 600000, 750000, 850000):
    it = get("/transactions?filter=validated&block_number=%d&index=0&items_count=50" % bn)["items"]
    print("slice", bn, it[0]["timestamp"][:10], "to", it[-1]["timestamp"][:10], "n", len(it), "to_contract", sum(1 for t in it if ((t["to"] or {}).get("hash") or "").lower() == A.lower()))
