#!/usr/bin/env python3
"""X Account Monitor - Report Generator for 2026-06-13"""
import json, os

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

with open(RESULTS_FILE) as f:
    data = json.load(f)

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

# Build flat list of all qualifying tweets
all_tweets = []
for acc in accounts:
    for t in acc.get("tweets", []):
        tweet_id = t.get("id", "")
        handle = acc["handle"]
        url = f"https://x.com/{handle}/status/{tweet_id}" if tweet_id else ""
        all_tweets.append({
            "handle": handle,
            "filtered": acc.get("filtered", False),
            "bio": acc.get("bio", ""),
            "id": tweet_id,
            "text": t.get("text", ""),
            "date": t.get("date", ""),
            "likes": t.get("likes", 0),
            "retweets": t.get("retweets", 0),
            "replies": t.get("replies", 0),
            "views": t.get("views", 0),
            "score": t.get("score", 0),
            "url": url,
        })

# Separate filtered and unfiltered
unfiltered = [t for t in all_tweets if not t["filtered"]]
filtered = [t for t in all_tweets if t["filtered"]]

# Sort by score
unfiltered.sort(key=lambda x: x["score"], reverse=True)
filtered.sort(key=lambda x: x["score"], reverse=True)

# Top 10 from unfiltered
top10 = unfiltered[:10]

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

def fmt_score(t):
    return f"{t['score']:.0f}"

def fmt_views(t):
    v = t["views"]
    if v >= 1000000:
        return f"{v/1000000:.1f}M"
    elif v >= 1000:
        return f"{v/1000:.0f}K"
    return str(v)

lines = []
lines.append(f"Title: X Account Monitor -- 2026-06-13")
lines.append("")
lines.append("Top 10 by Engagement Score")
lines.append("")
lines.append("#, Account, Best Tweet, Views, Date, Score")

for i, t in enumerate(top10):
    snippet = truncate(t["text"], 75)
    entry = f"{i+1}, @{t['handle']}, {snippet} ({t['url']}), {fmt_views(t)}, {t['date']}, {fmt_score(t)}"
    lines.append(entry)

# Full breakdown by account
lines.append("")
lines.append("=" * 60)
lines.append("FULL ACCOUNT BREAKDOWN")
lines.append("=" * 60)

# Sort accounts by total qualifying tweets and max score
account_summaries = []
for acc in accounts:
    q_tweets = []
    for t in acc.get("tweets", []):
        tweet_id = t.get("id", "")
        url = f"https://x.com/{acc['handle']}/status/{tweet_id}" if tweet_id else ""
        q_tweets.append({
            "text": t.get("text", ""),
            "date": t.get("date", ""),
            "likes": t.get("likes", 0),
            "retweets": t.get("retweets", 0),
            "views": t.get("views", 0),
            "score": t.get("score", 0),
            "url": url,
        })
    max_score = max((t["score"] for t in q_tweets), default=0)
    account_summaries.append({
        "handle": acc["handle"],
        "bio": acc.get("bio", ""),
        "filtered": acc.get("filtered", False),
        "total_fetched": acc.get("total_fetched", 0),
        "recent_count": acc.get("recent_count", 0),
        "qualifying_count": acc.get("qualifying_count", 0),
        "tweets": q_tweets,
        "max_score": max_score,
    })

# Sort: unfiltered first by max_score, then filtered
account_summaries.sort(key=lambda x: (x["filtered"], -x["max_score"]))

for acc_sum in account_summaries:
    tag = " [FILTERED]" if acc_sum["filtered"] else ""
    lines.append(f"\n@{acc_sum['handle']}{tag}")
    if acc_sum["bio"]:
        lines.append(f"  Bio: {acc_sum['bio']}")
    lines.append(f"  Fetched: {acc_sum['total_fetched']}, Recent (3d): {acc_sum['recent_count']}, Qualifying: {acc_sum['qualifying_count']}")
    
    if acc_sum["tweets"]:
        for t in acc_sum["tweets"]:
            snippet = truncate(t["text"], 78)
            lines.append(f"    {t['date']} | L:{t['likes']} RT:{t['retweets']} V:{fmt_views(t)} | S:{fmt_score(t)} | {snippet}")
            if t["url"]:
                lines.append(f"    URL: {t['url']}")
    else:
        lines.append("    (no qualifying tweets)")

# Summary
lines.append("")
lines.append("=" * 60)
lines.append("SUMMARY")
lines.append(f"Total accounts scanned: {len(accounts)}")
lines.append(f"API errors: {len(errors)}")
lines.append(f"Accounts with qualifying tweets: {sum(1 for a in accounts if a['qualifying_count'] > 0)}")
lines.append(f"Total qualifying tweets: {sum(a['qualifying_count'] for a in accounts)}")
lines.append(f"Top 10 (unfiltered): {len(top10)} tweets from {len(set(t['handle'] for t in top10))} accounts")
lines.append(f"Filtered accounts excluded from Top 10: {sum(1 for a in accounts if a.get('filtered'))}")
lines.append(f"Scan completed: 2026-06-13 06:00 UTC")

if errors:
    lines.append(f"\nAPI Errors:")
    for e in errors:
        lines.append(f"  @{e['handle']}: {e['error']}")

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

print(output)
print(f"\n--- Report saved to {OUTPUT_FILE} ---")
