import json

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

IRRELEVANT_HANDLES = {
    "ChrisLaubAI": "RT-only finance/news aggregator, zero AI filmmaking",
    "CINEMA505": "Brazilian cinema account, non-AI posts",
    "TheAIColony": "General AI news aggregator",
    "GoogleLabs": "Large corporate account",
    "GoogleAI": "Large corporate account",
    "Ai_Vaidehi": "RT aggregator, no original content",
    "AITOPIAai": "AI news/tools, not filmmaking",
    "AIBuzzNews": "AI news aggregator",
    "AIFrontliner": "AI news aggregator (ChatGPT/Claude prompts)",
    "AITECHio": "AI/crypto hybrid",
    "FaithJaiye2187": "Low/no qualifying tweets consistently",
    "KammelaBala": "Low/no qualifying tweets consistently",
    "MyStageAI": "Low/no qualifying tweets consistently",
    "AlexStudio44": "Low/no qualifying tweets consistently",
    "AI_with_jasmin": "RT-heavy, job boards, generic AI tools",
    "AIGuideHQ": "General AI tips/guides, not filmmaking",
    "4aibsc": "Unknown/unverified niche"
}

merged_path = f"/home/kiro/trend-engine/trends/x/account-monitor/scan_results_{DATE_STR}.json"
with open(merged_path) as f:
    merged = json.load(f)

all_accounts = {acc["handle"]: acc for acc in merged["accounts"]}
errors = merged.get("errors", [])

# Collect all qualifying tweets
all_tweets = []
for handle, acc in all_accounts.items():
    for t in acc.get("tweets", []):
        all_tweets.append({
            "handle": handle,
            "score": t["score"],
            "text": t["text"],
            "url": t["url"],
            "date": t["date"],
            "likeCount": t["likeCount"],
            "retweetCount": t["retweetCount"],
            "replyCount": t["replyCount"],
            "viewCount": t["viewCount"],
            "is_retweet": t.get("is_retweet", False),
            "author_userName": t.get("author_userName", handle)
        })

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

# Dedup by account: pick best tweet per account, then fill to 10
seen_handles = set()
deduped_top10 = []
for t in all_tweets:
    if t["handle"] not in IRRELEVANT_HANDLES and t["handle"] not in seen_handles:
        seen_handles.add(t["handle"])
        deduped_top10.append(t)
    if len(deduped_top10) >= 10:
        break

lines = []
lines.append(f"Title: X Account Monitor -- {DATE_STR}")
lines.append("")
lines.append("Top 10 by Engagement Score (AI Filmmaking Relevant)")
lines.append("")
lines.append("#, Account, Best Tweet, Views, Date")
for rank, t in enumerate(deduped_top10, 1):
    text = t["text"].replace("\n", " ").strip()
    if len(text) > 80:
        text = text[:77] + "..."
    views = t["viewCount"]
    date = t["date"]
    url = t["url"]
    lines.append(f"{rank}, @{t['author_userName']}, {text} ({url}), {views}, {date}")

lines.append("")

# --- Full Per-Account Breakdown ---
lines.append("Full Account Breakdown")
lines.append("")

for handle in sorted(all_accounts.keys()):
    acc = all_accounts[handle]
    rc = acc["recent_count"]
    qc = acc["qualifying_count"]

    marker = ""
    if handle in IRRELEVANT_HANDLES:
        marker = " [FILTERED]"

    lines.append(f"@{handle}{marker}: {rc} recent tweets, {qc} qualifying")

    if qc > 0 and acc.get("tweets"):
        for t in sorted(acc["tweets"], key=lambda x: x["score"], reverse=True):
            rt = " [RT]" if t.get("is_retweet") else ""
            likes = t["likeCount"]
            retweets = t["retweetCount"]
            views = t["viewCount"]
            date = t["date"]
            text = t["text"].replace("\n", " ").strip()
            if len(text) > 100:
                text = text[:97] + "..."
            lines.append(f"  {date} | L:{likes} RT:{retweets} V:{views}{rt} | {text} ({t['url']})")
    lines.append("")

# --- Summary ---
total_accounts = len(all_accounts)
with_content = sum(1 for a in all_accounts.values() if a["qualifying_count"] > 0)
total_qualifying = sum(len(a.get("tweets", [])) for a in all_accounts.values())
error_count = len(errors)

lines.append("---")
lines.append(f"Summary: {total_accounts} accounts scanned, {with_content} with qualifying content, {total_qualifying} qualifying tweets found. {error_count} API errors.")
lines.append(f"Irrelevant/filtered accounts removed from top 10: {len(IRRELEVANT_HANDLES)}")

report = "\n".join(lines)

with open(OUTPUT_FILE, "w") as f:
    f.write(report)

print(f"Report saved to {OUTPUT_FILE}")
print(report)
