import json
from datetime import datetime, timezone, timedelta

today = "2026-08-29"
out_path = f"/home/kiro/trend-engine/trends/x/scan_results_{today}_FULL.json"
with open(out_path) as f:
    data = json.load(f)

CORE = [
    "runwayml", "CuriousRefuge", "nofilmschool", "venturetwins", "Kling_ai",
    "paultrillo", "c_valenzuelab", "CorridorDigital", "karenxcheng", "higgsfield",
    "pika_labs", "EHuanglu", "azed_ai", "JeffSynthesized", "ai_filmmaker",
    "visiblemaker", "Magiermogul", "WuxiaRocks", "JiamingSuen", "moonvalley",
    "higgsfield_ai", "Chandan_Perla",
]
core_set = set(CORE)

cutoff = datetime.now(timezone.utc) - timedelta(days=3)
cutoff = cutoff.replace(hour=0, minute=0, second=0, microsecond=0)
DATE_FMT = "%a %b %d %H:%M:%S %z %Y"

def parse_date(s):
    try:
        return datetime.strptime(s, DATE_FMT)
    except Exception:
        return None

qualifying = []
filtered = []
for handle, tweets in data["results"].items():
    if not tweets:
        continue
    is_core = handle in core_set
    for tw in tweets:
        if not isinstance(tw, dict):
            continue
        if tw.get("retweeted_tweet"):
            continue
        likes = tw.get("likeCount") or 0
        rts = tw.get("retweetCount") or 0
        replies = tw.get("replyCount") or 0
        views = tw.get("viewCount") or 0
        score = likes + (rts * 2) + (replies * 3) + (views / 100)
        created = tw.get("createdAt") or tw.get("created_at")
        dt = parse_date(created) if created else None
        in_window = dt is not None and dt >= cutoff
        qualifies = likes >= 50 or rts >= 10 or views >= 1000
        if qualifies and in_window:
            e = {"handle": handle, "id": tw.get("id"), "score": score,
                 "likes": likes, "rts": rts, "replies": replies, "views": views,
                 "dt": dt, "text": (tw.get("text") or "")}
            (qualifying if is_core else filtered).append(e)

qualifying.sort(key=lambda x: -x["score"])
filtered.sort(key=lambda x: -x["score"])

def fmt_url(h, tid):
    return f"https://x.com/{h}/status/{tid}"

def snippet(text, n=90):
    t = " ".join((text or "").split())
    return t[:n] + ("..." if len(t) > n else "")

lines = []
lines.append("X ACCOUNT MONITOR — " + today)
lines.append("=" * 40)
lines.append(f"Scanned {len(data['results'])} accounts | {len(qualifying)} core + {len(filtered)} filtered qualifying tweets | window: last 3 days")
if data.get("failed"):
    lines.append(f"Failed: {', '.join(data['failed'])}")
lines.append("")

lines.append("TOP 10 — CORE ACCOUNTS")
lines.append("-" * 40)
for i, e in enumerate(qualifying[:10], 1):
    lines.append(f"#{i} | @{e['handle']}")
    lines.append(f"    {fmt_url(e['handle'], e['id'])}")
    lines.append(f"    Views: {e['views']:,} | Likes: {e['likes']:,} | RT: {e['rts']:,} | Replies: {e['replies']:,}")
    lines.append(f"    {snippet(e['text'])}")
    lines.append("")

if len(qualifying) > 10:
    lines.append(f"(+{len(qualifying)-10} more core tweets below top-10 cutoff)")
    lines.append("")

# Inactive core accounts note
active_core = {e['handle'] for e in qualifying}
inactive = [h for h in CORE if h not in active_core]
if inactive:
    lines.append("INACTIVE CORE (no qualifying tweet in window)")
    lines.append("-" * 40)
    for h in inactive:
        lines.append(f"  - @{h}")
    lines.append("")

if filtered:
    lines.append("FILTERED (auto-discovered / non-core) — NOT in top 10")
    lines.append("-" * 40)
    by_handle = {}
    for e in filtered:
        by_handle.setdefault(e['handle'], []).append(e)
    for handle, entries in by_handle.items():
        top = entries[0]
        lines.append(f"  @{handle}: {len(entries)} qualifying — best {top['views']:,} views")
        lines.append(f"      {fmt_url(top['handle'], top['id'])}")
        lines.append(f"      {snippet(top['text'])}")
        lines.append("")

print("\n".join(lines))
