#!/usr/bin/env python3
"""Generate plain-text report from scan results JSON"""

import json
from datetime import datetime, timezone

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

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)",
}

def load_results():
    with open(SCAN_FILE) as f:
        return json.load(f)

def truncate_text(text, max_len=100):
    if not text:
        return ""
    # Remove newlines
    text = text.replace("\n", " ").replace("\r", " ").strip()
    if len(text) > max_len:
        return text[:max_len-3] + "..."
    return text

def main():
    data = load_results()
    accounts = data["accounts"]
    errors = data["errors"]
    scan_date = "2026-06-09"
    
    # Collect all qualifying tweets
    all_qualifying = []
    
    for acc in accounts:
        handle = acc["handle"]
        bio = BIO_INFO.get(handle, "")
        
        for tweet in acc["tweets"]:
            if not tweet.get("is_recent", False):
                continue
            
            like = tweet.get("like_count", 0)
            rt = tweet.get("retweet_count", 0)
            reply = tweet.get("reply_count", 0)
            views = tweet.get("view_count", 0)
            
            # Check qualifying thresholds
            qualifies = (like >= 50 or rt >= 10 or views >= 1000)
            if not qualifies:
                continue
            
            score = like + (rt * 2) + reply + (views / 100)
            
            # Filter out retweet-only accounts (RTs with 0 likes/0 views)
            is_rt = tweet.get("is_rt", False)
            
            all_qualifying.append({
                "handle": handle,
                "tweet_id": tweet.get("id", ""),
                "text": tweet.get("text", ""),
                "text_short": truncate_text(tweet.get("full_text", tweet.get("text", "")), 80),
                "date": tweet.get("date", ""),
                "like": like,
                "rt": rt,
                "reply": reply,
                "views": views,
                "score": score,
                "url": tweet.get("url", ""),
                "is_rt": is_rt,
                "author_handle": tweet.get("author_handle", handle),
                "followers": tweet.get("followers", 0),
            })
    
    # Sort by score descending
    all_qualifying.sort(key=lambda x: x["score"], reverse=True)
    
    # Build report
    lines = []
    lines.append(f"Title: X Account Monitor -- {scan_date}")
    lines.append("")
    
    # Top 10 table
    lines.append("Top 10 by Engagement Score")
    lines.append("")
    lines.append("#, Account, Best Tweet, Views, Date")
    
    for i, t in enumerate(all_qualifying[:10], 1):
        snippet = truncate_text(t["text"], 70)
        views_str = str(t["views"]) if t["views"] else "0"
        lines.append(f"{i}, @{t['handle']}, {snippet} ({t['url']}), {views_str}, {t['date']}")
    
    lines.append("")
    lines.append("---")
    lines.append("")
    
    # Detailed per-account breakdown
    lines.append("Detailed Breakdown (All Accounts with Qualifying Tweets)")
    lines.append("")
    
    # Group by handle
    from collections import OrderedDict
    grouped = OrderedDict()
    for t in all_qualifying:
        if t["handle"] not in grouped:
            grouped[t["handle"]] = []
        grouped[t["handle"]].append(t)
    
    total_tweets_found = 0
    accounts_with_content = 0
    
    for handle, tweets in grouped.items():
        bio = BIO_INFO.get(handle, "")
        bio_str = f" ({bio})" if bio else ""
        # Get follower count from the first tweet
        followers = tweets[0].get("followers", 0)
        follower_str = f" [{followers:,} followers]" if followers else ""
        
        lines.append(f"@{handle}{bio_str}{follower_str}")
        
        # Sort by score descending
        tweets_sorted = sorted(tweets, key=lambda x: x["score"], reverse=True)
        
        for t in tweets_sorted:
            snippet = truncate_text(t["text"], 120)
            rt_tag = " [RT]" if t["is_rt"] else ""
            lines.append(f"  {t['like']}L {t['rt']}RT {t['reply']}Rep {t['views']}V | {t['date']} | {snippet}{rt_tag}")
            lines.append(f"  {t['url']}")
        
        total_tweets_found += len(tweets)
        accounts_with_content += 1
        lines.append("")
    
    # Summary
    lines.append("---")
    lines.append("")
    lines.append(f"Summary: {len(accounts)} scans total, {accounts_with_content} accounts with content, {total_tweets_found} qualifying tweets found. {len(errors)} API failures.")
    
    # Notes
    lines.append("")
    
    # Identify notable replying/engagement opportunities
    high_original = [t for t in all_qualifying if not t["is_rt"] and t["like"] >= 50 and t["views"] >= 1000]
    if high_original:
        lines.append("Notable reply opportunities (high engagement, original content):")
        for t in high_original[:5]:
            snippet = truncate_text(t["text"], 80)
            lines.append(f"  @{t['handle']}: {snippet} ({t['url']})")
    
    output = "\n".join(lines)
    
    with open(OUTPUT_FILE, "w") as f:
        f.write(output)
    
    print(f"Report saved to: {OUTPUT_FILE}")
    print(output)

if __name__ == "__main__":
    main()
