#!/usr/bin/env python3
"""X Account Monitor — Report Generator — 2026-06-14"""

import json
from datetime import datetime, timezone

DATE_STR = "2026-06-14"
OUTPUT_FILE = f"/home/kiro/trend-engine/trends/x/account-monitor/{DATE_STR}_account-monitor.txt"

# Load both chunks
accounts = []
errors = []

for chunk in ["chunk1", "chunk2"]:
    path = f"/home/kiro/trend-engine/trends/x/account-monitor/scan_results_{DATE_STR}_{chunk}.json"
    try:
        with open(path) as f:
            data = json.load(f)
        accounts.extend(data.get("accounts", []))
        errors.extend(data.get("errors", []))
    except FileNotFoundError:
        print(f"WARNING: {path} not found")

# Relevance filter — exclude these from Top 10, show in full breakdown with [FILTERED]
IRRELEVANT_HANDLES = {
    "CINEMA505",       # Brazilian cinema account — Portuguese, non-AI filmmaking
    "TheAIColony",     # General AI news aggregator
    "GoogleLabs",      # Large corporate
    "GoogleAI",        # Large corporate
    "Ai_Vaidehi",      # RT aggregator, 0 original posts
    "AI_with_jasmin",  # RT aggregator / job board
    "CharaspowerAI",   # RT-heavy general AI
    "AIBuzzNews",      # General AI news
    "AlexStudio44",    # No qualifying tweets
    "FaithJaiye2187",  # No qualifying tweets
    "KammelaBala",     # No qualifying tweets (dates are May)
    "MyStageAI",       # No qualifying tweets
}

# BIO info for enrichment
BIO_INFO = {
    "runwayml": "Runway AI (~260K)",
    "CuriousRefuge": "Curious Refuge",
    "nofilmschool": "No Film School (~241.7K)",
    "venturetwins": "Justine Moore, a16z (~149.5K)",
    "Kling_ai": "Kling AI (~130K)",
    "paultrillo": "Paul Trillo, director (~15K)",
    "c_valenzuelab": "Cristobal Valenzuela, Runway CEO (~42.7K)",
    "CorridorDigital": "Corridor Digital",
    "karenxcheng": "Karen X. Cheng, director (~58K)",
    "higgsfield": "Higgsfield AI (~63K)",
    "pika_labs": "Pika (~143K)",
    "EHuanglu": "el.cine / Elsa Huang (~128K)",
}

# Build all qualifying tweets from relevant accounts
all_qualifying = []  # for Top 10
filtered_qualifying = []  # for filtered accounts

# Per-account breakdown
account_maps = {}  # handle -> list of qualifying tweets

for acc in accounts:
    handle = acc["handle"]
    tweets = acc.get("tweets", [])
    
    if not tweets:
        continue
    
    # Filter out RTs (RT aggregator accounts)
    non_rt_tweets = [t for t in tweets if not t.get("is_rt", False)]
    effective = non_rt_tweets if non_rt_tweets else tweets  # fall back to all if only RTs
    
    if handle in IRRELEVANT_HANDLES:
        filtered_qualifying.extend(effective)
    else:
        all_qualifying.extend(effective)
    
    account_maps[handle] = effective

# Sort all qualifying by score
all_qualifying.sort(key=lambda x: x["score"], reverse=True)
filtered_qualifying.sort(key=lambda x: x["score"], reverse=True)

# Top 10 from relevant accounts only
top10 = all_qualifying[:10]

# 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):
    num = i + 1
    handle = t.get("author", "?")
    text = t["text"].replace("\n", " ").strip()
    # Truncate text to ~100 chars for readability
    snippet = text[:120]
    if len(text) > 120:
        snippet += "..."
    tweet_id = t["id"]
    url = f"https://x.com/{handle}/status/{tweet_id}"
    views = t["views"]
    date = t["date"]
    lines.append(f"{num}, @{handle}, {snippet} ({url}), {views}, {date}")

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

# Sort accounts: most qualifying tweets first, then by max score
def account_sort_key(handle):
    tweets = account_maps.get(handle, [])
    if not tweets:
        return (0, 0)
    return (len(tweets), max(t["score"] for t in tweets))

sorted_handles = sorted(account_maps.keys(), key=account_sort_key, reverse=True)

total_scans = len(accounts)
accounts_with_content = sum(1 for h in sorted_handles if account_maps.get(h))
total_qualifying = len(all_qualifying) + len(filtered_qualifying)
error_count = len([a for a in accounts if a.get("error")])

for handle in sorted_handles:
    tweets = account_maps.get(handle, [])
    if not tweets:
        continue
    
    is_filtered = handle in IRRELEVANT_HANDLES
    bio = BIO_INFO.get(handle, "")
    tag = " [FILTERED — excluded from Top 10]" if is_filtered else ""
    bio_str = f" — {bio}" if bio else ""
    
    lines.append(f"")
    lines.append(f"@{handle}{bio_str}{tag}")
    lines.append(f"  {len(tweets)} qualifying tweets (last 3 days)")
    
    for t_idx, t in enumerate(tweets):
        text = t["text"].replace("\n", " ").strip()
        snippet = text[:150]
        if len(text) > 150:
            snippet += "..."
        tweet_id = t["id"]
        url = f"https://x.com/{handle}/status/{tweet_id}"
        likes = t["likes"]
        rts = t["retweets"]
        replies = t["replies"]
        views = t["views"]
        score = t["score"]
        date = t["date"]
        lines.append(f"  [{score}pts] L:{likes} RT:{rts} R:{replies} V:{views} — {date}")
        lines.append(f"    {snippet}")
        lines.append(f"    {url}")

lines.append("")
lines.append("---")
lines.append(f"Summary: {total_scans} scans total, {accounts_with_content} accounts with content, {total_qualifying} qualifying tweets found. {error_count} API failures.")

report = "\n".join(lines)

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

print(report)
print(f"\n\nSaved to {OUTPUT_FILE}")
