#!/usr/bin/env python3
"""X monitor offers/verify audit 2026-10-29."""
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-29_FULL.json"))
q = D["qualifying"]; raw = D["raw"]
cutoff = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=3)

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

# in-window originals across all handles
inwin = []
for h, tw in raw.items():
    for t in tw:
        if t.get("retweeted_tweet") or (t.get("text") or "").startswith("RT @"): continue
        try:
            dt = parse_d(t["createdAt"])
        except Exception:
            continue
        if dt < cutoff: continue
        inwin.append((h, t, dt))
print(f"IN-WINDOW ORIGINALS {len(inwin)}")

PATTERNS = {
 "flova": r"flova",
 "seedance": r"seedance",
 "kling": r"kling",
 "capcut": r"capcut",
 "dreamina": r"dreamina",
 "topview": r"topview",
 "higgsfield": r"higgsfield",
 "genjutsu": r"genjutsu",
 "content factory": r"content.?factory",
 "cashback": r"cashback|cash back",
 "ads studio": r"ads studio|ad multiplier",
 "topaz": r"topaz",
 "davinci": r"davinci|resolve studio",
 "nebius": r"nebius",
 "magnific": r"magnific",
 "pika": r"pika",
 "runway": r"runway",
 "unlimited": r"unlimited",
 "free credits": r"free credits|free plan|free tier",
 "discount pct": r"\b\d{1,2}% off\b|\bhalf price\b|\bbogo\b|buy 1 get|buy one get",
 "price per sec": r"\$\s?0\.\d+\s*/\s*sec|per second|/\s?sec",
 "trial": r"\btrial\b",
 "promo code": r"promo code|discount code|coupon|refCode|utm_campaign",
 "black friday": r"black friday",
 "veo": r"\bveo\b",
 "sora": r"\bsora\b",
 "wan ": r"\bwan\s?3|\bwan\b",
 "gpt-6": r"gpt-6",
 "gemini": r"gemini",
 "free prompt": r"free prompt|open sourced|open.source|prompt.*public",
}
print("\n=== OFFER GREP (in-window originals) ===")
for name, pat in PATTERNS.items():
    rx = re.compile(pat, re.I)
    hits = [(h,t,dt) for h,t,dt in inwin if rx.search(t.get("text") or "")]
    if not hits: 
        print(f"[{name}] 0 hits")
        continue
    print(f"[{name}] {len(hits)} hits")
    for h,t,dt in hits[:6]:
        print(f"   @{h} {dt.strftime('%m-%d %H:%M')} {t.get('likeCount')}L/{t.get('viewCount')}V :: {(t.get('text') or '').replace(chr(10),' ')[:230]}")

# ---- film bucket audit ----
STRONG = re.compile(r"\b(seedance|kling|runway|sora|veo|higgsfield|midjourney|nano.?banana|stable diffusion|"
                    r"generative video|text.to.video|image.to.video|ai filmmaker|ai filmmaking|ai video|"
                    r"artificial intelligence|gpt|claude|gemini|llm|diffusion model|deepfake)\b", re.I)
URLRX = re.compile(r"https?://\S+|t\.co/\S+")
print("\n=== FILM BUCKET AUDIT ===")
for h in ["DiscussingFilm","nofilmschool","CINEMA505"]:
    tw = [t for t in raw.get(h,[]) if not t.get("retweeted_tweet") and not (t.get("text") or "").startswith("RT @")]
    inw = [(t, parse_d(t["createdAt"])) for t in tw if parse_d(t["createdAt"]) >= cutoff]
    strong = [(t,d) for t,d in inw if STRONG.search(URLRX.sub("", t.get("text") or ""))]
    bareai = [(t,d) for t,d in inw if re.search(r"\bai\b", URLRX.sub("", t.get("text") or ""), re.I)]
    print(f"@{h}: in-window originals {len(inw)} STRONG_TERMS {len(strong)} bare-ai-after-URLstrip {len(bareai)}")
    for t,d in strong + [x for x in bareai if x not in strong]:
        print(f"   {d.strftime('%m-%d %H:%M')} {t.get('likeCount')}L/{t.get('viewCount')}V :: {(t.get('text') or '').replace(chr(10),' ')[:300]}")

# ---- key account chronologies ----
print("\n=== KEY ACCOUNT IN-WINDOW ORIGINALS ===")
for h in ["Flovaai","higgsfield","higgsfield_ai","runwayml","Kling_ai","c_valenzuelab","GoogleAI",
          "CharaspowerAI","AIWarper","EHuanglu","ItsMaryamAi","Soaima_Ai","ElsaSofia__AI","AI__TSUBAKI","azed_ai"]:
    tw = raw.get(h, [])
    rows = []
    for t in tw:
        isrt = bool(t.get("retweeted_tweet")) or (t.get("text") or "").startswith("RT @")
        try: dt = parse_d(t["createdAt"])
        except Exception: continue
        rows.append((dt, isrt, t))
    rows.sort(key=lambda r: r[0], reverse=True)
    inw = [r for r in rows if r[0] >= cutoff and not r[1]]
    print(f"\n-- @{h} ({len(inw)} in-window originals of {len(rows)} fetched) --")
    for dt, isrt, t in inw[:14]:
        print(f"  {dt.strftime('%m-%d %H:%M')} {t.get('likeCount')}L/{t.get('retweetCount')}RT/{t.get('viewCount')}V "
              f"reply={bool(t.get('isReply'))} :: {(t.get('text') or '').replace(chr(10),' ')[:260]}")
