#!/usr/bin/env python3
"""Generate report from scan data — 2026-06-15"""
import json

RESULTS_FILE = "/home/kiro/trend-engine/trends/x/account-monitor/scan_results_2026-06-15.json"
OUTPUT_FILE = "/home/kiro/trend-engine/trends/x/account-monitor/2026-06-15_account-monitor.txt"

IRRELEVANT_HANDLES = {
    "CINEMA505", "TheAIColony", "GoogleLabs", "GoogleAI", "Ai_Vaidehi",
    "AI_with_jasmin", "CharaspowerAI", "AIBuzzNews", "AlexStudio44",
    "FaithJaiye2187", "KammelaBala", "MyStageAI",
}

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": "Cristóbal 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)",
}

with open(RESULTS_FILE) as f:
    data = json.load(f)

# Collect all qualifying tweets
all_tweets = []
for acc in data["accounts"]:
    handle = acc["handle"]
    is_irrelevant = acc.get("is_irrelevant", False) or handle in IRRELEVANT_HANDLES
    for t in acc.get("tweets", []):
        all_tweets.append({
            "handle": handle,
            "is_irrelevant": is_irrelevant,
            **t,
        })

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

# Build top 10 — filter irrelevant
top10 = []
for t in all_tweets:
    if t["is_irrelevant"]:
        continue
    if len(top10) >= 10:
        break
    top10.append(t)

# Build report
lines = []
lines.append("Title: X Account Monitor -- 2026-06-15")
lines.append("")
lines.append("Top 10 by Engagement Score")
lines.append("")
lines.append(f"{'#':>2}  {'Account':<22}  {'Best Tweet':<85}  {'Views':>8}  {'Date':>10}")
lines.append("-" * 145)

for i, t in enumerate(top10, 1):
    handle = t["handle"]
    text = t["text"].replace("\n", " ").strip()
    # Truncate text for display
    if len(text) > 60:
        text = text[:57] + "..."
    tweet_id = t["id"]
    url = f"https://x.com/{handle}/status/{tweet_id}" if tweet_id else ""
    views = t["views"]
    date = t["date"]

    # Format: #, Account, Txt (URL), Views, Date
    display = f"{text} ({url})"
    lines.append(f"{i:>2}  {handle:<22}  {display:<85}  {views:>8,}  {date:>10}")

# Summary counts
total_accounts = len(data["accounts"])
accounts_with_content = sum(1 for acc in data["accounts"] if acc["qualifying_count"] > 0)
total_qual_tweets = len(all_tweets)
errors = len(data.get("errors", []))

lines.append("")
lines.append(f"--- Summary: {total_accounts} scans total, {accounts_with_content} accounts with qualifying tweets, {total_qual_tweets} qualifying tweets found. {errors} API failures.")
lines.append("")

# Detailed per-account breakdown
lines.append("--- Full Account Breakdown ---")
lines.append("")

for acc in data["accounts"]:
    handle = acc["handle"]
    tweets = acc.get("tweets", [])
    qcount = acc.get("qualifying_count", 0)
    rcount = acc.get("recent_count", 0)
    is_irrelevant = acc.get("is_irrelevant", False) or handle in IRRELEVANT_HANDLES
    bio = BIO_INFO.get(handle, "")

    marker = " [FILTERED]" if is_irrelevant else ""
    header = f"  @{handle}{marker}"
    if bio:
        header += f" ({bio})"

    if qcount == 0:
        lines.append(f"{header} — {rcount} recent, 0 qualifying tweets")
    else:
        lines.append(f"{header} — {rcount} recent, {qcount} qualifying:")
        for t in tweets:
            rt_mark = " [RT]" if t.get("is_rt") else ""
            text = t["text"].replace("\n", " ").strip()
            if len(text) > 80:
                text = text[:77] + "..."
            tweet_id = t["id"]
            url = f"https://x.com/{handle}/status/{tweet_id}" if tweet_id else ""
            lines.append(f"    Score={t['score']:.1f}  L={t['likes']:,}  RT={t['retweets']:,}  Rpl={t['replies']:,}  V={t['views']:,}  {t['date']}{rt_mark}")
            lines.append(f"    {text}")
            if url:
                lines.append(f"    {url}")

    lines.append("")

# Errors
if errors:
    lines.append("--- API Errors ---")
    for e in data.get("errors", []):
        lines.append(f"  {e}")
    lines.append("")

report = "\n".join(lines)

# Save
with open(OUTPUT_FILE, "w") as f:
    f.write(report)

print(f"Report written to {OUTPUT_FILE}")
print(f"Top 10: {len(top10)} accounts")
print(f"Total qualifying: {len(all_tweets)} tweets from {accounts_with_content} accounts")

# Print top 10 preview
print("\n--- Top 10 Preview ---")
for i, t in enumerate(top10, 1):
    text = t["text"][:60]
    print(f"  {i}. @{t['handle']} score={t['score']:.1f} V={t['views']:,} L={t['likes']:,} RT={t['retweets']:,} | {text}")
