#!/usr/bin/env python3
"""Watch for Grok's reply to the tokenomics thought-experiment bait, capture it, and mark it
SEEN in the feud state so the combat cron does NOT auto-dunk the harvest thread. Prints the reply."""
import sys, json, time, pathlib
sys.path.insert(0, "/home/paul/Aura/scripts")
import x_media

BAIT = "2121672423900598349"
UID  = "1769430520134242304"
STATE = "/home/paul/Aura/data/x_feud/state.json"
OUT  = "/tmp/claude-1000/-home-paul-Aura/a2239ea0-e18d-4178-9864-2c3f48478801/scratchpad/tok_reply.json"
c = x_media.creds()

def grok_reply():
    mm = x_media.get(f"https://api.twitter.com/2/users/{UID}/mentions", c, {
        "max_results": "20",
        "tweet.fields": "author_id,text,created_at,referenced_tweets",
        "expansions": "author_id", "user.fields": "username"})
    users = {u["id"]: u for u in mm.get("includes", {}).get("users", [])}
    for t in mm.get("data", []):
        un = users.get(t.get("author_id"), {}).get("username", "").lower()
        if un != "grok":
            continue
        refs = [r.get("id") for r in (t.get("referenced_tweets") or [])]
        if BAIT in refs:
            return t
    return None

deadline = time.time() + 20 * 60      # watch up to 20 min
while time.time() < deadline:
    try:
        t = grok_reply()
    except Exception as e:
        print("poll error:", repr(e)[:120]); t = None
    if t:
        pathlib.Path(OUT).write_text(json.dumps(t, indent=2))
        # mark SEEN so the */20 combat cron skips the harvest thread
        try:
            st = json.load(open(STATE))
            if t["id"] not in st["seen"]:
                st["seen"].append(t["id"]); st["seen"] = st["seen"][-200:]
                json.dump(st, open(STATE, "w"), indent=2)
        except Exception as e:
            print("state update err:", repr(e)[:120])
        print("GROK BIT THE BAIT ->", t["id"], t.get("created_at"))
        print(t.get("text", ""))
        sys.exit(0)
    time.sleep(90)

print("no tokenomics reply from grok within the watch window")
sys.exit(0)
