#!/usr/bin/env python3
"""Board-wide keyword sweep 2026-11-07 + Miracle detail + unclassified checks."""
import json, re
from datetime import datetime, timedelta

DATE = "2026-11-07"
RAW = "/home/kiro/trend-engine/trends/x/raw"
FMT = "%a %b %d %H:%M:%S %z %Y"
D = json.load(open(f"{RAW}/scan_results_{DATE}_FULL.json"))
res = D["raw"]
cutoff = datetime.strptime(f"{DATE} 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z") - timedelta(days=3)

TERMS = ["Miracle", "miracle", "Sora", "Veo ", "Seedance 3", "Seedance 4", "Kling 5",
         "ecom", "product ad", "UGC", "Meta ad", "ROAS", "$0.0", "per second",
         "open weight", "open-source", "Black Friday", "Adobe MAX", "Chroma",
         "world model", "Miracle", "post-production", "layer"]

hits = {}
rows = []
for h, tw in res.items():
    for t in (tw or []):
        if t.get("retweeted_tweet"): continue
        d = datetime.strptime(t["createdAt"], FMT)
        if d < cutoff: continue
        rows.append((h, d, t))
print(f"in-window originals: {len(rows)}")

for term in TERMS:
    hs = [(h, d, t) for h, d, t in rows if term.lower() in (t.get("text") or "").lower()]
    if not hs: 
        print(f"\n[{term}] 0 hits"); continue
    print(f"\n[{term}] {len(hs)} hits")
    for h, d, t in sorted(hs, key=lambda x: -x[2].get("viewCount",0))[:8]:
        print(f"  @{h:18s} {d.strftime('%m-%d %H:%M')} {t.get('likeCount',0)}L/{t.get('viewCount',0)}V")
        print(f"    {(t.get('text') or '')[:260].replace(chr(10),' | ')}")

print("\n\n=== MIRACLE FULL COVERAGE ===")
for h, d, t in rows:
    tx = (t.get("text") or "")
    if "miracle" in tx.lower() or "pixel-level" in tx.lower() or "alexmashrabov" in tx.lower():
        print(f"@{h} {d.strftime('%m-%d %H:%M')} {t.get('likeCount',0)}L/{t.get('retweetCount',0)}RT/"
              f"{t.get('viewCount',0)}V RT={'Y' if t.get('retweeted_tweet') else 'N'}")
        print(f"  {tx[:900]}")
        rt = t.get("retweeted_tweet")
        if rt:
            print(f"  >> RT OF @{(rt.get('author') or {}).get('userName')}: {(rt.get('text') or '')[:900]}")

print("\n=== alexmashrabov originals anywhere ===")
for h, tw in res.items():
    for t in (tw or []):
        au = ""
        q = t.get("quoted_tweet") or t.get("retweeted_tweet") or {}
        au = (q.get("author") or {}).get("userName") or ""
        if au == "alexmashrabov":
            print(f"via @{h}: quote/RT -> {(q.get('text') or '')[:800]}")

print("\n=== FILM BUCKET AI TERMS ===")
STRONG = r"\bAI\b|artificial intelligence|generative|diffusion|model|prompt"
for h in ["DiscussingFilm", "nofilmschool"]:
    tw = res.get(h) or []
    n = 0
    for t in tw:
        d = datetime.strptime(t["createdAt"], FMT)
        if d < cutoff or t.get("retweeted_tweet"): continue
        n += 1
        tx = re.sub(r"https?://\S+", "", t.get("text") or "")
        if re.search(STRONG, tx):
            print(f"  @{h} {d.strftime('%m-%d %H:%M')} {t.get('likeCount',0)}L :: {tx[:200]}")
    print(f"  -> @{h} {n} in-window originals")

print("\n=== CHARASPOWERAI IN-WINDOW QUALIFYING COUNT ===")
c = 0
for t in (res.get("CharaspowerAI") or []):
    d = datetime.strptime(t["createdAt"], FMT)
    if d < cutoff: continue
    if t.get("likeCount",0) >= 50 or t.get("retweetCount",0) >= 10 or t.get("viewCount",0) >= 1000:
        c += 1
print(" qualifying:", c)

print("\n=== WUXIAROCKS / AI__TSUBAKI / BRONZE ===")
for h in ["WuxiaRocks", "AI__TSUBAKI", "ItsMaryamAi", "different_ai"]:
    tw = res.get(h) or []
    iw = [t for t in tw if datetime.strptime(t["createdAt"], FMT) >= cutoff and not t.get("retweeted_tweet")]
    if not iw: 
        print(f"  @{h}: 0 in-window originals")
        continue
    best = max(iw, key=lambda t: t.get("likeCount",0))
    print(f"  @{h}: {len(iw)} in-window originals, best {best.get('likeCount',0)}L/{best.get('viewCount',0)}V")
    print(f"    newest {(datetime.now() - datetime.strptime(max(t['createdAt'] for t in tw), FMT)).total_seconds()/3600:.1f}h ago")
