#!/usr/bin/env python3
"""X monitor 2026-10-19 part 2: offer grep + top-10 author/media verification + arrival check.
NOTE raw records key the account as `author.userName`, NOT `handle`."""
import json, re
from datetime import datetime, timezone, timedelta

DATE = "2026-10-19"
d = json.load(open(f"/home/kiro/trend-engine/trends/x/raw/scan_results_{DATE}_FULL.json"))
raw, q = d["raw"], d["qualifying"]
FMT = "%a %b %d %H:%M:%S %z %Y"
def dt(s):
    try: return datetime.strptime(s, FMT)
    except Exception: return None
now = datetime.now(timezone.utc)
cutoff = datetime(2026, 10, 16, tzinfo=timezone.utc)

IRR = {"AIBuzzNews","AIGuideHQ","AITECHio","AIFrontliner","TheAIColony","AITOPIAai","AISuperDomain",
 "GoogleLabs","GoogleAI","DonutAI","cladlabs","FaithJaiye2187","KammelaBala","MyStageAI","AlexStudio44",
 "AI_with_jasmin","Ai_Vaidehi","ChrisLaubAI","OpenAI","AnthropicAI","CINEMA505","AIScottAdams","AI_Jasonyu","AIByLeo"}
FILM = {"DiscussingFilm","nofilmschool"}

def recs():
    for h, tw in raw.items():
        for t in tw:
            yield h, t

print("===== OFFER / ARBITRAGE GREP (offer phrase, not bare brand) =====")
OFFERS = {
 "Flova x Seedance 2.5 promo": [r"flova.{0,60}seedance|seedance 2\.5.{0,60}flova|80%|kicks off|days to go"],
 "Higgsfield Genjutsu API": [r"genjutsu"],
 "Higgsfield Wan 3.0 UNLIMITED": [r"wan 3\.0"],
 "Higgsfield API cashback": [r"cashback"],
 "Higgsfield Ads Studio / Ad Multiplier": [r"ads studio|ad multiplier"],
 "Higgsfield AI Influencer free gens": [r"ai influencer"],
 "FLUX 3 Upscaler exclusive": [r"flux 3|upscal"],
 "Higgsfield Academy (free)": [r"higgsfield academy|higgsfield\.ai/academy"],
 "CapCut Black Friday 60/40": [r"capcut"],
 "Dreamina $1.50/mo Basic": [r"\$1\.50|dreamina.{0,50}basic|basic promotion"],
 "Dreamina Originals program": [r"dreamina originals"],
 "Dolphin AI referral XX-AYCMR8": [r"xx-aycmr8|dolphin"],
 "Air unlimited credits": [r"air unlimited|unlimited credits"],
 "Kling 4.0 (model, not offer)": [r"kling 4\.0"],
 "DeepSeek V4.1 Flash": [r"deepseek v4\.1 flash"],
 "freebeat Lyric Video Challenge": [r"freebeat|lyric video challenge"],
 "AITECHio ACN / GPU credits": [r"\bacn\b|gpu credits"],
 "filmera free template": [r"filmera"],
 "Higgsfield Film Festival": [r"film festival|audience choice"],
}
for name, pats in OFFERS.items():
    hits = []
    for h, t in recs():
        txt = str(t.get("text", "")); low = txt.lower()
        if any(re.search(p, low, re.I) for p in pats):
            hits.append((h, t.get("likeCount",0), t.get("viewCount",0), dt(t.get("createdAt","")), txt))
    print(f"\n[{name}] {len(hits)} hit(s)")
    for h,l,v,c,txt in sorted(hits, key=lambda x:-(x[2] or 0))[:5]:
        print(f"   @{h} {l}L/{v}V {c.strftime('%m-%d %H:%M') if c else '?'} :: {' '.join(txt.split())[:200]}")

