#!/usr/bin/env python3
"""2026-10-09: dormancy check on every zero-qualifying handle.

No 503s this run, so no retry pass is needed -- this script only runs the
dormancy verdict (newest FETCHED tweet per zero-qualifying handle vs the 3-day
cutoff), per the 2026-09-29 correction.
"""
import json
from datetime import datetime, timezone, timedelta
from collections import Counter

DATE = "2026-10-09"
RAW = "/home/kiro/trend-engine/trends/x/raw"
JSON = f"{RAW}/scan_results_{DATE}_FULL.json"

d = json.load(open(JSON))


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


def score(t):
    return ((t.get("likeCount") or 0) + 2 * (t.get("retweetCount") or 0)
            + 3 * (t.get("replyCount") or 0) + (t.get("viewCount") or 0) / 100)


now = datetime.now(timezone.utc)
cutoff = now.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=3)
print(f"CUTOFF {cutoff.isoformat()}  (now {now.isoformat()})")
print(f"failures in scan: {d.get('failures')}")

c = Counter(x["handle"] for x in d["qualifying"])
zero = [h for h in d.get("handles", []) if h not in c]
print("\n===== DORMANCY CHECK (newest fetched tweet per zero-qualifying handle) =====")
for h in zero:
    raw = d.get("raw", {}).get(h) or []
    ds = [pdate(t.get("createdAt", "")) for t in raw]
    ds = [x for x in ds if x]
    if not ds:
        print(f"@{h}: NO TWEETS FETCHED (empty account / API returned nothing)")
        continue
    newest = max(ds)
    age = (now - newest).days
    inwin = newest >= cutoff
    verdict = "IN-WINDOW (genuine threshold artefact)" if inwin else "DORMANT (threshold useless)"
    top = max(raw, key=score)
    rtt = "RT" if (top.get("retweeted_tweet") or top.get("type") == "retweet"
                   or (top.get("text") or "").startswith("RT @")) else "orig"
    print(f"@{h}: newest {newest.strftime('%Y-%m-%d')} ({age}d) -> {verdict}"
          f" | best fetched {rtt}: {top.get('likeCount', 0)}L/{top.get('viewCount', 0)}V"
          f" | {(top.get('text') or '')[:90]}")
