#!/usr/bin/env python3
"""Outlier verify (id from URL) + full offer texts + freshest posts, 2026-10-21."""
import json, re
from datetime import datetime, timezone, timedelta

BASE = "/home/kiro/trend-engine/trends/x/raw"
d = json.load(open(f"{BASE}/scan_results_2026-10-21_FULL.json"))
raw, qual = d["raw"], d["qualifying"]
now = datetime.now(timezone.utc)
cutoff = datetime(now.year, now.month, now.day, tzinfo=timezone.utc) - timedelta(days=3)
def pdt(s): return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")

IRR = {"AIBuzzNews","AIGuideHQ","AITECHio","AIFrontliner","TheAIColony","AITOPIAai","AISuperDomain",
 "GoogleLabs","GoogleAI","DonutAI","cladlabs","FaithJaiye2187","KammelaBala","MyStageAI","AlexStudio44",
 "AI_with_jasmin","Ai_Vaidehi","ChrisLaubAI","OpenAI","AnthropicAI","CINEMA505","AIScottAdams",
 "AI_Jasonyu","AIByLeo"}
FILM = {"DiscussingFilm","nofilmschool"}
core = sorted([q for q in qual if q["handle"] not in IRR and q["handle"] not in FILM], key=lambda x:-x["score"])

print("===== OUTLIER VERIFY (core top 5) =====")
for q in core[:5]:
    h = q["handle"]
    tid = q["url"].rstrip("/").split("/")[-1]
    rec = next((r for r in raw[h] if str(r.get("id")) == tid), None)
    if not rec:
        print(f"@{h} id={tid} NOT FOUND in raw"); continue
    author = (rec.get("author") or {}).get("userName")
    media = rec.get("media")
    mtype = media[0].get("type") if isinstance(media, list) and media else media
    base = max([(r.get("likeCount") or 0) for r in raw[h] if r is not rec] + [0])
    print(f"@{h} {q['likes']}L/{q['views']}V author={author} rt={'Y' if rec.get('retweeted_tweet') else 'N'} "
          f"quote={'Y' if rec.get('quoted_tweet') else 'N'} media={mtype} own_baseline_max={base} "
          f"ratio={(q['likes'] or 1)/max(base,1):.1f}x")

print("\n===== FULL TEXT: key offers =====")
TARGETS = [
 ("nofilmschool", r"davinci"),
 ("azed_ai", r"topaz"),
 ("higgsfield", r"(genjutsu|wan ?3\.0 prime)"),
 ("AIFrontliner", r"dreamina"),
 ("Ai_Vaidehi", r"capcut"),
]
for h, pat in TARGETS:
    rgx = re.compile(pat, re.I)
    for it in raw.get(h, []):
        if pdt(it["createdAt"]) < cutoff: continue
        if rgx.search(it.get("text") or ""):
            print(f"\n@{h} {it.get('likeCount')}L/{it.get('viewCount')}V {it['createdAt']}")
            print(f"  {re.sub(chr(10),' ', it.get('text') or '')}")
            print(f"  https://x.com/{h}/status/{it.get('id')}")

print("\n===== FRESHEST QUALIFYING (10-20 12:00 onwards) =====")
t0 = datetime(2026,10,20,12,0, tzinfo=timezone.utc)
fresh = [q for q in qual]
def qdt(q):
    return datetime.strptime(q["date"].replace(" UTC",""), "%Y-%m-%d %H:%M").replace(tzinfo=timezone.utc)
fresh = [q for q in fresh if qdt(q) >= t0]
fresh.sort(key=qdt)
print(f"{len(fresh)} qualifying posts since 10-20 12:00")
for q in fresh:
    print(f"{q['date']}|@{q['handle']:14s}|{q['likes']}L/{q['views']}V|{q['text'][:150].replace(chr(10),' ')}")
    print(f"   {q['url']}")

print("\n===== NOFILMSCHOOL full in-window list =====")
for it in raw.get("nofilmschool", []):
    if pdt(it["createdAt"]) < cutoff: continue
    print(f"{it.get('likeCount')}L/{it.get('viewCount')}V {it['createdAt']} :: {re.sub(chr(10),' ',(it.get('text') or ''))[:160]}")
