import json, os

DATE_STR = "2026-06-21"
OUT_DIR = "/home/kiro/trend-engine/trends/x/account-monitor"
REPORT_FILE = os.path.join(OUT_DIR, f"{DATE_STR}_account-monitor.txt")

# Irrelevant handles (non-AI-filmmaking)
IRRELEVANT_HANDLES = {
    "ChrisLaubAI",    # RT-only finance/news
    "CINEMA505",      # Brazilian cinema, non-AI
    "TheAIColony",    # General AI news aggregator
    "GoogleLabs",     # Corporate, non-filmmaking
    "GoogleAI",       # Corporate, non-filmmaking
    "Ai_Vaidehi",     # RT aggregator
    "AITOPIAai",      # General AI news
    "FaithJaiye2187", # Low engagement consistently
    "KammelaBala",    # Low engagement consistently
    "MyStageAI",      # Low engagement consistently
    "AlexStudio44",   # Low engagement consistently
    "AIGuideHQ",      # Low engagement consistently
}

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, LA",
    "ai_filmmaker": "Dmitry Alekseev -- Film director/AI filmmaker",
    "visiblemaker": "The Visiblemaker (Christian Fleischer) -- AI cinema director",
    "Magiermogul": "Particle Panic -- AI filmmaker, contest finalist",
    "WuxiaRocks": "WuxIA Rocks -- AI filmmaker, long-form storytelling",
    "JiamingSuen": "Jiaming Sun -- AI/VFX creator (CorridorDigital collab)",
    "moonvalley": "Moonvalley -- AI film model startup",
    "higgsfield_ai": "Higgsfield AI (secondary/ops account)",
    "Chandan_Perla": "Chandan Perla -- India AI Film Festival organizer",
    "AITOPIAai": "[FILTERED] General AI news",
    "FaithJaiye2187": "[FILTERED] Low engagement",
    "KammelaBala": "[FILTERED] Low engagement",
    "MyStageAI": "[FILTERED] Low engagement",
    "AI_Video_Dumps": "AI video content aggregator",
    "ChrisLaubAI": "[FILTERED] RT-only finance/news",
    "GoogleLabs": "[FILTERED] Corporate account",
    "TheAIColony": "[FILTERED] General AI news aggregator",
    "cladlabs": "CLAD labs",
    "AIBuzzNews": "AI news aggregator -- ChatGPT/Claude/Seedance",
    "AlexStudio44": "[FILTERED] Low engagement",
    "DonutAI": "AI tool ecosystem",
    "GoogleAI": "[FILTERED] Corporate account",
    "AI_with_jasmin": "AI creator",
    "CharaspowerAI": "Seedance 2 creator -- original anime VFX, kaiju",
    "Ai_Vaidehi": "[FILTERED] RT aggregator",
    "CINEMA505": "[FILTERED] Brazilian cinema, non-AI",
    "AIFrontliner": "AI news aggregator -- ChatGPT/Claude prompts, Seedance",
    "AIGuideHQ": "[FILTERED] Low engagement",
    "AIWarper": "AI creator -- Seedance 2.0 prompts, ComfyUI workflows",
    "AITECHio": "AI/crypto hybrid -- ACN token, AI infrastructure",
    "4aibsc": "AI creator",
}

# Load both chunks
with open(f"{OUT_DIR}/scan_results_2026-06-21_CHUNK1.json") as f:
    c1 = json.load(f)
with open(f"{OUT_DIR}/scan_results_2026-06-21_CHUNK2.json") as f:
    c2 = json.load(f)

# Merge all tweets
all_tweets = []
accounts_with_content = 0
total_qualifying = 0
error_handles = []
empty_handles = []

