#!/usr/bin/env python3
"""Analisa reach & engagement akun Threads dari dump API Repliz."""
import json, collections, datetime

accs = json.load(open("/tmp/reach_accs.json"))
cmts = json.load(open("/tmp/reach_comments.json"))
sch = json.load(open("/tmp/reach_schedules.json"))

TID = {a["_id"]: a["username"] for a in accs if a.get("type") == "threads"}
print("=== KOMENTAR MASUK PER AKUN THREADS (window data API) ===")
byacc = collections.Counter()
for c in cmts:
    if c.get("accountId") in TID:
        byacc[c["accountId"]] += 1
for aid, n in byacc.most_common():
    print(f"  {TID[aid]:22s} {n} komentar")

print("\n=== DETAIL KOMENTAR (akun | tanggal | komentator | isi komentar | postingan induk) ===")
for c in sorted(cmts, key=lambda x: x.get("comment", {}).get("createdAt", "")):
    if c.get("accountId") not in TID:
        continue
    cm = c.get("comment", {})
    ct = (c.get("content") or {})
    print(f"{TID[c['accountId']]:14s} | {cm.get('createdAt','')[:10]} | {cm.get('owner',{}).get('name','')[:24]:24s} | "
          f"{(cm.get('text') or '').replace(chr(10),' ')[:110]}")
    print(f"{'':14s}   -> induk: {(ct.get('description') or '').replace(chr(10),' ')[:120]}")
    print(f"{'':14s}   -> {ct.get('url','')}")

print("\n=== JADWAL PER AKUN THREADS (semua status) ===")
st = collections.defaultdict(collections.Counter)
for s in sch:
    aid = s.get("accountId")
    if aid in TID:
        st[aid][s.get("status")] += 1
for aid, c in st.items():
    last = max((s.get("scheduleAt", "") for s in sch if s.get("accountId") == aid), default="")
    print(f"  {TID[aid]:22s} {dict(c)}  terakhir={last[:10]}")

print("\n=== 30 HARI TERAKHIR (sukses tayang per akun) ===")
for aid, name in TID.items():
    ups = [s for s in sch if s.get("accountId") == aid and s.get("status") == "success"]
    print(f"  {name:22s} total_success={len(ups):5d}")
