#!/usr/bin/env python3
"""Verification pass 2026-11-11: key posts full text, per-handle chronology, model/price greps."""
import re, json
from datetime import datetime, timezone

RAW = "/home/kiro/trend-engine/trends/x/raw"
cur = json.load(open(f"{RAW}/scan_results_2026-11-11_FULL.json"))
prev = json.load(open(f"{RAW}/scan_results_2026-11-10_FULL.json"))
now = datetime.now(timezone.utc)
CUT = datetime(2026, 11, 8, tzinfo=timezone.utc)
def pdate(s):
    try: return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")
    except Exception: return None

def origs(h):
    out = []
    for t in cur["raw"].get(h) or []:
        if t.get("retweeted_tweet") or t.get("type") == "retweet": continue
        if (t.get("text") or "").startswith("RT @"): continue
        d = pdate(t.get("createdAt", ""))
        if not d: continue
        out.append((d, t))
    return sorted(out, key=lambda x: x[0])

# ---------- per-handle in-window chronology for the craft bench ----------
for h in ["EHuanglu", "c_valenzuelab", "CharaspowerAI", "AI__TSUBAKI", "AIWarper",
          "azed_ai", "Flovaai", "Kling_ai", "openart_ai", "pika_labs", "runwayml",
          "higgsfield_ai", "perplexity_ai", "ElsaSofia__AI"]:
    print(f"\n===== @{h} (originals) =====")
    for d, t in origs(h):
        if d < CUT: continue
        rep = "R" if (t.get("isReply") or t.get("inReplyToId")) else " "
        med = ((t.get("media") or [{}])[0].get("type") if t.get("media") else "-")
        print(f"  {d.strftime('%m-%d %H:%M')}{rep} {t.get('likeCount') or 0:>5}L/{(t.get('viewCount') or 0):>7}V "
              f"[{str(med):6s}] {re.sub(r'\\s+',' ',(t.get('text') or ''))[:300]}")
        if t.get("quoted_tweet"):
            print(f"      QT: {re.sub(r'\\s+',' ',(t['quoted_tweet'].get('text') or ''))[:200]}")

# ---------- global greps ----------
print("\n\n===== GLOBAL MODEL / PRICE GREPS (in-window originals) =====")
allorig = []
for h in cur["raw"]:
    for d, t in origs(h):
        if d >= CUT:
            allorig.append((h, d, t))
print(f"corpus {len(allorig)}")
for pat in [r"\bveo\b", r"\bsora\b", r"\bseedance\b", r"\bkling\b", r"\bhailuo\b",
            r"per (second|sec)", r"/sec\b", r"\bpricing\b", r"\bcost\b", r"\bcredits?\b",
            r"\bopen[\s-]?weights?\b", r"\bminimax h3\b", r"\bseedream 5\.5\b",
            r"\bgemini 4\b", r"\bfable 5\.2\b", r"\bnano banana\b"]:
    hits = [(h, d, t) for h, d, t in allorig if re.search(pat, (t.get("text") or ""), re.I)]
    print(f"\n-- {pat}: {len(hits)} --")
    for h, d, t in sorted(hits, key=lambda x: -(x[2].get("likeCount") or 0))[:6]:
        print(f"   @{h:15s} {d.strftime('%m-%d %H:%M')} {t.get('likeCount') or 0:>5}L "
              f"| {re.sub(r'\\s+',' ',(t.get('text') or ''))[:210]}")

# ---------- delta recompute for headline ----------
print("\n\n===== HEADLINE DELTAS (clean) =====")
pm = {t["url"].rsplit("/", 1)[-1]: t for t in prev["qualifying"]}
for tid in ["2119846806066733206", "2119884452054937656", "2119867707546071125",
            "2119947980400976267", "2119975721909301684", "2119918834841010320",
            "2119579582592630873", "2119993792875180244"]:
    c = next((t for t in cur["qualifying"] if t["url"].endswith(tid)), None)
    p = pm.get(tid)
    if c and p:
        print(f"  @{c['handle']:14s} {tid} likes {p['likes']}->{c['likes']} ({c['likes']-p['likes']:+}) "
              f"views {p['views']}->{c['views']} ({c['views']-p['views']:+}) rate {c['likes']/c['views']*100:.3f}%")

# ---------- watchlist ----------
md = open("/home/kiro/trend-engine/trends/x/raw/rising-accounts.md").read()
hs = {m.lower() for m in re.findall(r"@(\w+)", md)}
print(f"\nunique @handles in md: {len(hs)} | scanned {len(cur['handles'])}")
sc = {h.lower() for h in cur["handles"]}
print("in md not scanned:", sorted(hs - sc))
