#!/usr/bin/env python3
"""X monitor offers audit 2026-10-30: offer grep over in-window originals + key post full text."""
import json, re
from datetime import datetime, timezone, timedelta
from collections import Counter

RAW = "/home/kiro/trend-engine/trends/x/raw"
D = json.load(open(f"{RAW}/scan_results_2026-10-30_FULL.json"))
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")

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:
            d = parse_d(t.get("createdAt",""))
        except Exception:
            continue
        if d >= cutoff:
            inwin.append((h, t, d))
print(f"IN-WINDOW ORIGINALS {len(inwin)}")

PATTERNS = {
 "flova": r"flova",
 "seedance_price": r"\$0\.0\d+|0\.025|\$0\.\d+/sec|per second",
 "bogo": r"buy 1 year|buy one year|get 1 free|2 years of pro|bogo",
 "capcut_bf": r"capcut",
 "higgsfield_unlimited": r"unlimited seedance|zero credit|zero credit cost",
 "pika_h3": r"pika h3|h3 flex|designarena",
 "topview": r"topview",
 "dreamina": r"dreamina",
 "topaz": r"topaz",
 "davinci": r"davinci|resolve studio",
 "kling4": r"kling 4|kling4",
 "veo": r"\bveo\b",
 "magnific": r"magnific",
 "nebius": r"nebius",
 "runway_ads": r"runway ads|runway\.com/product",
 "app_studio": r"app studio",
 "playable": r"playable",
 "open_source_prompts": r"open source|open-source|all prompts",
 "genjutsu": r"genjutsu",
 "content_factory": r"content factory",
 "ads_studio": r"ads studio|ad multiplier",
 "pika_api": r"pika api|pika api club|pika\.art",
 "sunra": r"sunra",
 "free_credits": r"free credits|free credit|credits free",
 "discount": r"\d{2}% off|discount|sale|deal",
 "nov30": r"nov 30|november 30",
 "gemini4": r"gemini 4|gemini4",
 "genie4": r"genie 4|genie4",
 "nemotron": r"nemotron",
 "patrick_stewart": r"patrick stewart",
}
print("\n=== OFFER GREP ===")
for name, pat in PATTERNS.items():
    rx = re.compile(pat, re.I)
    hits = [(h, t) for h, t, d in inwin if rx.search((t.get("text") or ""))]
    if not hits:
        print(f"{name}: 0")
        continue
    print(f"{name}: {len(hits)}")
    for h, t in hits[:8]:
        print(f"   @{h} {t.get('createdAt')} {t.get('likeCount')}L/{t.get('viewCount')}V | {(t.get('text') or '')[:220]}")

print("\n=== KEY POST FULL TEXT ===")
keys = [
 ("higgsfield", "Unlimited Seedance"),
 ("pika_labs", "Pika H3 Flex"),
 ("Flovaai", "Launch Special"),
 ("higgsfield", "Mobile game ads"),
 ("higgsfield_ai", "Selected"),
]
for h, needle in keys:
    for t in raw.get(h, []):
        if needle.lower() in (t.get("text") or "").lower():
            media = t.get("media") or []
            print(f"\n--- @{h} {t.get('createdAt')} {t.get('likeCount')}L/{t.get('retweetCount')}RT/{t.get('replyCount')}R/{t.get('viewCount')}V "
                  f"media={[m.get('type') for m in media]} rt={bool(t.get('retweeted_tweet'))} quote={bool(t.get('quoted_tweet'))} reply={bool(t.get('isReply'))}")
            print(t.get("text"))
            print(f"https://x.com/{h}/status/{t.get('id')}")

print("\n=== HIGGSFIELD / PIKA / RUNWAY CHRONOLOGY (in-window originals) ===")
for h in ["higgsfield","higgsfield_ai","pika_labs","runwayml","c_valenzuelab","Kling_ai","Flovaai"]:
    rows = sorted([(t, d) for hh, t, d in inwin if hh == h], key=lambda r: r[1])
    print(f"\n-- @{h} ({len(rows)}) --")
    for t, d in rows:
        print(f"  {d.strftime('%m-%d %H:%M')} {t.get('likeCount')}L/{t.get('viewCount')}V | {(t.get('text') or '')[:160]}")

print("\n=== PROMPT-REPLY HARVEST ===")
for h in ["ItsMaryamAi","Soaima_Ai","ElsaSofia__AI","CharaspowerAI","AI__TSUBAKI"]:
    rows = [(t, d) for hh, t, d in inwin if hh == h]
    reps = [(t, d) for t, d in rows if t.get("isReply")]
    print(f"\n-- @{h}: {len(rows)} in-window originals/replies, {len(reps)} isReply --")
    for t, d in sorted(reps, key=lambda r: r[1])[-4:]:
        print(f"  {d.strftime('%m-%d %H:%M')} {t.get('likeCount')}L | {(t.get('text') or '')[:300]}")