for chunk in [c1, c2]:
    for acc in chunk["accounts"]:
        handle = acc["handle"]
        if acc.get("qualifying_count", 0) > 0:
            accounts_with_content += 1
            total_qualifying += acc["qualifying_count"]
            for t in acc["tweets"]:
                all_tweets.append(t)
        elif acc.get("qualifying_count", 0) == 0 and handle not in [e["handle"] for e in chunk.get("errors", [])]:
            empty_handles.append(handle)
    
    for e in chunk.get("errors", []):
        error_handles.append(f"{e['handle']}: {e['error']}")

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

# Build deduped top 10 (skip irrelevant AND duplicate handles)
seen_handles = set()
deduped_top10 = []
for t in all_tweets:
    h = t["handle"]
    if h not in IRRELEVANT_HANDLES and h not in seen_handles:
        seen_handles.add(h)
        deduped_top10.append(t)
    if len(deduped_top10) >= 10:
        break

# Count scans
total_scans = len(c1["accounts"]) + len(c2["accounts"])

# 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 rank, t in enumerate(deduped_top10, 1):
    url = f"https://x.com/{t['handle']}/status/{t['tweet_id']}"
    snippet = t["text"].replace(",", " ").strip()
    lines.append(f"{rank}, @{t['handle']}, {snippet} ({url}), {t['views']}, {t['date']}")

lines.append("")
lines.append("Full Breakdown by Account")
lines.append("")

# Sort accounts by max score
account_max_scores = {}
for t in all_tweets:
    h = t["handle"]
    if h not in account_max_scores or t["score"] > account_max_scores[h]["score"]:
        account_max_scores[h] = t

sorted_accounts = sorted(account_max_scores.items(), key=lambda x: x[1]["score"], reverse=True)

for handle, best_tweet in sorted_accounts:
    bio = BIO_INFO.get(handle, "")
    marker = " [FILTERED]" if handle in IRRELEVANT_HANDLES else ""
    
    lines.append(f"@{handle}{marker} -- {bio}")
    
    # Get all qualifying tweets for this account
    account_tweets = [t for t in all_tweets if t["handle"] == handle]
    account_tweets_sorted = sorted(account_tweets, key=lambda t: t["score"], reverse=True)
    
    for t in account_tweets_sorted:
        url = f"https://x.com/{t['handle']}/status/{t['tweet_id']}"
        # is_rt check
        is_rt = t.get("full_text", "").startswith("RT @") if t.get("full_text") else False
        rt_marker = " [RT]" if is_rt else ""
        lines.append(f"  Score:{t['score']} Likes:{t['likes']} RTs:{t['retweets']} Views:{t['views']} Date:{t['date']}{rt_marker}")
        lines.append(f"  {t['text']}")
        lines.append(f"  {url}")
        lines.append("")
    
    lines.append("")

# Accounts with no qualifying tweets
if empty_handles:
    lines.append("Accounts with No Qualifying Tweets (recent but below thresholds)")
    lines.append("")
    for h in sorted(empty_handles):
        bio = BIO_INFO.get(h, "")
        lines.append(f"  @{h} -- {bio}")
    lines.append("")

# Errors
if error_handles:
    lines.append("API Errors")
    lines.append("")
    for e in error_handles:
        lines.append(f"  {e}")
    lines.append("")

lines.append("Summary")
lines.append(f"Total scans: {total_scans}")
lines.append(f"Accounts with content: {accounts_with_content}")
lines.append(f"Total qualifying tweets: {total_qualifying}")
lines.append(f"API failures: {len(error_handles)}")
lines.append(f"Accounts with no qualifying tweets: {len(empty_handles)}")

report_text = "\n".join(lines)

# Write to file
os.makedirs(OUT_DIR, exist_ok=True)
with open(REPORT_FILE, "w") as f:
    f.write(report_text)

print(f"Report written to {REPORT_FILE}")
print(f"Report size: {len(report_text)} chars")
print(f"Top 10 entries: {len(deduped_top10)}")
print(f"Total accounts with tweets: {accounts_with_content}")
print(f"Total qualifying tweets: {total_qualifying}")
