#!/usr/bin/env python3
"""Generate the plain-text X Account Monitor report from merged scan results."""

import json
import os
from datetime import datetime, timezone

# Config
CHUNK1 = "/home/kiro/trend-engine/trends/x/account-monitor/scan_results_2026-06-16_CHUNK1.json"
CHUNK2 = "/home/kiro/trend-engine/trends/x/account-monitor/scan_results_2026-06-16_CHUNK2.json"
OUTPUT_DIR = "/home/kiro/trend-engine/trends/x/account-monitor"
DATE_STR = "2026-06-16"

# IRRELEVANT HANDLES (filter from Top 10, show [FILTERED] in breakdown)
IRRELEVANT = {
    "CINEMA505",        # Brazilian cinema account (Portuguese), non-AI
    "TheAIColony",      # General AI news aggregator
    "GoogleLabs",       # Large corporate, general Google products
    "GoogleAI",         # Large corporate, Gemini launches
    "Ai_Vaidehi",       # RT aggregator, 0 original posts
    "AI_with_jasmin",   # RT aggregator, remote job lists
    "CharaspowerAI",    # RT-heavy general AI
    "AIBuzzNews",       # General AI news, not filmmaking
    "AlexStudio44",     # No qualifying tweets, unclear niche
    "FaithJaiye2187",   # 0 qualifying tweets consistently
    "KammelaBala",      # 0 qualifying tweets consistently  
    "MyStageAI",        # 0 qualifying tweets consistently
    "ChrisLaubAI",      # 100% RTs of non-filmmaking (finance/news)
    "AIGuideHQ",        # 0 qualifying tweets consistently
}

# These accounts are actually relevant AI filmmaking despite being auto-discovered
# (kept for comparison — only filter the IRRELEVANT set above)

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)",
    "azed_ai": "Amira Zairi — Adobe & Leonardo AI ambassador (~37K)",
    "ChrisLaubAI": "RT-only account — FILTERED, zero AI filmmaking content",
    "AIFrontliner": "AI news aggregator — Seedance, Claude, AI filmmaking mentions",
    "AIWarper": "AI creator — Seedance 2.0 prompts, ComfyUI workflows",
    "AITECHio": "AI/crypto hybrid — ACN token, AI infrastructure",
    "DonutAI": "AI tool ecosystem — small but on-topic",
    "JeffSynthesized": "Jeff Synthesized — NeoCinema AI Studio, Runway/Kling CPP (~8.5K)",
    "ai_filmmaker": "Dmitry Alekseev — AI filmmaker, Curious Refuge featured",
    "visiblemaker": "Christian Fleischer — AI cinema director, The Great Catspy (50M+ views)",
    "Magiermogul": "Particle Panic — AI filmmaker, $1M AI Film Award CPP",
    "WuxiaRocks": "WuxIA Rocks — AI filmmaking, character consistency (~6.5K)",
    "JiamingSuen": "Jiaming Sun — AI/VFX creator, CorridorDigital collaborator (~900)",
    "moonvalley": "Moonvalley — clean-trained AI film model, Paul Trillo partnership",
    "higgsfield_ai": "Higgsfield AI — ops account, Kling integrations, prompt drops",
    "Chandan_Perla": "Chandan Perla — India AI Film Festival organizer",
    "AITOPIAai": "AI TOPIA — Grok Imagine Video integrations, tool content",
    "AI_Video_Dumps": "AI Video Dumps — AI filmmaking clips and demos",
    "cladlabs": "Clad Labs — AI/tech (small account)",
    "4aibsc": "4AI BSC — AI content (auto-discovered)",
}

def format_snippet(text, max_len=65):
    """Truncate tweet text for display."""
    # Remove newlines
    text = text.replace("\n", " ").replace("\r", " ").strip()
    if len(text) <= max_len:
        return text
    return text[:max_len-3] + "..."

