#!/usr/bin/env python3
"""Dormancy check for a given scan date.

For every zero-qualifying handle, report the newest FETCHED tweet and whether it
falls inside the 3-day window. A handle whose newest fetched tweet is OLDER than
the window is DORMANT (threshold changes cannot help). A handle posting INSIDE
the window with 0 qualifying is a genuine threshold artefact -- but ONLY if its
in-window tweets are ORIGINALS (the runner drops retweets, so a 1-day-old RT
reads as an in-window post in the raw store).

Usage: xmon_dormancy_2026-10-10.py [YYYY-MM-DD]
"""
import json, sys
from datetime import datetime, timezone, timedelta

date = sys.argv[1] if len(sys.argv) > 1 else datetime.now(timezone.utc).strftime("%Y-%m-%d")
path = f"/home/kiro/trend-engine/trends/x/raw/scan_results_{date}_FULL.json"
d = json.load(open(path))

now = datetime.now(timezone.utc)
cutoff = now.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=3)

def pdate(s):
    try:
        return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")
    except Exception:
        return None

def is_original(t):
    if t.get("retweeted_tweet") or t.get("type") == "retweet":
        return False
    if (t.get("text") or "").startswith("RT @"):
        return False
    return True

qual_handles = {x["handle"] for x in d["qualifying"]}
print(f"DATE {date} | cutoff {cutoff.isoformat()} | now {now.isoformat()}")
print(f"handles scanned: {len(d['handles'])} | qualifying handles: {len(qual_handles)}")
print(f"failures: {len(d.get('failures') or [])}")

zero = [h for h in d["handles"] if h not in qual_handles]
print(f"\nzero-qualifying handles ({len(zero)}): {', '.join('@'+h for h in zero)}\n")

for h in zero:
    tw = d["raw"].get(h) or []
    dated = [(pdate(t.get("createdAt", "")), t) for t in tw]
    dated = [(dt, t) for dt, t in dated if dt]
    if not dated:
        print(f"@{h}: NO FETCHED TWEETS (payload empty)")
        continue
    dated.sort(key=lambda x: x[0], reverse=True)
    newest_dt, newest_t = dated[0]
    age_days = (now - newest_dt).days
    in_win = [t for dt, t in dated if dt >= cutoff]
    originals = [t for t in in_win if is_original(t)]
    if not in_win:
        verdict = "DORMANT (newest fetched outside window)"
    elif not originals:
        verdict = "RT-ONLY in window (runner drops RTs -> nothing scoreable)"
    else:
        verdict = f"IN-WINDOW, {len(originals)} original(s) 0 qualifying -> GENUINE THRESHOLD ARTEFACT"
    print(f"@{h}: newest {newest_dt.strftime('%Y-%m-%d')} ({age_days}d) | in-window {len(in_win)} | verdict: {verdict}")
    for t in originals[:3]:
        dt = pdate(t["createdAt"])
        print(f"    orig {dt.strftime('%Y-%m-%d')} {t.get('likeCount') or 0}L "
              f"{t.get('retweetCount') or 0}RT {t.get('viewCount') or 0}V :: "
              f"{(t.get('text') or '')[:110].replace(chr(10),' ')}")
    for t in in_win[:3]:
        if is_original(t):
            continue
        dt = pdate(t["createdAt"])
        print(f"    RT   {dt.strftime('%Y-%m-%d')} :: {(t.get('text') or '')[:80]}")
