#!/usr/bin/env python3
"""Build X Account Monitor report from scored JSON."""
import json
from datetime import datetime, timezone

today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
with open(f"/home/kiro/trend-engine/trends/x/scan_scored_{today}.json") as f:
    data = json.load(f)

core = data["core"]
filtered = data["filtered"]

def fmt_num(n):
    return f"{n:,}"

def fmt_views(n):
    if n >= 1_000_000:
        return f"{n/1_000_000:.1f}M"
    if n >= 1000:
        return f"{n/1000:.0f}K"
    return str(n)

def snippet(text, n=110):
    t = " ".join((text or "").split())
    return t[:n] + ("..." if len(t) > n else "")

lines = []
lines.append(f"X ACCOUNT MONITOR — {today}")
lines.append("=" * 44)
lines.append(f"Scanned {data['scanned']} accounts | Failed: {len(data['failed'])}")
if data["failed"]:
    lines.append(f"Failures: {', '.join('@'+h for h in data['failed'])}")
lines.append(f"{len(core)} core + {len(filtered)} filtered qualifying tweets | window: last 3 days")
lines.append("")

lines.append("TOP 10 (high engagement, last 3 days)")
lines.append("-" * 44)
for i, e in enumerate(core[:10], 1):
    url = f"https://x.com/{e['handle']}/status/{e['id']}"
    lines.append(f"{i}. @{e['handle']}")
    lines.append(f"   {url}")
    lines.append(f"   Views: {fmt_num(e['views'])} | Likes: {fmt_num(e['likes'])} | RT: {fmt_num(e['rts'])} | Replies: {fmt_num(e['replies'])} | {e['date']}")
    lines.append(f"   {snippet(e['text'])}")
    lines.append("")

if len(core) > 10:
    lines.append(f"(+{len(core)-10} more core tweets below top-10 cutoff)")
    lines.append("")

# Inactive core accounts
active_core = {e["handle"] for e in core}
inactive_core = []
for h in ["runwayml", "CuriousRefuge", "nofilmschool", "venturetwins", "Kling_ai",
          "paultrillo", "c_valenzuelab", "CorridorDigital", "karenxcheng", "higgsfield",
          "pika_labs", "EHuanglu", "azed_ai", "JeffSynthesized", "ai_filmmaker",
          "visiblemaker", "Magiermogul", "WuxiaRocks", "JiamingSuen", "moonvalley",
          "higgsfield_ai", "Chandan_Perla"]:
    if h not in active_core:
        inactive_core.append(h)

if inactive_core:
    lines.append("INACTIVE CORE (no qualifying tweet in window)")
    lines.append("-" * 44)
    lines.append(", ".join("@" + h for h in inactive_core))
    lines.append("")

# Filtered summary
if filtered:
    lines.append("FILTERED (auto-discovered / non-core, not in top 10)")
    lines.append("-" * 44)
    by_handle = {}
    for e in filtered:
        by_handle.setdefault(e["handle"], []).append(e)
    for handle, entries in by_handle.items():
        top = max(entries, key=lambda x: x["views"])
        likes_top = max(entries, key=lambda x: x["likes"])
        lines.append(f"  @{handle}: {len(entries)} qualifying — best {fmt_views(top['views'])} views / {fmt_num(likes_top['likes'])} likes")
        lines.append(f"    https://x.com/{top['handle']}/status/{top['id']}")
        lines.append(f"    {snippet(top['text'], 90)}")
        lines.append("")

lines.append("Summary stats:")
lines.append(f"  scanned={data['scanned']} core_hits={len(core)} filtered_hits={len(filtered)} failed={len(data['failed'])}")

report_path = f"/home/kiro/trend-engine/trends/x/x-account-monitor-{today}.txt"
with open(report_path, "w") as f:
    f.write("\n".join(lines) + "\n")
print(f"Report saved: {report_path}")
print()
print("\n".join(lines))
