#!/usr/bin/env python3
"""X monitor detail pull 2026-10-29: quoted tweets, labs detail, specific post ladders."""
import json, re
from datetime import datetime, timezone, timedelta
RAW = "/home/kiro/trend-engine/trends/x/raw"
D = json.load(open(f"{RAW}/scan_results_2026-10-29_FULL.json"))
raw = D["raw"]; q = D["qualifying"]
cutoff = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=3)
def pd_(s): return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")

def full(h, sub):
    for t in raw.get(h, []):
        if sub in (t.get("text") or ""):
            print(f"\n--- @{h} {t['createdAt']} {t.get('likeCount')}L/{t.get('retweetCount')}RT/{t.get('viewCount')}V"
                  f" reply={bool(t.get('isReply'))} ---")
            print((t.get("text") or "")[:1400])
            qt = t.get("quoted_tweet")
            if qt:
                print(f"  [QUOTED @{(qt.get('author') or {}).get('userName')}] {(qt.get('text') or '')[:700]}")
            return
    print(f"\n--- @{h} '{sub}' NOT FOUND")

full("EHuanglu", "clone any AI platform")
full("NVIDIAAI", "Nemotron 3.5 Transcribe")
full("GoogleAI", "Gemini 4 Carbon")
full("Teamily_AI", "shared context")
full("Kling_ai", "Minibots")
full("higgsfield_ai", "MADSEASON")
full("runwayml", "Runway Dev is now on Codex")
full("venturetwins", "Genie 4")
full("AIWarper", "body doubles")
full("AIWarper", "character swap")
full("c_valenzuelab", "Anthropic's S-1")
full("CharaspowerAI", "Starlight Precise")

print("\n\n=== LABS DETAIL (all in-window originals) ===")
for h in ["NVIDIAAI","OpenAI","AnthropicAI","GoogleAI","GoogleLabs"]:
    rows=[]
    for t in raw.get(h,[]):
        if t.get("retweeted_tweet") or (t.get("text") or "").startswith("RT @"): continue
        d=pd_(t["createdAt"])
        if d<cutoff: continue
        rows.append((d,t))
    rows.sort(reverse=True, key=lambda r:r[0])
    print(f"\n-- @{h} ({len(rows)} in-window originals) --")
    for d,t in rows:
        print(f"  {d.strftime('%m-%d %H:%M')} {t.get('likeCount')}L/{t.get('retweetCount')}RT/{t.get('viewCount')}V :: {(t.get('text') or '').replace(chr(10),' ')[:210]}")

print("\n\n=== CORE 21-45 (full board tail) ===")
IRR = {"AIBuzzNews","AIGuideHQ","AITECHio","AIFrontliner","TheAIColony","AITOPIAai","GoogleLabs","GoogleAI",
 "DonutAI","cladlabs","FaithJaiye2187","KammelaBala","MyStageAI","AlexStudio44","AI_with_jasmin","Ai_Vaidehi",
 "ChrisLaubAI","CINEMA505","OpenAI","AnthropicAI","AIScottAdams","AISuperDomain","AI_Jasonyu","AIByLeo"}
FILM={"DiscussingFilm","nofilmschool"}; LABS={"OpenAI","AnthropicAI","NVIDIAAI"}; OFF={"interesting_aIl","hubermanlab"}
def b(x):
    h=x["handle"]
    if h in LABS: return "labs"
    if h in OFF: return "off"
    if h in FILM: return "film"
    if h in IRR: return "irr"
    return "core"
core=sorted([x for x in q if b(x)=="core"], key=lambda x:x["score"], reverse=True)
for i,x in enumerate(core[20:45],21):
    print(f"{i}|@{x['handle']}|{x['likes']}L|{x['rt']}RT|{x['views']}V|{x['date']}|{x['score']:.0f}|{x['text'][:120]}")
print(f"\nCORE total {len(core)}")

print("\n=== PER-HANDLE QUALIFYING COUNTS ===")
from collections import Counter
c=Counter(x["handle"] for x in q)
print(", ".join(f"@{h}({n})" for h,n in sorted(c.items(), key=lambda kv:-kv[1])))

# flova paid-amplification check: like rate on all in-window flova originals
print("\n=== FLOVA LIKE RATE CHECK ===")
for t in raw["Flovaai"]:
    if t.get("retweeted_tweet") or (t.get("text") or "").startswith("RT @"): continue
    d=pd_(t["createdAt"])
    if d<cutoff: continue
    v=t.get("viewCount") or 0; l=t.get("likeCount") or 0
    print(f"  {d.strftime('%m-%d %H:%M')} {l}L/{v}V like_rate={(l/v*100 if v else 0):.3f}% reply={bool(t.get('isReply'))}")

print("\n=== INTERESTING_AIL profile ===")
tw=[t for t in raw["interesting_aIl"] if not t.get("retweeted_tweet")]
inw=[t for t in tw if pd_(t["createdAt"])>=cutoff]
from collections import Counter as C2
print("in-window originals", len(inw), "media", dict(C2((t.get("media") or [{}])[0].get("type","none") for t in inw)),
      "likes", sorted([t.get("likeCount") or 0 for t in inw], reverse=True)[:8])
