#!/usr/bin/env python3
"""Generate X Account Monitor report from scan JSON files."""
import json, os
from datetime import datetime

CHUNK1 = "/home/kiro/trend-engine/trends/x/account-monitor/scan_results_2026-06-18_CHUNK1.json"
CHUNK2 = "/home/kiro/trend-engine/trends/x/account-monitor/scan_results_2026-06-18_CHUNK2.json"
OUTPUT = "/home/kiro/trend-engine/trends/x/account-monitor/2026-06-18_account-monitor.txt"
DATE_STR = "2026-06-18"

IRRELEVANT = {
    "CINEMA505", "TheAIColony", "GoogleLabs", "GoogleAI",
    "Ai_Vaidehi", "AI_with_jasmin", "CharaspowerAI",
    "AIBuzzNews", "ChrisLaubAI", "FaithJaiye2187",
    "KammelaBala", "MyStageAI", "AlexStudio44", "AIGuideHQ",
    "4aibsc",
}

BIO_INFO = {
    "runwayml": "Runway AI — professional AI filmmaking (~260K)",
    "CuriousRefuge": "Curious Refuge — home for AI filmmakers",
    "nofilmschool": "No Film School — filmmaking news (~241.7K)",
    "venturetwins": "Justine Moore — a16z partner AI video (~149.5K)",
    "Kling_ai": "Kling AI — AI video generation (~130K)",
    "paultrillo": "Paul Trillo — LA director/artist (~15K)",
    "c_valenzuelab": "Cristobal Valenzuela — Runway CEO (~42.7K)",
    "CorridorDigital": "Corridor Digital — VFX/filmmaking (15M+ YouTube)",
    "karenxcheng": "Karen X. Cheng — Director, brand AI video (~58K)",
    "higgsfield": "Higgsfield AI — multi-model platform (~63K)",
    "pika_labs": "Pika — AI video for social creators (~143K)",
    "EHuanglu": "el.cine / Elsa Huang — Film director, AI consultant (~128K)",
    "azed_ai": "Amira Zairi — Adobe & Leonardo AI ambassador (~37K)",
    "JeffSynthesized": "Jeff Synthesized — NeoCinema AI Studio founder (~8.5K)",
    "ai_filmmaker": "Dmitry Alekseev — Film director/AI filmmaker",
    "visiblemaker": "The Visiblemaker — AI cinema director",
    "Magiermogul": "Particle Panic — AI filmmaker, Kling/Runway CPP",
    "WuxiaRocks": "WuxIA Rocks — AI filmmaker, character consistency (~6.5K)",
    "JiamingSuen": "Jiaming Sun — AI/VFX creator",
    "moonvalley": "Moonvalley — AI film model startup",
    "higgsfield_ai": "Higgsfield AI (secondary) — Kling/Seedance integration news",
    "Chandan_Perla": "Chandan Perla — India AI Film Festival organizer",
    "AITOPIAai": "AI platform — Grok Imagine Video integrations",
    "AI_Video_Dumps": "AI video content aggregator",
    "cladlabs": "CLAD Labs — AI/creative tools",
    "DonutAI": "AI tool ecosystem — small but on-topic",
    "AIFrontliner": "AI news aggregator — ChatGPT/Claude, some Seedance",
    "AIWarper": "AI creator — Seedance 2.0, ComfyUI workflows",
    "AITECHio": "AI/crypto hybrid — ACN token, AI infrastructure",
    "ChrisLaubAI": "RT-only — FILTERED (finance/news RTs)",
    "CINEMA505": "Brazilian cinema account — FILTERED (non-AI)",
    "TheAIColony": "General AI news aggregator — FILTERED",
    "GoogleLabs": "Google product news — FILTERED",
    "GoogleAI": "Google AI — FILTERED",
    "Ai_Vaidehi": "RT aggregator — FILTERED",
    "AI_with_jasmin": "RT/job board aggregator — FILTERED",
    "CharaspowerAI": "RT-heavy general AI — FILTERED",
    "AIBuzzNews": "General AI news — FILTERED",
}

# Load both chunks
all_accounts = []
all_errors = []
for chunk_file in [CHUNK1, CHUNK2]:
    with open(chunk_file) as f:
        data = json.load(f)
    all_accounts.extend(data.get("accounts", []))
    all_errors.extend(data.get("errors", []))

total_scanned = len(all_accounts) + len(all_errors)

# Collect all qualifying tweets with their account info (handle, bio)
all_tweets = []
accounts_with_content = 0
accounts_with_qualifying = 0
total_fetched_total = 0
for acc in all_accounts:
    tweet_count = acc.get("total_fetched", 0)
    total_fetched_total += tweet_count
    if tweet_count > 0:
        accounts_with_content += 1
    for t in acc.get("tweets", []):
        t["handle"] = acc["handle"]
        t["bio"] = BIO_INFO.get(acc["handle"], "")
        all_tweets.append(t)
    if len(acc.get("tweets", [])) > 0:
        accounts_with_qualifying += 1

# Sort by score descending
all_tweets.sort(key=lambda x: x["score"], reverse=True)

# Separate top 10 by unique account (best tweet per account)
seen_handles_top10 = set()
top10_relevant = []
for t in all_tweets:
    if t["handle"] in IRRELEVANT:
        continue
    if t["handle"] in seen_handles_top10:
        continue
    seen_handles_top10.add(t["handle"])
    top10_relevant.append(t)
    if len(top10_relevant) >= 10:
        break

# Build report
lines = []
lines.append(f"Title: X Account Monitor — {DATE_STR}")
lines.append("")

lines.append("Top 10 by Engagement Score")
lines.append("")
lines.append("#, Account, Best Tweet, Views, Date")
for i, t in enumerate(top10_relevant):
    handle = t["handle"]
    url = f"https://x.com/{handle}/status/{t['id']}"
    snippet = t["text"][:80]
    date = t["date"]
    views = f"{t['views']:,}"
    lines.append(f"{i+1}, @{handle}, {snippet} ({url}), {views}, {date}")

lines.append("")

# Full breakdown
lines.append("--- Full Breakdown ---")
lines.append("")

for acc in all_accounts:
    handle = acc["handle"]
    bio = acc.get("bio", BIO_INFO.get(handle, ""))
    tweets = acc.get("tweets", [])
    fetched = acc.get("total_fetched", 0)
    
    is_filtered = handle in IRRELEVANT
    filter_tag = " [FILTERED]" if is_filtered else ""
    
    if len(tweets) == 0:
        if fetched == 0:
            lines.append(f"@{handle}{filter_tag}: 0 tweets fetched (empty/suspended)")
        else:
            lines.append(f"@{handle}{filter_tag}: {fetched} tweets fetched, 0 qualifying")
    else:
        top = tweets[0]
        lines.append(f"@{handle}{filter_tag} ({bio}): {len(tweets)} qualifying tweets")
        for j, t in enumerate(tweets[:3]):
            url = f"https://x.com/{handle}/status/{t['id']}"
            lines.append(f"  [{t['score']}pts] {t['text'][:100]} ({url}) — {t['likes']}L/{t['retweets']}RT/{t['views']}V, {t['date']}")
    lines.append("")

# Summary
lines.append("---")
lines.append(f"Summary: {total_scanned} accounts scanned, {accounts_with_content} with content, {accounts_with_qualifying} with qualifying tweets. {len(all_errors)} API failures.")

# Write to file
with open(OUTPUT, "w") as f:
    f.write("\n".join(lines))

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