#!/usr/bin/env python3
"""Track kch123's new trades and log them"""
import json
import os
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

WALLET = "0x6a72f61820b26b1fe4d956e17b6dc2a1ea3033ee"
DATA_DIR = Path(__file__).parent / "data" / "kch123-tracking"
TRADES_FILE = DATA_DIR / "all-trades.json"
NEW_FILE = DATA_DIR / "new-trades.json"
STATS_FILE = DATA_DIR / "stats.json"

def fetch_recent(limit=50):
    url = f"https://data-api.polymarket.com/activity?user={WALLET}&limit={limit}"
    r = subprocess.run(["curl", "-s", "-H", "User-Agent: Mozilla/5.0", url],
                       capture_output=True, text=True, timeout=15)
    return json.loads(r.stdout)

def main():
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    
    # Load known trades
    known_hashes = set()
    all_trades = []
    if TRADES_FILE.exists():
        with open(TRADES_FILE) as f:
            all_trades = json.load(f)
        known_hashes = {t.get("transactionHash", "") + str(t.get("outcomeIndex", "")) for t in all_trades}
    
    # Fetch recent
    recent = fetch_recent(100)
    
    new_trades = []
    for t in recent:
        key = t.get("transactionHash", "") + str(t.get("outcomeIndex", ""))
        if key not in known_hashes:
            new_trades.append(t)
            known_hashes.add(key)
            all_trades.append(t)
    
    # Save updated trades
    with open(TRADES_FILE, "w") as f:
        json.dump(all_trades, f)
    
    # Save new trades for alerting
    with open(NEW_FILE, "w") as f:
        json.dump(new_trades, f)
    
    # Update stats
    stats = {}
    if STATS_FILE.exists():
        with open(STATS_FILE) as f:
            stats = json.load(f)
    
    stats["last_check"] = datetime.now(timezone.utc).isoformat()
    stats["total_tracked"] = len(all_trades)
    stats["new_this_check"] = len(new_trades)
    
    with open(STATS_FILE, "w") as f:
        json.dump(stats, f, indent=2)
    
    # Output for alerting
    if new_trades:
        buys = [t for t in new_trades if t.get("type") == "TRADE" and t.get("side") == "BUY"]
        redeems = [t for t in new_trades if t.get("type") == "REDEEM"]
        
        print(f"NEW TRADES: {len(new_trades)} ({len(buys)} buys, {len(redeems)} redeems)")
        for t in buys:
            print(f"  BUY ${t.get('usdcSize',0):,.2f} | {t.get('title','')} ({t.get('outcome','')})")
        for t in redeems:
            amt = t.get('usdcSize', 0)
            status = "WIN" if amt > 0 else "LOSS"
            print(f"  REDEEM ${amt:,.2f} [{status}] | {t.get('title','')}")
    else:
        print("NO_NEW_TRADES")

if __name__ == "__main__":
    main()
