#!/usr/bin/env python3
"""X monitor dormancy check for one scan date: newest fetched tweet per
zero-qualifying handle vs the 3-day window cutoff."""
import json, sys, os
from datetime import datetime, timezone, timedelta

date = sys.argv[1] if len(sys.argv) > 1 else datetime.now(timezone.utc).strftime("%Y-%m-%d")
base = "/home/kiro/trend-engine/trends/x/raw"
p = f"{base}/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]

lines = [f"scan date {date} | cutoff {cutoff.isoformat()} | handles {len(d['handles'])} | qualifying {len(d['qualifying'])} | failures {d.get('failures')}",
         f"zero-qualifying: {len(zero)}"]
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:
        lines.append(f"@{h:22} NO DATA")
        continue
    age = (now - best).days
    v = "DORMANT (older than window)" if best < cutoff else "IN WINDOW -> threshold artefact"
    lines.append(f"@{h:22} {best.strftime('%Y-%m-%d')} {age:>4}d  {v}")

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