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

import json
import os
from datetime import datetime, timezone

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", [])

# Date cutoff: last 3 days from June 10, 2026
CUTOFF = "2026-06-07"

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 ""
    # Remove newlines
    text = text.replace("\n", " ").replace("\r", " ")
    if len(text) > max_len:
        return text[:max_len-3] + "..."
    return text

# Collect all qualifying tweets (recent + pass thresholds + non-RT)
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
        # Prefer original tweets over RTs for scoring, but keep RTs as fallback
        text = t.get("text", "")
        if is_retweet(text):
            # Still include but mark it
            pass
        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),
        })

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

# Count accounts with qualifying tweets
accounts_with_content = set()
for t in all_qualifying:
    accounts_with_content.add(t["handle"])

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

top10 = all_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("")

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

# Group by handle
from collections import OrderedDict
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():
    # Find best tweet score for this account
    best = tweets[0]
    lines.append(f"@{handle}: {len(tweets)} qualifying tweets (best: {best['likes']}L / {best['retweets']}RT / {best['views']}V)")
    for t in tweets[:3]:  # Show up to 3 per account
        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("")
lines.append("---")

# Accounts with recent tweets but no qualifying ones
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:
        total = acc.get("tweet_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("---")
total_scanned = len(accounts)
lines.append(f"Summary: {total_scanned} scans total, {len(accounts_with_content)} accounts with qualifying content, {len(all_qualifying)} qualifying tweets found. {len(errors)} API failures.")

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

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