#!/usr/bin/env python3
"""Chronologies + full text for key handles; venturetwins retry; trend."""
import json, re, os, time
import requests
from datetime import datetime, timezone, timedelta

DATE = "2026-11-07"
RAW = "/home/kiro/trend-engine/trends/x/raw"
FMT = "%a %b %d %H:%M:%S %z %Y"
D = json.load(open(f"{RAW}/scan_results_{DATE}_FULL.json"))
res = D["raw"]

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

# retry venturetwins
print("=== VENTURETWINS RETRY ===")
for attempt in range(3):
    try:
        r = requests.get("https://api.getxapi.com/twitter/user/tweets",
                         params={"userName": "venturetwins", "count": 5},
                         headers={"Authorization": f"Bearer {API_KEY}"}, timeout=60)
        if r.status_code == 200:
            tw = r.json().get("tweets") or []
            print(f"OK {len(tw)} tweets")
            for t in tw[:12]:
                d = datetime.strptime(t["createdAt"], FMT)
                print(f"  {d.strftime('%m-%d %H:%M')} {t.get('likeCount',0)}L/{t.get('viewCount',0)}V "
                      f"{(t.get('text') or '')[:160]}")
            json.dump(tw, open(f"{RAW}/vt_retry_{DATE}.json","w"))
            break
        else:
            print(f"attempt{attempt} HTTP {r.status_code}")
    except Exception as e:
        print("err", e)
    time.sleep(3)

KEY = ["higgsfield", "higgsfield_ai", "perplexity_ai", "Kling_ai", "EinsiaAI",
       "AiWithTariq", "CharaspowerAI", "Flovaai", "pika_labs", "runwayml",
       "EHuanglu", "AIWarper", "heyglif", "azed_ai", "ElsaSofia__AI", "openart_ai",
       "CuriousRefuge", "c_valenzuelab", "GoogleAI"]
cutoff = datetime.strptime(f"{DATE} 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z") - timedelta(days=3)

for h in KEY:
    tw = res.get(h) or []
    if not tw:
        print(f"\n### @{h} -- no data")
        continue
    inwin = [t for t in tw if datetime.strptime(t["createdAt"], FMT) >= cutoff]
    print(f"\n### @{h}  ({len(inwin)} in-window of {len(tw)})")
    for t in sorted(inwin, key=lambda x: x["createdAt"]):
        d = datetime.strptime(t["createdAt"], FMT)
        med = (t.get("media") or [{}])
        mt = med[0].get("type") if med else None
        rt = " RT" if t.get("retweeted_tweet") else ""
        rp = " REPLY" if t.get("isReply") else ""
        qt = " QUOTE" if t.get("quoted_tweet") else ""
        print(f"  {d.strftime('%m-%d %H:%M')} {t.get('likeCount',0)}L/{t.get('retweetCount',0)}RT/"
              f"{t.get('replyCount',0)}R/{t.get('viewCount',0)}V [{mt}]{rt}{rp}{qt}")
        print(f"    {(t.get('text') or '')[:700].replace(chr(10),' | ')}")
        if t.get("quoted_tweet"):
            qt_ = t["quoted_tweet"]
            print(f"    >>QUOTE @{(qt_.get('author') or {}).get('userName')}: {(qt_.get('text') or '')[:400]}")

print("\n=== TREND (qualifying by date) ===")
import glob
for f in sorted(glob.glob(f"{RAW}/scan_results_*_FULL.json"))[-16:]:
    try:
        j = json.load(open(f))
        q = len(j.get("qualifying") or [])
        print(f"  {os.path.basename(f)[13:23]}  {q}")
    except Exception as e:
        print(f"  {f}: {e}")
