#!/usr/bin/env python3
"""Offer grep + cutoffs + tier-2 + film audit, 2026-10-26."""
import json, re
from datetime import datetime, timezone
D = json.load(open('/home/kiro/trend-engine/trends/x/raw/scan_results_2026-10-26_FULL.json'))
raw, qual = D['raw'], D['qualifying']
CUTOFF = datetime(2026,10,23,tzinfo=timezone.utc)
F = "%a %b %d %H:%M:%S %z %Y"
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"}

core=[q for q in qual if q['handle'] not in IRR and q['handle'] not in FILM]
core.sort(key=lambda q:-q['score'])
print(f"CORE n={len(core)}  top10 cutoff={core[9]['score']:.0f}  rank11={core[10]['score']:.0f} (@{core[10]['handle']})")
print(f"FILM n={len([q for q in qual if q['handle'] in FILM])}  IRR n={len([q for q in qual if q['handle'] in IRR])}")

print("\n=== CORE RANKS 26-40 (below the fold, for signal) ===")
for i,q in enumerate(core[25:40],26):
    print(f"{i}. @{q['handle']} {q['score']:.0f} {q['date']} | {q['text'][:110].replace(chr(10),' ')}")

STRONG = re.compile(r"(seedance|kling|veo|runway|higgsfield|midjourney|flux|sora|wan ?\d|hailuo|minimax|"
 r"nano ?banana|ideogram|topview|pika|dreamina|capcut|davinci|topaz|magnific|comfyui|stable diffusion|"
 r"generative|text-to-video|text to video|image-to-video|diffusion|ai video|ai film|ai ad|prompt)", re.I)
def clean(t):
    return re.sub(r"https?://\S+","",t or "")

print("\n=== FILM TIER: AI/STRONG matches with context ===")
n=0
for q in qual:
    if q['handle'] not in FILM: continue
    t=clean(q['text'])
    m=STRONG.findall(t)
    if m:
        n+=1; print(f"@{q['handle']} {q['date']} match={set(m)} | {t[:160]}")
print(f"film strong-term matches: {n}")

print("\n=== TIER-2 detail ===")
T2=["CuriousRefuge","paultrillo","CorridorDigital","JeffSynthesized","ai_filmmaker","visiblemaker","Magiermogul","JiamingSuen","Chandan_Perla"]
for h in T2:
    rs=raw.get(h,[]) or []
    o=[]
    for r in rs:
        if r.get('retweeted_tweet'): continue
        try: d=datetime.strptime(r['createdAt'],F)
        except Exception: continue
        if d>=CUTOFF: o.append(r)
    cnt=sum(1 for q in qual if q['handle']==h)
    print(f"@{h}: qualifying={cnt} inwindow_originals={len(o)}")

print("\n=== OFFER GREP over in-window raw (all handles) ===")
PATTERNS = {
 "flova":r"flova", "seedance_price":r"\$0\.0\d+ ?/ ?s|\$0\.\d+ per sec|per second",
 "capcut_bf":r"capcut.*(60%|40%|black friday)|black friday.*capcut",
 "dreamina029":r"dreamina.*0\.29|0\.29.*dreamina", "dreamina_other":r"dreamina",
 "topview":r"topview|t1\b.*\$0\.22|\$0\.22", "kling4":r"kling 4|kling4", "wavespeed":r"wavespeed",
 "higgsfield":r"higgsfield", "genjutsu":r"genjutsu", "content_factory":r"content factory",
 "pika":r"pika", "runway_unlimited":r"unlimited kling|3 days of unlimited",
 "topaz":r"topaz", "davinci":r"davinci|resolve studio", "magnific":r"magnific",
 "nebius":r"nebius", "free_credits":r"free credits|credits free|250 free|free trial|free plan",
 "percent_off":r"\d{2}% off", "discount":r"discount|promo code|coupon",
 "nemotron":r"nemotron", "gemini":r"gemini", "grok":r"grok", "claude":r"claude",
 "official_offer":r"available now|now live|launch|out now|sign up",
}
hits={k:[] for k in PATTERNS}
for h,rs in raw.items():
    for r in rs:
        try: d=datetime.strptime(r['createdAt'],F)
        except Exception: continue
        if d<CUTOFF: continue
        t=r.get('text') or ''
        for k,p in PATTERNS.items():
            if re.search(p,t,re.I): hits[k].append((d,h,r.get('likeCount') or 0,r.get('viewCount') or 0,t))
for k,v in hits.items():
    print(f"\n[{k}] {len(v)} hits")
    for d,h,l,vs,t in sorted(v, reverse=True)[:6]:
        print(f"  {d.strftime('%m-%d %H:%M')} @{h} {l}L/{vs}V | {t[:190].replace(chr(10),' ')}")
