#!/usr/bin/env python3
import json, os
from datetime import datetime, timezone

today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
path = f"/home/kiro/trend-engine/trends/x/scan_results_{today}.json"
data = json.load(open(path))

IRRELEVANT_HANDLES = {
    "AIBuzzNews", "AIGuideHQ", "AITECHio", "AIFrontliner", "AIWarper", "TheAIColony", "AITOPIAai",
    "GoogleLabs", "GoogleAI", "DonutAI", "cladlabs", "4aibsc", "FaithJaiye2187", "KammelaBala", "MyStageAI", "AlexStudio44",
    "AI_Video_Dumps", "AI_with_jasmin", "Ai_Vaidehi", "CharaspowerAI", "ChrisLaubAI",
    "CINEMA505", "Chandan_Perla"
}

BIO = {
    "runwayml": "Runway AI (Gen-4.5)",
    "CuriousRefuge": "AI film home",
    "nofilmschool": "No Film School",
    "venturetwins": "Justine Moore (a16z)",
    "Kling_ai": "Kling AI",
    "paultrillo": "Paul Trillo (dir)",
    "c_valenzuelab": "Runway CEO",
    "CorridorDigital": "Corridor Digital",
    "karenxcheng": "Karen X. Cheng",
    "higgsfield": "Higgsfield AI",
    "pika_labs": "Pika",
    "EHuanglu": "el.cine (Elsa Huang)",
    "azed_ai": "Amira Zairi",
    "JeffSynthesized": "Jeff Synthesized",
    "ai_filmmaker": "Dmitry Alekseev",
    "visiblemaker": "The Visiblemaker",
    "Magiermogul": "Particle Panic",
    "WuxiaRocks": "WuxIA Rocks",
    "JiamingSuen": "Jiaming Sun",
    "moonvalley": "Moonvalley",
    "higgsfield_ai": "Higgsfield (ops)",
}

# Build flat list of (tweet dict) with score
all_tweets = []
for handle, tweets in data["results"].items():
    for t in tweets:
        t["_handle"] = handle
        all_tweets.append(t)

# Top 10 by score, excluding irrelevant
relevant = [t for t in all_tweets if t["_handle"] not in IRRELEVANT_HANDLES]
relevant.sort(key=lambda x: x["score"], reverse=True)

print("=" * 60)
print(f"X ACCOUNT MONITOR — {today}")
print(f"Scanned {len(data['results'])} active accounts / 44 watchlist")
print("=" * 60)
print()

print("TOP 10 (by engagement score)")
print("-" * 60)
for i, t in enumerate(relevant[:10], 1):
    handle = t["_handle"]
    url = f"https://x.com/{handle}/status/{t['id']}"
    date = t["created"][:16] if t.get("created") else "?"
    views = t["views"]
    likes = t["likes"]
    rts = t["rts"]
    replies = t["replies"]
    bio = BIO.get(handle, handle)
    text = t["text"].replace("\n", " ")[:120]
    print(f"{i}. @{handle} ({bio})")
    print(f"   {text}")
    print(f"   {url}")
    print(f"   Views: {views:,} | Likes: {likes:,} | RTs: {rts} | Replies: {replies} | {date}")
    print()

# Filtered section
filtered = [t for t in all_tweets if t["_handle"] in IRRELEVANT_HANDLES]
if filtered:
    print("FILTERED (auto-discovered, non-core)")
    print("-" * 60)
    for t in sorted(filtered, key=lambda x: x["score"], reverse=True)[:8]:
        handle = t["_handle"]
        url = f"https://x.com/{handle}/status/{t['id']}"
        text = t["text"].replace("\n", " ")[:100]
        print(f"  @{handle}: {text}")
        print(f"    {url}  (views {t['views']:,})")

# Failed
if data.get("failed"):
    print()
    print("FAILED:")
    for h, e in data["failed"]:
        print(f"  {h}: {e}")
