#!/usr/bin/env python3
"""Dormancy + bucket breakdown for x-account-monitor, one date.

Reads scan_results_<date>_FULL.json and prints:
 - qualifying tweet count and score-based buckets
 - per zero-qualifying handle: newest ORIGINAL tweet date, days old, in/out of window
 - distinguishes genuine threshold artefacts (in-window originals) from dormancy/RT artefacts
"""
import json, sys, os
from datetime import datetime, timezone, timedelta

DATE = sys.argv[1]
BASE = "/home/kiro/trend-engine/trends/x/raw"
d = json.load(open(f"{BASE}/scan_results_{DATE}_FULL.json"))

CORE = set("""higgsfield higgsfield_ai EHuanglu venturetwins AIWarper c_valenzuelab runwayml
Kling_ai CharaspowerAI karenxcheng pika_labs azed_ai ayesha_ai Flovaai AI__TSUBAKI WuxiaRocks
CuriousRefuge paultrillo JeffSynthesized ai_filmmaker Magiermogul JiamingSuen Chandan_Perla
nofilmschool""".split())
IRRELEVANT = set("""AIBuzzNews AIGuideHQ AITECHio AIFrontliner TheAIColony AITOPIAai AISuperDomain
GoogleLabs GoogleAI DonutAI cladlabs FaithJaiye2187 KammelaBala MyStageAI AlexStudio44
AI_with_jasmin Ai_Vaidehi ChrisLaubAI OpenAI AnthropicAI CINEMA505 AIScottAdams AI_Jasonyu AIByLeo
TheAIColony""".split())
FILM_INDUSTRY = {"DiscussingFilm", "nofilmschool"}

handles = d["handles"]
raw = d["raw"]
qual = d["qualifying"]
print(f"DATE {DATE}  qualifying={len(qual)}  handles={len(handles)}  failures={len(d['failures'])}")

def bucket(h):
    if h in IRRELEVANT: return "irrelevant"
    if h in FILM_INDUSTRY: return "film-industry"
    return "core"

cnt = {"core": 0, "film-industry": 0, "irrelevant": 0}
for t in qual:
    cnt[bucket(t.get("userName") or t.get("handle") or "")] += 1
print("bucket totals:", cnt)

cutoff = datetime.now(timezone.utc) - timedelta(days=3)
cutoff_date = (datetime.now(timezone.utc).date() - timedelta(days=3))
print(f"cutoff (3d window start) ~ {cutoff_date}")

qhandles = set()
for t in qual:
    qhandles.add(t.get("userName") or t.get("handle") or "")

print("\n=== ZERO-QUALIFYING HANDLE ANALYSIS ===")
for h in sorted(handles):
    if h in qhandles:
        continue
    tw = raw.get(h, [])
    if not tw:
        print(f"{h:22s} tier={bucket(h):13s} NO TWEETS FETCHED")
        continue
    def parse(t):
        c = t.get("createdAt")
        if not c: return None
        try: return datetime.strptime(c, "%a %b %d %H:%M:%S %z %Y")
        except Exception: return None
    dated = [(parse(t), t) for t in tw]
    dated = [(dt, t) for dt, t in dated if dt]
    if not dated:
        print(f"{h:22s} tier={bucket(h):13s} unparseable dates"); continue
    newest_dt, newest_t = max(dated, key=lambda x: x[0])
    days = (datetime.now(timezone.utc) - newest_dt).days
    # originals only
    origs = [(dt, t) for dt, t in dated
             if t.get("retweeted_tweet") is None and not (t.get("text") or "").startswith("RT @")]
    in_win_origs = [(dt, t) for dt, t in origs if dt >= cutoff]
    newest_orig = max(origs, key=lambda x: x[0])[0] if origs else None
    verdict = "OUT-of-window (boundary/dormant)" if newest_dt < cutoff else "IN-WINDOW"
    if in_win_origs:
        top = max(in_win_origs, key=lambda x: (x[1].get("likeCount") or 0) + (x[1].get("viewCount") or 0)/100)
        verdict = (f"*** GENUINE THRESHOLD ARTEFACT: {len(in_win_origs)} in-window originals, "
                   f"best {top[1].get('likeCount')}L/{top[1].get('viewCount')}V")
    elif newest_dt >= cutoff:
        verdict = "IN-WINDOW but RT-only -> RT artefact, not reach problem"
    print(f"{h:22s} tier={bucket(h):13s} newest={newest_dt.strftime('%Y-%m-%d')} ({days}d) "
          f"newest_orig={newest_orig.strftime('%Y-%m-%d') if newest_orig else 'none'} :: {verdict}")
