#!/usr/bin/env python3
"""Offer grep + key handle chronologies for 2026-10-25."""
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-25_FULL.json"))
IRRELEVANT = {"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"}
now = datetime.now(timezone.utc)
cutoff = now.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=3)

def pd(s):
    try: return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")
    except Exception: return None

# remaining new CORE posts beyond first 30
P = json.load(open(f"{RAW}/scan_results_2026-10-24_FULL.json"))
prev_ids = {q["url"].rstrip("/").split("/")[-1] for q in P["qualifying"]}
new = [q for q in D["qualifying"] if q["url"].rstrip("/").split("/")[-1] not in prev_ids]
new.sort(key=lambda x: x["score"], reverse=True)
corenew = [q for q in new if q["handle"] not in IRRELEVANT and q["handle"] not in FILM]
print(f"=== NEW CORE/FILMMAKING POSTS SINCE YESTERDAY ({len(corenew)}) ===")
for q in corenew:
    print(f"@{q['handle']} {q['likes']}L/{q['views']}V {q['date']} :: {q['text'][:220]}")
    print(f"   {q['url']}")

PATTERNS = [
    ("flova", r"flova"), ("seedance_price", r"\$0\.0\d+ ?/ ?sec|\$0\.022|\$0\.044"),
    ("free", r"\bfree\b"), ("discount", r"\d{2}% ?off|half price|half off|save \d+%"),
    ("dreamina", r"dreamina"), ("capcut", r"capcut"), ("topaz", r"topaz"),
    ("davinci", r"davinci|resolve"), ("qoder", r"qoder"), ("nebius", r"nebius"),
    ("higgsfield_offer", r"higgsfield"), ("kling4", r"kling 4"), ("topview", r"topview|\bT1\b"),
    ("runway_offer", r"unlimited|25% off"), ("credits", r"credits"), ("api_price", r"/sec|per second"),
    ("pika", r"pika"), ("content_factory", r"content factory"), ("genjutsu", r"genjutsu"),
    ("ideogram", r"ideogram"), ("nano_banana", r"nano banana"), ("flux3", r"flux 3"),
    ("price", r"\$\d"), ("trial", r"trial"), ("launch", r"\blaunch|now live|available now|introducing"),
]
print("\n=== OFFER GREP (all in-window ORIGINAL posts, all buckets) ===")
texts = []
for h, tw in D["raw"].items():
    for t in tw:
        if t.get("retweeted_tweet") or (t.get("text") or "").startswith("RT @"): continue
        dt = pd(t.get("createdAt",""))
        if not dt or dt < cutoff: continue
        texts.append((h, dt, t.get("text") or "", t.get("likeCount") or 0, t.get("viewCount") or 0, t.get("id")))
print(f"  pool: {len(texts)} in-window originals")
for name, pat in PATTERNS:
    hits = [x for x in texts if re.search(pat, x[2], re.I)]
    if not hits: 
        print(f"  [{name}] 0 hits")
        continue
    print(f"  [{name}] {len(hits)} hits")
    for h, dt, tx, l, v, tid in sorted(hits, key=lambda x: -x[3])[:4]:
        print(f"     @{h} {dt:%m-%d %H:%M} {l}L/{v}V :: {tx[:170].replace(chr(10),' ')}")
        print(f"       https://x.com/{h}/status/{tid}")

print("\n=== KEY HANDLE CHRONOLOGY (in-window originals) ===")
for h in ["higgsfield","higgsfield_ai","azed_ai","Flovaai","pika_labs","CharaspowerAI","EHuanglu","Kling_ai","runwayml","venturetwins","EinsiaAI","c_valenzuelab"]:
    tw = D["raw"].get(h, [])
    rows = []
    for t in tw:
        if t.get("retweeted_tweet") or (t.get("text") or "").startswith("RT @"): continue
        dt = pd(t.get("createdAt",""))
        if not dt or dt < cutoff: continue
        rows.append((dt, t))
    rows.sort(key=lambda r: r[0])
    print(f"\n  -- @{h}: {len(rows)} in-window originals of {len(tw)} fetched --")
    for dt, t in rows:
        print(f"    {dt:%m-%d %H:%M} {t.get('likeCount') or 0}L/{t.get('retweetCount') or 0}RT/{t.get('viewCount') or 0}V :: {(t.get('text') or '')[:160].replace(chr(10),' ')}")
