#!/usr/bin/env python3
"""Offer/arbitrage grep 2026-10-27 + tier-2 dormancy detail + offer-bearing post text."""
import json, re
from datetime import datetime, timezone, timedelta

DATE = "2026-10-27"
RAW = "/home/kiro/trend-engine/trends/x/raw"
d = json.load(open(f"{RAW}/scan_results_{DATE}_FULL.json"))
raws = d["raw"]

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

now = datetime.now(timezone.utc)
cutoff = now.replace(hour=0,minute=0,second=0,microsecond=0)-timedelta(days=3)

# all in-window originals
inw = []
for h, tw in raws.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
        inw.append((h, dt, t))
print(f"in-window originals across all handles: {len(inw)}")

PATTERNS = {
 "flova_80_off": r"80% ?off|flova.*off|off.*flova",
 "seedance_price": r"\$0\.0\d+|per second|/sec",
 "capcut_bf": r"capcut.*(black friday|60%|40%)|black friday",
 "dreamina_029": r"dreamina|0\.29|\$0\.29",
 "topview": r"topview|t1|cinematic suite",
 "kling_runway_20": r"20% ?off.*kling|kling 4.*20%|runway dev",
 "higgsfield_playable": r"playable",
 "higgsfield_factory": r"content factory|genjutsu|ads studio|ad multiplier|wan 3\.0",
 "topaz": r"topaz",
 "davinci": r"davinci|resolve studio",
 "nebius": r"nebius",
 "magnific": r"magnific",
 "pika_credits": r"pika.*(credit|free)",
 "runway_unlimited": r"unlimited",
 "app_studio": r"app studio",
 "free_prompt": r"free prompt|prompt free|prompts for free",
 "open_source": r"open.?source",
 "discount_generic": r"\d{2}% ?off|coupon|promo code|free credits|free trial",
 "lora_style": r"\blora\b",
 "character_sheet": r"character sheet",
 "video_character_sheet": r"video character sheet",
 "reference_images": r"reference image|ref image|references",
 "native_4k": r"native 4k|4k instead of upscal|10-bit|hdr",
 "audio_in_video": r"with audio|stereo audio|lip ?sync",
 "gpt61": r"gpt-?6\.1|terra",
 "claude_opus_55": r"opus 5\.5",
 "s1_ipo": r"s-1|ipo",
 "nemotron": r"nemotron",
}
print("\n===== OFFER / TECH GREP =====")
for name, pat in PATTERNS.items():
    rx = re.compile(pat, re.I)
    hits = [(h, dt, t) for h, dt, t in inw if rx.search(t.get("text") or "")]
    print(f"\n[{name}] {len(hits)} hits")
    for h, dt, t in sorted(hits, key=lambda z: -(z[2].get('likeCount') or 0))[:5]:
        print(f"   @{h} {dt.strftime('%m-%d %H:%M')} {t.get('likeCount',0)}L/{t.get('viewCount',0)}V :: {(t.get('text') or '').replace(chr(10),' ')[:230]}")

# ---------- full text of key posts ----------
print("\n\n===== FULL TEXT: key posts =====")
KEY_IDS = ["2114673394054795679",  # Flova 1.5
           "2114769835859271760",  # Higgsfield Playable
           "2114709051598880801",  # higgsfield_ai claude commercial
          ]
for h, tw in raws.items():
    for t in tw:
        if str(t.get("id")) in KEY_IDS:
            print(f"\n--- @{h} {t.get('createdAt')} {t.get('likeCount')}L/{t.get('viewCount')}V")
            print((t.get("text") or "")[:1200])
            print(f"URL https://x.com/{h}/status/{t.get('id')}")

# runway app studio thread
print("\n\n===== @runwayml App Studio thread (all in-window originals) =====")
for t in sorted([t for t in raws.get("runwayml",[]) if (pd(t.get('createdAt','')) or datetime.min.replace(tzinfo=timezone.utc))>=cutoff and not t.get('retweeted_tweet')], key=lambda t: pd(t['createdAt'])):
    print(f"{pd(t['createdAt']).strftime('%m-%d %H:%M')} {t.get('likeCount',0)}L/{t.get('viewCount',0)}V :: {(t.get('text') or '').replace(chr(10),' ')[:300]}")

# ---------- tier-2 dormancy ----------
print("\n\n===== TIER-2 ORIGINALS-ONLY DORMANCY =====")
TIER2 = ["CuriousRefuge","paultrillo","JeffSynthesized","ai_filmmaker","Magiermogul","JiamingSuen","Chandan_Perla"]
for h in TIER2:
    tw = raws.get(h, [])
    orig = [t for t in tw if not t.get("retweeted_tweet") and not (t.get("text") or "").startswith("RT @")]
    inwo = [t for t in orig if (pd(t.get("createdAt","")) or datetime.min.replace(tzinfo=timezone.utc))>=cutoff]
    dts = [pd(t.get("createdAt","")) for t in orig]; dts=[x for x in dts if x]
    new = max(dts) if dts else None
    age = (now-new).total_seconds()/3600 if new else -1
    best = max([t.get("likeCount") or 0 for t in inwo], default=0)
    print(f"@{h}: fetched {len(tw)} originals {len(orig)} in-window {len(inwo)} newest {new} ({age:.1f}h) best_likes_in_window {best}")
