#!/usr/bin/env python3
"""For every handle whose fetched id-set was identical across 3 days, ask the
advanced_search endpoint how many posts it ACTUALLY made since 2026-11-07.
0 = genuinely quiet (real signal). >0 = the user/tweets route was serving a stale page."""
import os, time, json
import requests
from datetime import datetime, timezone

ENV = os.path.expanduser("~/.hermes/.env")
API_KEY = [l.strip().split("=",1)[1] for l in open(ENV) if l.startswith("GETXAPI_KEY=")][0]
H = {"Authorization": f"Bearer {API_KEY}"}
def pdt(s):
    try: return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")
    except Exception: return None

FROZEN = ['AIByLeo','AIFrontliner','AITOPIAai','AIWarper','Ai_Vaidehi','AidenChaoyangHe',
 'AlexStudio44','AnthropicAI','CuriousRefuge','DonutAI','EinsiaAI','FaithJaiye2187','Flovaai',
 'GoogleAI','GoogleLabs','ItsMaryamAi','KammelaBala','OpenAI','Teamily_AI','TheAIColony',
 'WuxiaRocks','cladlabs','different_ai','higgsfield','higgsfield_ai','karenxcheng','numerai',
 'openart_ai','perplexity_ai','pika_labs','runwayml','via_ai_','AI__TSUBAKI','Nevermined_ai',
 'heyglif','c_valenzuelab','dai2noyuyuta']

out = {}
for h in FROZEN:
    try:
        r = requests.get("https://api.getxapi.com/twitter/tweet/advanced_search", headers=H,
                         params={"q": f"from:{h} since:2026-11-07", "count": 20}, timeout=60)
        if r.status_code != 200:
            print(f"{h:20s} HTTP {r.status_code}"); time.sleep(1); continue
        tw = r.json().get("tweets", [])
        ds = [d for d in (pdt(t.get("createdAt","")) for t in tw) if d]
        mx = max(ds).strftime('%m-%d %H:%M') if ds else '-'
        verd = "GENUINELY QUIET" if not tw else "STALE-PAGE (has posts)"
        out[h] = (len(tw), mx, verd)
        print(f"{h:20s} posts_since_11-07={len(tw):2d} newest={mx} -> {verd}")
        if tw:
            for t in sorted(tw, key=lambda x: pdt(x["createdAt"]))[-3:]:
                print(f"      MISSED {t['createdAt'][:19]} {t['likeCount']}L/{t['viewCount']}V :: {(t.get('text') or '')[:120]}")
    except Exception as e:
        print(f"{h:20s} ERR {e}")
    time.sleep(1.0)

missed = {h:v for h,v in out.items() if v[0] > 0}
print("\n=== handles with posts the user/tweets route MISSED:", len(missed))
for h,v in sorted(missed.items(), key=lambda kv:-kv[1][0]):
    print(f"  {h}: {v[0]} posts")
json.dump({k:{"n":v[0],"newest":v[1]} for k,v in out.items()}, open("/home/kiro/trend-engine/trends/x/raw/stalecheck_2026-11-09.json","w"), indent=1)
