#!/usr/bin/env python3
"""Ringkasan backlog 'reply 2x' Threads per akun aktif per pekan (logika koreksi anak-reply)."""
import json, datetime, collections, os
f = '/tmp/threads_reply_dump.json'
docs = json.load(open(f))
WIB = datetime.timezone(datetime.timedelta(hours=7))
AKUN = {
    "6a334e89c5ff4ce3a3225a48": "uky", "6a335b9ec5ff4ce3a3225c2a": "ss",
    "6a35f8b7c5ff4ce3a322b2ed": "tslaw", "6a39e461c5ff4ce3a3233e09": "das",
    "6a4bbc5920e4f4f195e52960": "tsc", "6a44ed1920e4f4f195d8ecf7": "everybe",
}


def induk(d):
    for r in d.get("replies") or []:
        if isinstance(r, dict):
            k = [x for x in r.keys() if x.isdigit()]
            if 8 <= len(k) < 40:
                return "".join(str(r[x]) for x in sorted(k, key=int))
    return None


def isi(d):
    return [r for r in (d.get("replies") or [])
            if isinstance(r, dict) and ((r.get("description") or r.get("text") or "").strip())]


anak = {}
id_anak = set()
for d in docs:
    p = induk(d)
    if p:
        id_anak.add(d.get("_id"))
        anak[p] = anak.get(p, 0) + 1

now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
per = collections.defaultdict(collections.Counter)
kurang_total = collections.Counter()
for d in docs:
    a = AKUN.get(d.get("accountId"))
    if not a or d.get("status") != "pending" or (d.get("scheduleAt") or "") <= now or d.get("_id") in id_anak:
        continue
    jml = len(isi(d)) + anak.get(d.get("_id"), 0)
    if jml >= 2:
        continue
    t = datetime.datetime.fromisoformat(d["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
    pekan = t.date().isocalendar()[1]
    per[f"pekan {pekan} ({t.date() - datetime.timedelta(days=t.date().weekday())})"][a] += 1
    kurang_total[a] += 1
print("backlog postingan Threads yang belum punya 2 reply (per pekan):")
for p in sorted(per, key=lambda x: int(x.split()[1])):
    row = per[p]
    print(f"  {p:26s} " + " ".join(f"{a}={row.get(a,0)}" for a in ("das", "everybe", "ss", "tsc", "tslaw", "uky") if row.get(a)))
print("\ntotal:", dict(kurang_total), "| jumlah postingan:", sum(kurang_total.values()))
print("dump:", f, "| usia dump (menit):", round((__import__('time').time() - os.path.getmtime(f)) / 60, 1))
