#!/usr/bin/env python3
"""Build the plain-text X account monitor report for a given date from the
saved scan JSON. Mirrors the established report_<date>.txt format:
TOP 10 (core AI-filmmaking), FILTERED, FILM INDUSTRY, AI LABS, SCAN HEALTH."""
import json, sys, re
from collections import Counter

date = sys.argv[1] if len(sys.argv) > 1 else "2026-09-30"
base = "/home/kiro/trend-engine/trends/x/raw"
d = json.load(open(f"{base}/scan_results_{date}_FULL.json"))
q = d["qualifying"]

AI_TERMS = re.compile(r"\b(ai\b|a\.i\.|seedance|kling|runway|veo|sora|minimax|hailuo|higgsfield|"
                      r"midjourney|nano ?banana|gpt-?[0-9.]*|chatgpt|gemini|prompt|generative|"
                      r"render|vfx|ai film|aifilm|grokbot|motion capture|deepfake|davinci|"
                      r"blender|autocad|storyboard|animation|diffusion|comfyui)", re.I)

FILM_INDUSTRY = {"DiscussingFilm", "nofilmschool"}
AI_NEWS = {"OpenAI", "AnthropicAI"}
IRRELEVANT = {"AIBuzzNews", "AIGuideHQ", "AITECHio", "AIFrontliner", "TheAIColony",
              "AITOPIAai", "GoogleLabs", "GoogleAI", "DonutAI", "cladlabs",
              "FaithJaiye2187", "KammelaBala", "MyStageAI", "AlexStudio44",
              "AI_with_jasmin", "Ai_Vaidehi", "ChrisLaubAI", "CINEMA505", "AIScottAdams"}

core = [x for x in q if x["handle"] not in FILM_INDUSTRY
        and x["handle"] not in AI_NEWS and x["handle"] not in IRRELEVANT]
film = [x for x in q if x["handle"] in FILM_INDUSTRY and AI_TERMS.search(x["text"])]
filt = [x for x in q if x["handle"] in IRRELEVANT and AI_TERMS.search(x["text"])]
labs = [x for x in q if x["handle"] in AI_NEWS]

for lst in (core, film, filt, labs):
    lst.sort(key=lambda x: x["score"], reverse=True)

out = []
out.append("X ACCOUNT MONITOR -- DAILY REPORT")
out.append(f"Date: {date} | Window: last 3 days | {len(d['handles'])} accounts scanned")
out.append("=" * 60)
out.append("")
out.append("TOP 10 -- AI FILMMAKING CORE")
out.append("-" * 60)
for i, x in enumerate(core[:10], 1):
    out.append(f"{i}. @{x['handle']}  [{x['date']}]")
    out.append(f"   {x['text'][:300]}")
    out.append(f"   Views: {x['views']:,} | Likes: {x['likes']:,} | RT: {x['rt']} | "
               f"Replies: {x['replies']} | Score: {x['score']:.0f}")
    out.append(f"   {x['url']}")
    out.append("")

out.append("FILM INDUSTRY (AI-relevant only)")
out.append("-" * 60)
if not film:
    out.append("(empty -- correct output, do not recover these posts)")
else:
    for x in film:
        out.append(f"• @{x['handle']} | {x['views']:,}V / {x['likes']}L | {x['date']}")
        out.append(f"  {x['text'][:220]}")
        out.append(f"  {x['url']}")
out.append("")

out.append("FILTERED (non-core / auto-discovered, AI-term matches)")
out.append("-" * 60)
for x in filt[:8]:
    out.append(f"• @{x['handle']} | {x['views']:,}V / {x['likes']:,}L | {x['date']}")
    out.append(f"  {x['text'][:220]}")
    out.append(f"  {x['url']}")
out.append("")

out.append("AI LABS (non-production -- never in top 10)")
out.append("-" * 60)
for x in labs[:5]:
    out.append(f"• @{x['handle']} | {x['views']:,}V / {x['likes']:,}L | {x['date']}")
    out.append(f"  {x['text'][:180]}")
    out.append(f"  {x['url']}")
out.append("")

c = Counter(x["handle"] for x in q)
zero = [h for h in d["handles"] if h not in c]
out.append("SCAN HEALTH")
out.append("-" * 60)
out.append(f"Accounts scanned: {len(d['handles'])} | Failures: {len(d['failures'])} | "
           f"Qualifying tweets: {len(q)} (core {len(core)} / film {len([x for x in q if x['handle'] in FILM_INDUSTRY])} "
           f"/ filtered {len(q) - len(core) - len([x for x in q if x['handle'] in FILM_INDUSTRY])})")
out.append(f"Handles with >= 1 qualifying post: {len(c)} of {len(d['handles'])}")
out.append(f"Film-industry / link-farm tier: " +
           ", ".join(f"@{h}({n})" for h, n in c.most_common() if h in FILM_INDUSTRY))
out.append(f"Zero-qualifying handles ({len(zero)}): " + ", ".join("@" + h for h in sorted(zero)))
if d["failures"]:
    out.append("SCAN FAILURES: " + ", ".join("@" + h for h, _ in d["failures"]))
out.append("")
out.append(f"Full JSON: {base}/scan_results_{date}_FULL.json")

txt = "\n".join(out)
open(f"{base}/report_{date}.txt", "w").write(txt + "\n")
print(txt)