def main():
    # Merge chunks
    all_accounts = []
    
    for chunk_path in [CHUNK1, CHUNK2]:
        with open(chunk_path) as f:
            data = json.load(f)
        all_accounts.extend(data["accounts"])
    
    # Build best-tweet-per-account for Top 10
    account_best = {}  # handle -> best entry
    
    for acc in all_accounts:
        handle = acc["handle"]
        tweets = acc.get("tweets", [])
        
        for t in tweets:
            tweet_id = t.get("id", "")
            url = f"https://x.com/{handle}/status/{tweet_id}" if tweet_id else ""
            entry = {
                "handle": handle,
                "tweet": t,
                "text": t.get("text", ""),
                "score": t.get("score", 0),
                "url": url,
                "date": t.get("date", ""),
                "views": t.get("views", 0),
                "likes": t.get("likes", 0),
                "retweets": t.get("retweets", 0),
                "replies": t.get("replies", 0),
            }
            if handle not in account_best or entry["score"] > account_best[handle]["score"]:
                account_best[handle] = entry
    
    # Build flat entries list for full breakdown
    entries = []
    for acc in all_accounts:
        handle = acc["handle"]
        tweets = acc.get("tweets", [])
        for t in tweets:
            tweet_id = t.get("id", "")
            url = f"https://x.com/{handle}/status/{tweet_id}" if tweet_id else ""
            entries.append({
                "handle": handle,
                "tweet": t,
                "text": t.get("text", ""),
                "score": t.get("score", 0),
                "url": url,
                "date": t.get("date", ""),
                "views": t.get("views", 0),
                "likes": t.get("likes", 0),
                "retweets": t.get("retweets", 0),
                "replies": t.get("replies", 0),
            })
    
    # Top 10: best per account, sorted by score
    top10_candidates = [e for e in account_best.values() if e["handle"] not in IRRELEVANT]
    top10_candidates.sort(key=lambda x: x["score"], reverse=True)
    
    # Build lines
    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")
    
    rank = 0
    for entry in top10_candidates[:10]:
        rank += 1
        handle = entry["handle"]
        snippet = format_snippet(entry["text"])
        line = f"{rank}, @{handle}, {snippet} ({entry['url']}), {entry['views']}, {entry['date']}"
        lines.append(line)
    
    lines.append("")
    lines.append("---")
    lines.append("")
    lines.append("Full Account Breakdown")
    lines.append("")
    
    # Group by account
    acc_map = {}
    for entry in entries:
        h = entry["handle"]
        if h not in acc_map:
            acc_map[h] = []
        acc_map[h].append(entry)
    
    total_scans = len(all_accounts)
    accounts_with_content = sum(1 for acc in all_accounts if acc.get("qualifying_count", 0) > 0)
    total_qualifying = sum(acc.get("qualifying_count", 0) for acc in all_accounts)
    
    # Sort accounts by their best tweet score
    account_order = sorted(acc_map.keys(), key=lambda h: max(e["score"] for e in acc_map[h]), reverse=True)
    
    for handle in account_order:
        entries = acc_map[handle]
        best = entries[0]
        bio = BIO_INFO.get(handle, "")
        is_irrelevant = handle in IRRELEVANT
        tag = " [FILTERED]" if is_irrelevant else ""
        qual_count = len(entries)
        
        lines.append(f"@{handle}{tag} — {qual_count} qualifying tweets")
        if bio:
            lines.append(f"  {bio}")
        
        for i, e in enumerate(entries[:5]):
            snippet = format_snippet(e["text"], max_len=80)
            lines.append(f"  [{e['date']}] L{e['likes']} RT{e['retweets']} R{e['replies']} V{e['views']} | {snippet}")
            lines.append(f"    {e['url']}")
        lines.append("")
    
    lines.append("---")
    lines.append(f"Summary: {total_scans} scans total, {accounts_with_content} accounts with qualifying tweets, {total_qualifying} qualifying tweets found.")
    
    # Count filtered
    filtered_qual = sum(
        acc.get("qualifying_count", 0) for acc in all_accounts if acc["handle"] in IRRELEVANT
    )
    lines.append(f"  {len(IRRELEVANT)} accounts filtered from Top 10 as irrelevant ({filtered_qual} qualifying tweets excluded).")
    
    # Errors
    error_count = 0
    for chunk_path in [CHUNK1, CHUNK2]:
        with open(chunk_path) as f:
            data = json.load(f)
        error_count += len(data.get("errors", []))
    if error_count:
        lines.append(f"  {error_count} API errors (non-blocking).")
    
    report = "\n".join(lines)
    
    # Save to disk
    output_path = os.path.join(OUTPUT_DIR, f"{DATE_STR}_account-monitor.txt")
    with open(output_path, "w") as f:
        f.write(report)
    
    print(f"Report saved to {output_path}")
    print(f"  Total entries: {len(entries)}")
    print(f"  Top 10 shown: {len(top10_candidates[:10])}")
    print()
    print(report)

if __name__ == "__main__":
    main()
