#!/usr/bin/env python3
"""Analisa volume & tipe post Threads per akun dari dump Repliz (proxy reach)."""
import json, sys, collections, datetime

path = sys.argv[1] if len(sys.argv) > 1 else "/tmp/repliz_all_20261004.json"
d = json.load(open(path))
docs = d if isinstance(d, list) else d.get("docs") or d.get("data") or []

ACC = {
    "6a334e89c5ff4ce3a3225a48": "uky_threads",
    "6a335b9ec5ff4ce3a3225c2a": "studiosoft_threads",
    "6a35f8b7c5ff4ce3a322b2ed": "tslaw_threads",
    "6a5f4af462caae1e04e8b9a6": "leit_threads",
    "6a39e461c5ff4ce3a3233e09": "das_threads",
    "6a4bbc5920e4f4f195e52960": "tsc_threads",
    "6a86d84b62caae1e04fff12c": "soto_threads",
    "6a44ed1920e4f4f195d8ecf7": "everybe_threads",
}
print("total docs:", len(docs))
if docs:
    print("keys contoh:", sorted(docs[0].keys()))

def accname(doc):
    a = doc.get("account") or {}
    aid = a.get("_id") or a.get("id") or doc.get("accountId")
    return ACC.get(aid, str(aid))

def tgl(doc):
    s = doc.get("scheduleAt") or ""
    return s[:10]

today = datetime.date(2026, 10, 4)
cut = today - datetime.timedelta(days=30)

per = collections.defaultdict(lambda: collections.defaultdict(collections.Counter))
for doc in docs:
    an = accname(doc)
    if not an.endswith("_threads"):
        continue
    st = doc.get("status")
    hari = tgl(doc)
    if not hari:
        continue
    try:
        dd = datetime.date.fromisoformat(hari)
    except Exception:
        continue
    if dd > today or dd < today - datetime.timedelta(days=60):
        continue
    bucket = "30hari_terakhir" if dd >= cut else "30hari_sebelum"
    per[an][bucket]["total"] += 1
    per[an][bucket][st] += 1
    if st == "success":
        tipe = doc.get("type") or "?"
        per[an][bucket]["ok_" + str(tipe)] += 1
        # punya reply anak?
        rl = doc.get("replies") or []
        per[an][bucket]["ok_reply_anak" if rl else "ok_tanpa_reply"] += 1
        desc = doc.get("description") or ""
        per[an][bucket]["ok_ada_link" if "http" in desc else "ok_tanpa_link"] += 1
        per[an][bucket]["ok_len_" + ("gt500" if len(desc) > 500 else "le500")] += 1

for an in sorted(per):
    print("\n===", an)
    for b in ("30hari_sebelum", "30hari_terakhir"):
        c = per[an][b]
        if not c:
            continue
        print(" ", b, dict(c))
