#!/usr/bin/env python3
"""reproduce_tm_clawhunt_20260928.py — verify the 2026-09-28 TM+Clawhunt re-measure.

Stdlib-only, read-only.
  Section 1 (anonymous): taskmarket.dev public task list — counts of
    status/phase/submissionWindowOpen, reward stats, escrow presence,
    fee bps, submission totals, oldest awaiting_settlement rows.
  Section 2 (needs any Clawhunt account's cph_ API key in CLAWHUNT_KEY):
    clawhunt.store problem list — status/escrow_status counts, claimed
    USD escrow sum, bid totals, routing modes, oldest problem.
"""
import json, os, sys, urllib.request, urllib.parse, collections, datetime

UA = {"User-Agent": "ARION-repro/1.0"}

def get(url, headers=None):
    h = dict(UA); h.update(headers or {})
    req = urllib.request.Request(url, headers=h)
    return json.load(urllib.request.urlopen(req, timeout=25))

print("== taskmarket.dev (anonymous) ==")
tasks, cursor = [], None
for _ in range(10):
    url = "https://api.taskmarket.dev/api/tasks?limit=100" + (
        f"&cursor={urllib.parse.quote(cursor)}" if cursor else "")
    r = get(url)
    batch = r.get("tasks") or []
    tasks += batch
    cursor = r.get("nextCursor")
    if not cursor or not batch:
        break

print("fetched", len(tasks), "at", datetime.datetime.utcnow().isoformat()[:19] + "Z")
print("status:", dict(collections.Counter(t.get("status") for t in tasks)))
print("phase:", dict(collections.Counter(t.get("phase") for t in tasks)))
print("requesterActorType:", dict(collections.Counter(t.get("requesterActorType") for t in tasks)))
print("windowOpen among 'open':",
      sum(1 for t in tasks if t["status"] == "open" and t.get("submissionWindowOpen")),
      "/ total windowOpen:",
      sum(1 for t in tasks if t.get("submissionWindowOpen")))
rw = [int(t.get("reward") or 0) for t in tasks]
print("reward micros: min", min(rw), "max", max(rw), "sum", sum(rw), "median", sorted(rw)[len(rw)//2])
print("feeBps:", dict(collections.Counter(t.get("platformFeeBps") for t in tasks)))
print("escrowTxHash present:", sum(1 for t in tasks if t.get("escrowTxHash")))
print("subs total:", sum(t.get("submissionCount") or 0 for t in tasks))
aw = [t for t in tasks if t.get("phase") == "awaiting_settlement"]
for t in sorted(aw, key=lambda x: x.get("expiryTime") or "")[:3]:
    print("oldest awaiting:", t["referenceCode"], t.get("expiryTime"),
          "subs", t.get("submissionCount"), "reward", t.get("reward"))
comp = [t for t in tasks if t["status"] == "completed"]
print("awardCount dist:", collections.Counter(t.get("awardCount") for t in comp).most_common())

print()
print("== clawhunt.store (needs CLAWHUNT_KEY env) ==")
key = os.environ.get("CLAWHUNT_KEY", "")
if not key:
    print("CLAWHUNT_KEY not set — skipped (any account's cph_ key works)")
    sys.exit(0)
probs, off = [], 0
while True:
    r = get(f"https://clawhunt.store/api/v1/problems?limit=100&offset={off}",
            {"Authorization": f"Bearer {key}"})
    d = r["data"]; probs += d["problems"]
    if not d.get("has_more"):
        break
    off += d["limit"]
print("fetched", len(probs))
print("status:", dict(collections.Counter(p.get("status") for p in probs)))
print("escrow_status:", dict(collections.Counter(p.get("escrow_status") for p in probs)))
pr = [float(p.get("price") or 0) for p in probs]
print("claimed USD escrow: nonzero", sum(1 for x in pr if x > 0), "sum", round(sum(pr), 2), "max", max(pr))
print("bids total:", sum(p.get("bid_count") or 0 for p in probs))
print("routing:", dict(collections.Counter(
    (p.get("routing_mode"), p.get("current_routing_round")) for p in probs)))
ages = sorted(p.get("created_at", "") for p in probs)
print("oldest:", ages[0], "newest:", ages[-1])
