#!/usr/bin/env python3
"""Generate filtered plain-text account monitor report - excluding irrelevant accounts from top 10."""

import json
import os
from collections import OrderedDict

SCAN_FILE = "/home/kiro/trend-engine/trends/x/account-monitor/scan_results_2026-06-10.json"
OUTPUT_DIR = "/home/kiro/trend-engine/trends/x/account-monitor"
DATE_STR = "2026-06-10"
OUTPUT_FILE = os.path.join(OUTPUT_DIR, f"{DATE_STR}_account-monitor.txt")

with open(SCAN_FILE) as f:
    data = json.loads(f.read(), strict=False)

accounts = data.get("accounts", [])
errors = data.get("errors", [])

CUTOFF = "2026-06-07"

# Auto-discovered accounts that are NOT AI filmmaking relevant (per skill docs)
IRRELEVANT_HANDLES = {
    "CINEMA505",    # Brazilian cinema account
    "TheAIColony",  # General AI news aggregator, not filmmaking
    "GoogleLabs",   # Large corporate
    "GoogleAI",     # Large corporate
    "AlexStudio44", # Not AI filmmaking
    "FaithJaiye2187", "KammelaBala", "MyStageAI",  # Consistently low/no qualifying tweets
    "Ai_Vaidehi",   # Mostly RTs of general AI news
    "AI_with_jasmin", # Mostly RTs of general AI/job content
    "CharaspowerAI", # Mostly RTs of general AI content
    "AIBuzzNews",   # General AI news
}

def score_tweet(t):
    likes = t.get("likeCount", 0) or 0
    retweets = t.get("retweetCount", 0) or 0
    replies = t.get("replyCount", 0) or 0
    views = t.get("viewCount", 0) or 0
    return likes + (retweets * 2) + replies + (views // 100)

def passes_threshold(t):
    likes = t.get("likeCount", 0) or 0
    retweets = t.get("retweetCount", 0) or 0
    views = t.get("viewCount", 0) or 0
    return likes >= 50 or retweets >= 10 or views >= 1000

def is_retweet(text):
    return text and text.startswith("RT @")

def truncate(text, max_len=80):
    if not text:
        return ""
    text = text.replace("\n", " ").replace("\r", " ")
    if len(text) > max_len:
        return text[:max_len-3] + "..."
    return text

# Collect all qualifying tweets
all_qualifying = []
for acc in accounts:
    handle = acc["handle"]
    for t in acc.get("tweets", []):
        tweet_date = t.get("date", "")
        if tweet_date < CUTOFF:
            continue
        if not passes_threshold(t):
            continue
        text = t.get("text", "")
        tweet_id = t.get("id", "")
        url = f"https://x.com/{handle}/status/{tweet_id}"
        s = score_tweet(t)
        all_qualifying.append({
            "handle": handle,
            "text": text,
            "date": tweet_date,
            "score": s,
            "likes": t.get("likeCount", 0) or 0,
            "retweets": t.get("retweetCount", 0) or 0,
            "replies": t.get("replyCount", 0) or 0,
            "views": t.get("viewCount", 0) or 0,
            "url": url,
            "is_retweet": is_retweet(text),
        })

all_qualifying.sort(key=lambda x: x["score"], reverse=True)

# Filter for top 10: exclude irrelevant accounts
relevant_qualifying = [t for t in all_qualifying if t["handle"] not in IRRELEVANT_HANDLES]

accounts_with_content = set(t["handle"] for t in all_qualifying)
relevant_accounts_with_content = set(t["handle"] for t in relevant_qualifying)

lines = []
lines.append(f"Title: X Account Monitor -- {DATE_STR}")
lines.append("")
lines.append(f"Top 10 by Engagement Score (AI Filmmaking Relevant)")
lines.append("")
lines.append("#, Account, Best Tweet, Views, Date")

top10 = relevant_qualifying[:10]
for i, t in enumerate(top10, 1):
    snippet = truncate(t["text"], 70)
    rt_marker = " [RT]" if t["is_retweet"] else ""
    views_str = f"{t['views']:,}" if t["views"] > 0 else "0"
    lines.append(f"{i}, @{t['handle']}, {snippet}{rt_marker} ({t['url']}), {views_str}, {t['date']}")

lines.append("")

# Full breakdown - include ALL accounts
lines.append("---")
lines.append(f"Full Breakdown ({len(all_qualifying)} qualifying tweets from {len(accounts_with_content)} accounts)")
lines.append("")

by_handle = OrderedDict()
for t in all_qualifying:
    h = t["handle"]
    if h not in by_handle:
        by_handle[h] = []
    by_handle[h].append(t)

for handle, tweets in by_handle.items():
    best = tweets[0]
    relevance_note = " [FILTERED]" if handle in IRRELEVANT_HANDLES else ""
    lines.append(f"@{handle}{relevance_note}: {len(tweets)} qualifying tweets (best: {best['likes']}L / {best['retweets']}RT / {best['views']}V)")
    for t in tweets[:3]:
        snippet = truncate(t["text"], 60)
        rt = " [RT]" if t["is_retweet"] else ""
        lines.append(f"  - {snippet}{rt} ({t['url']}) [{t['likes']}L/{t['retweets']}RT/{t['views']}V] {t['date']}")
    lines.append("")

# Accounts with recent but no qualifying
accounts_no_qualifying = []
for acc in accounts:
    handle = acc["handle"]
    if handle in accounts_with_content:
        continue
    recent_count = len([t for t in acc.get("tweets", []) if t.get("date", "") >= CUTOFF])
    if recent_count > 0:
        accounts_no_qualifying.append(f"@{handle} ({recent_count} recent tweets, none qualifying)")

if accounts_no_qualifying:
    lines.append("Accounts with Recent Activity but No Qualifying Tweets:")
    for a in accounts_no_qualifying:
        lines.append(f"  {a}")
    lines.append("")

# Summary
lines.append("---")
lines.append(f"Summary: 44 scans total, {len(relevant_accounts_with_content)} relevant accounts with qualifying content, {len(relevant_qualifying)} qualifying tweets from relevant accounts. {len(errors)} API failures.")
lines.append("")
lines.append(f"Note: {len(IRRELEVANT_HANDLES)} accounts filtered from top 10 as non-AI-filmmaking (general news, RT aggregators, non-English cinema).")
lines.append(f"Filtered accounts that had high-volume tweets: TheAIColony (5.7M views on iOS 27 post), CINEMA505 (5 tweets in top 10, Brazilian cinema).")

output = "\n".join(lines)
with open(OUTPUT_FILE, "w") as f:
    f.write(output)

print(output)
print(f"\n\nReport saved to: {OUTPUT_FILE}")