print("\n\n===== CORE TOP 10: author / media / own-baseline verification =====")
core_q = [t for t in q if t["handle"] not in IRR and t["handle"] not in FILM]
core_q.sort(key=lambda t: -t["score"])
for i, t in enumerate(core_q[:10], 1):
    h = t["handle"]; tid = t["url"].rsplit("/",1)[-1]
    m = next((x for x in raw.get(h,[]) if str(x.get("id"))==tid), {})
    author = (m.get("author") or {}).get("userName") if isinstance(m.get("author"), dict) else m.get("author")
    media = m.get("media"); rt = m.get("retweeted_tweet"); qt = m.get("quoted_tweet")
    media_desc = [ (x.get("type") if isinstance(x,dict) else str(x)) for x in media ] if media else None
    others = [x.get("likeCount",0) for x in raw.get(h,[]) if str(x.get("id"))!=tid]
    base = max(others) if others else 0
    ratio = (t["likes"]/base) if base else float("inf")
    print(f"{i}. @{h} {t['likes']}L/{t['views']}V score={t['score']:.0f} posted {t['date']}")
    print(f"   author={author!r} media={media_desc} RT={'Y' if rt else 'N'} quote={'Y' if qt else 'N'} acct_maxOther={base}L ratio={ratio:.1f}x")
    print(f"   {' '.join(str(t['text']).split())[:160]}")

print("\n===== ARRIVAL CHECK =====")
print("core top-10 handles:", [t["handle"] for t in core_q[:10]])
for h in sorted(IRR):
    n = sum(1 for t in q if t["handle"]==h)
    if n: print(f"  filtered-tier @{h}: {n} qualifying")

print("\n===== TIER-2 IN-WINDOW ORIGINALS =====")
T2 = ["CuriousRefuge","paultrillo","CorridorDigital","JeffSynthesized","ai_filmmaker","visiblemaker",
      "Magiermogul","JiamingSuen","moonvalley","Chandan_Perla"]
for h in T2:
    tw = raw.get(h, [])
    if not tw: print(f"{h:16s} NOT IN RAWSET"); continue
    orig = [t for t in tw if t.get("retweeted_tweet") is None and not str(t.get("text","")).startswith("RT @")]
    inw = [t for t in orig if dt(t.get("createdAt","")) and dt(t.get("createdAt","")) >= cutoff]
    nq = sum(1 for t in q if t["handle"]==h)
    print(f"{h:16s} fetched={len(tw):2d} originals={len(orig):2d} in-window={len(inw):2d} qualifying={nq}")
    for t in inw[:3]:
        print(f"     {t.get('likeCount')}L/{t.get('viewCount')}V {t.get('createdAt')} :: {' '.join(str(t.get('text'))[:110].split())!r}")

print("\n===== LABS =====")
for h in ["OpenAI","AnthropicAI"]:
    for t in sorted(raw.get(h,[]), key=lambda x:-(x.get("viewCount") or 0))[:4]:
        if dt(t.get("createdAt","")) and dt(t.get("createdAt",""))>=cutoff:
            print(f"@{h} {t.get('likeCount')}L/{t.get('viewCount')}V {t.get('createdAt')} :: {' '.join(str(t.get('text'))[:130].split())}")

print("\n===== FILM BUCKET AI-TERM MATCHES (manual audit) =====")
AI_TERMS = re.compile(r"ai\b|artificial intelligence|generative|midjourney|stable diffusion|sora|runway|veo|vfx|machine learning|llm|prompt", re.I)
for h in ["DiscussingFilm","nofilmschool"]:
    tw = [t for t in raw.get(h,[]) if dt(t.get("createdAt","")) and dt(t.get("createdAt",""))>=cutoff]
    hits = [(t, AI_TERMS.findall(str(t.get("text","")))) for t in tw]
    hits = [(t,m) for t,m in hits if m]
    print(f"@{h}: {len(tw)} in-window, {len(hits)} AI-term hits")
    for t,m in hits[:5]:
        print(f"   {m} :: {' '.join(str(t.get('text'))[:170].split())!r}")
