#!/usr/bin/env python3
"""X monitor dormancy check: for every handle with zero qualifying posts in the
saved scan JSON, report the newest fetched tweet date and compare to the 3-day
window cutoff. Older-than-window = DORMANT (threshold change is pointless).
Inside-window with 0 qualifying = genuine threshold artefact."""
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")
p = f"/home/kiro/trend-engine/trends/x/raw/scan_results_{date}_FULL.json"
d = json.load(open(p))

FMT = "%a %b %d %H:%M:%S %z %Y"
now = datetime.now(timezone.utc)
cutoff = now.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=3)

q = {x["handle"] for x in d["qualifying"]}
zero = [h for h in d["handles"] if h not in q]

print(f"scan date {date} | cutoff {cutoff.isoformat()} | zero-qualifying {len(zero)}")
print(f"{'handle':22} {'newest fetched':20} {'age':>10}  verdict")
for h in sorted(zero):
    tws = d["raw"].get(h) or []
    best = None
    for t in tws:
        try:
            dt = datetime.strptime(t.get("createdAt", ""), FMT)
        except Exception:
            continue
        if best is None or dt > best:
            best = dt
    if best is None:
        print(f"@{h:21} {'no tweets fetched':20} {'-':>10}  NO DATA")
        continue
    age = (now - best).days
    if best < cutoff:
        v = "DORMANT (older than window)"
    else:
        v = "IN WINDOW -> threshold artefact"
    print(f"@{h:21} {best.strftime('%Y-%m-%d'):20} {age:>7}d  {v}")
