#!/usr/bin/env python3
"""2026-10-23 pass 2: offer grep, film AI audit, labs, new-since-last-run timeline, tier-2."""
import json, re
from datetime import datetime, timezone

D = "/home/kiro/trend-engine/trends/x/raw/scan_results_2026-10-23_FULL.json"
d = json.load(open(D))
raw, qual = d["raw"], d["qualifying"]
cutoff = datetime(2026, 10, 20, 0, 0, tzinfo=timezone.utc)
last_run = datetime(2026, 10, 22, 6, 0, tzinfo=timezone.utc)

def pdate(s):
    return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")

# all in-window raw texts
win = []
for h, arr in raw.items():
    for t in arr:
        try:
            dt = pdate(t["createdAt"])
        except Exception:
            continue
        if dt >= cutoff:
            win.append((h, dt, t))
print("in-window raw posts:", len(win))

OFFERS = {
 "Flova x Seedance": r"flova.{0,40}seedance|seedance.{0,40}flova|0\.0(22|44)/sec|80%",
 "CapCut BF": r"capcut.{0,80}(black friday|60%|40%)|black friday.{0,60}capcut",
 "DaVinci": r"davinci|resolve studio",
 "Dreamina price": r"dreamina.{0,80}\$\d|\\\$\d[\.\d]*.{0,40}dreamina|\$0\.29|1\.50/month",
 "Higgsfield Genjutsu": r"genjutsu",
 "Higgsfield Wan3": r"wan ?3\.0 ?(prime|unlimited)",
 "Higgsfield cashback": r"cashback|\$18M",
 "Higgsfield Academy": r"academy",
 "Higgsfield Content Factory": r"content factory",
 "Higgsfield Ads Studio": r"ads studio|ad multiplier",
 "Topaz deal": r"topaz.{0,60}(50%|off|sale)|50% off.{0,40}topaz",
 "Runway promo": r"unlimited kling|25% off",
 "Nebius": r"nebius",
 "Qoder": r"qoder",
 "Magnific": r"magnific",
 "Kling credits/deal": r"kling.{0,60}(off|discount|free|unlimited|credits)",
 "Topview T1 price": r"topview|\bt1\b.{0,40}(\\\$|sec)",
 "Viggle": r"viggle|jst-2",
 "Claude Duet": r"claude duet|duet",
 "filmera": r"filmera",
 "Prize/challenge": r"challenge|prize|grand prize|\$[0-9,]+ in prizes",
 "Free credits/gens": r"free (generations|credits|trial|access)|days of unlimited|no credits required",
}
print("\n=== OFFER GREP (in-window) ===")
for name, pat in OFFERS.items():
    hits = [(h, dt, t) for (h, dt, t) in win if re.search(pat, t.get("text") or "", re.I)]
    print("\n[%s] %d hits" % (name, len(hits)))
    for h, dt, t in sorted(hits, key=lambda x: -x[1].timestamp())[:5]:
        print("  %-14s %s %6dL/%8dV %s" % (h, dt.strftime("%m-%d %H:%M"), t.get("likeCount", 0),
                                           t.get("viewCount", 0), (t.get("text") or "").replace("\n", " ")[:190]))

# film AI-term audit
FILM = {"DiscussingFilm", "nofilmschool", "CINEMA505"}
AI_TERMS = re.compile(r"(?<![a-z])(ai|a\.i\.|artificial intelligence|vfx|generative|(ai|3d|generated) ?animation|prompt|machine learning|sora|midjourney|runway|seedance|kling)(?![a-z])", re.I)
print("\n=== FILM-INDUSTRY AI-TERM AUDIT ===")
for h in FILM:
    posts = [t for t in raw.get(h, []) if pdate(t["createdAt"]) >= cutoff]
    m = [t for t in posts if AI_TERMS.search(t.get("text") or "")]
    print("%-16s in-window=%2d ai-matches=%d" % (h, len(posts), len(m)))
    for t in m:
        print("   %s %dL/%dV %s" % (pdate(t["createdAt"]).strftime("%m-%d %H:%M"), t.get("likeCount", 0),
                                    t.get("viewCount", 0), (t.get("text") or "")[:170].replace("\n", " ")))

# labs
LABS = {"OpenAI", "AnthropicAI"}
print("\n=== AI LABS ===")
lq = sorted([q for q in qual if q["handle"] in LABS], key=lambda q: -q["score"])
for q in lq:
    print("%-12s %s %6dL %9dV %s" % (q["handle"], q["date"], q["likes"], q["views"], q["text"][:120].replace("\n", " ")))

# new since last run
print("\n=== NEW POSTS SINCE LAST RUN (>= 10-22 06:00), qualifying only ===")
def qdt(q):
    return datetime.strptime(q["date"].replace(" UTC", ""), "%Y-%m-%d %H:%M").replace(tzinfo=timezone.utc)
new = sorted([q for q in qual if qdt(q) >= last_run], key=lambda q: -qdt(q).timestamp())
for q in new:
    print("%-16s %s %6dL/%9dV %s" % (q["handle"], q["date"], q["likes"], q["views"], q["text"][:150].replace("\n", " ")))
print("new qualifying count:", len(new))
