import json, re, datetime
base="/home/kiro/trend-engine/trends/x/raw/"
D="2026-10-17"
cur=json.load(open(base+f"scan_results_{D}_FULL.json"))
q=cur["qualifying"]; raw=cur["raw"]
now=datetime.datetime.now(datetime.timezone.utc)
cutoff=datetime.datetime(now.year,now.month,now.day,tzinfo=datetime.timezone.utc)-datetime.timedelta(days=3)
def P(s): return datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")
print("cutoff:", cutoff.isoformat())

CORE = set("""runwayml CuriousRefuge venturetwins Kling_ai paultrillo c_valenzuelab karenxcheng higgsfield pika_labs EHuanglu azed_ai JeffSynthesized ai_filmmaker Magiermogul WuxiaRocks JiamingSuen higgsfield_ai Chandan_Perla CharaspowerAI AIWarper nofilmschool Flovaai AI__TSUBAKI""".split())
FILM={"DiscussingFilm","nofilmschool"}; LABS={"OpenAI","AnthropicAI"}

print("\n=== FETCH WINDOW (chronological, top-volume handles) ===")
for h in sorted(raw, key=lambda x: -len(raw[x]))[:16]:
    ts=[P(t["createdAt"]) for t in raw[h] if t.get("createdAt")]
    if ts:
        print(f"{h:18s} n={len(raw[h]):3d} oldest={min(ts).strftime('%Y-%m-%d %H:%M')} newest={max(ts).strftime('%Y-%m-%d %H:%M')} oldestInWin={'YES' if min(ts)>=cutoff else 'no'}")

print("\n=== ZERO-QUALIFYING HANDLES (originals-only, chronological) ===")
def is_orig(t):
    return t.get("retweeted_tweet") is None and not (t.get("text") or "").startswith("RT @")
qual=set(t["handle"] for t in q)
for h in sorted(h for h in raw if h not in qual):
    ts=raw[h]; origs=[t for t in ts if is_orig(t)]
    if not origs:
        print(f"{h:18s} orig=0/{len(ts)} NO ORIGINALS"); continue
    newest=max(P(t["createdAt"]) for t in origs)
    inw=[t for t in origs if P(t["createdAt"])>=cutoff]
    tag="IN-WINDOW" if newest>=cutoff else "out"
    bestL=max((t.get("likeCount",0) for t in inw), default=None)
    bestV=max((t.get("viewCount",0) for t in inw), default=None)
    print(f"{h:18s} orig={len(origs):2d}/{len(ts):2d} newestORIG={newest.strftime('%Y-%m-%d %H:%M')} age={(now-newest).days:4d}d {tag:9s} nInWin={len(inw)} bestL={bestL} bestV={bestV}")

print("\n=== OFFER / PROMO GREP (offer phrases, not bare brand words) ===")
OFFERS = {
 "Flova Seedance 80% off": r"80%\s*(off|on)|save up to 80%",
 "Higgsfield Wan 3.0 unlimited": r"WAN ?3\.?0?\s*UNLIMITED|Wan 3\.0.{0,30}[Uu]nlimited",
 "Higgsfield API discount": r"(50|60)% ?(OFF|off).{0,40}API|API.{0,30}(50|60)% ?(OFF|off)",
 "FLUX 3 Upscaler": r"FLUX ?3 ?Upscaler",
 "Genjutsu API": r"Genjutsu",
 "CapCut Black Friday": r"Black ?Friday",
 "Magnific One unlimited": r"Magnific",
 "Higgsfield cashback": r"cashback|100% instant",
 "Ads Studio / Ad Multiplier": r"Ads Studio|Ad Multiplier",
 "AI Influencer free gens": r"AI ?[Ii]nfluencer",
 "Air unlimited": r"unlimited credits|free until (the )?end of",
 "Dolphin AI referral": r"XX-AYCMR8|Dolphin AI",
 "Dreamina Originals": r"Dreamina Originals|Dreamina ?[Oo]riginals",
 "Higgsfield Academy": r"Higgsfield Academy",
 "Krea 3": r"Krea ?3",
 "Mirelo SFX": r"Mirelo",
 "Pika x ChatGPT": r"Pika X ChatGPT|Pika.{0,10}ChatGPT plugin",
 "free credits/generations": r"free (credits|generations|trial|tier)",
 "discount %": r"\b(50|60|70|80|90)% ?(off|discount)",
}
for name,pat in OFFERS.items():
    hits=[]
    for h,ts in raw.items():
        for t in ts:
            txt=(t.get("text") or "")
            if re.search(pat, txt, re.I):
                hits.append((h, t.get("createdAt","")[:16], t.get("likeCount"), t.get("viewCount"), txt.replace("\n"," ")[:190]))
    print(f"\n-- {name}: {len(hits)} hit(s)")
    for h,d,l,v,txt in sorted(hits, key=lambda x:-(x[3] or 0))[:3]:
        print(f"   @{h} {d} {l}L {v}V :: {txt}")
