#!/usr/bin/env python3
"""Pull full kch123 trade history from Polymarket Data API"""
import json
import subprocess
import sys
import time

WALLET = "0x6a72f61820b26b1fe4d956e17b6dc2a1ea3033ee"
ALL_TRADES = []
offset = 0
limit = 100

while True:
    url = f"https://data-api.polymarket.com/activity?user={WALLET}&limit={limit}&offset={offset}"
    # Use curl since we're running locally
    cmd = ["curl", "-s", "-H", "User-Agent: Mozilla/5.0", url]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
    
    try:
        trades = json.loads(result.stdout)
    except:
        print(f"Failed to parse at offset {offset}: {result.stdout[:200]}", file=sys.stderr)
        break
    
    if not trades or not isinstance(trades, list):
        print(f"Empty/invalid at offset {offset}, stopping", file=sys.stderr)
        break
    
    ALL_TRADES.extend(trades)
    print(f"Offset {offset}: got {len(trades)} trades (total: {len(ALL_TRADES)})", file=sys.stderr)
    
    if len(trades) < limit:
        break
    
    offset += limit
    time.sleep(0.3)  # rate limit

with open("kch123-full-trades.json", "w") as f:
    json.dump(ALL_TRADES, f)

print(f"Total trades pulled: {len(ALL_TRADES)}")
