#!/usr/bin/env python3
"""Probe for a NON-CACHED route to a handle's recent tweets.
The user/tweets endpoint appears to be serving a page cached around 2026-11-07 06:00 UTC
for high-cadence handles (32 handles show byte-identical id sets across 3 days while
their view counts keep rising). Try alternate params and the search endpoint."""
import os, json, time
import requests
from datetime import datetime, timezone

ENV = os.path.expanduser("~/.hermes/.env")
API_KEY = None
for line in open(ENV):
    if line.startswith("GETXAPI_KEY="):
        API_KEY = line.strip().split("=", 1)[1]
        break
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

def show(tag, r):
    print(f"\n--- {tag} -> HTTP {r.status_code}")
    if r.status_code != 200:
        print("   ", r.text[:300]); return None
    try: j = r.json()
    except Exception:
        print("   ", r.text[:300]); return None
    tw = j.get("tweets", j) if isinstance(j, dict) else j
    if isinstance(tw, dict): tw = list(tw.values())
    if not isinstance(tw, list):
        print("   keys:", list(j.keys())[:20] if isinstance(j, dict) else type(j)); return None
    ds = [pdt(t.get("createdAt","")) for t in tw if t.get("createdAt")]
    ds = [d for d in ds if d]
    print(f"    n={len(tw)} max={max(ds).strftime('%m-%d %H:%M') if ds else 'NA'} "
          f"min={min(ds).strftime('%m-%d %H:%M') if ds else 'NA'}")
    for t in sorted(tw, key=lambda t: pdt(t.get("createdAt","")) or datetime.min.replace(tzinfo=timezone.utc))[-4:]:
        print(f"      {t.get('createdAt','')[:19]} {t.get('likeCount')}L/{t.get('viewCount')}V :: {(t.get('text') or '')[:110]}")
    return tw

base = "https://api.getxapi.com/twitter/user/tweets"
show("count=20", requests.get(base, headers=H, params={"userName":"higgsfield","count":20}, timeout=60))
time.sleep(1)
show("count=5&includeReplies=false", requests.get(base, headers=H, params={"userName":"higgsfield","count":5,"includeReplies":"false"}, timeout=60))
time.sleep(1)

for path in ["/twitter/tweet/advanced_search", "/twitter/tweet/search", "/twitter/search"]:
    for q in ["from:higgsfield since:2026-11-07", "from:higgsfield"]:
        try:
            r = requests.get("https://api.getxapi.com"+path, headers=H,
                             params={"query": q, "count": 20}, timeout=60)
            tw = show(f"{path} q={q}", r)
            if tw: break
        except Exception as e:
            print(path, "ERR", e)
        time.sleep(1)
    else:
        continue
    break
