#!/usr/bin/env python3
"""Alat ukur Threads: hitung balasan masuk per akun & per postingan, simpan riwayat.
Dijalankan kapan saja (aman, hanya membaca). Menjadi penilai uji 21 hari."""
import json, os, re, sys
from collections import Counter, defaultdict
from datetime import datetime, timedelta, timezone

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
from repliz_client import get_client, ACC          # noqa: E402

RIWAYAT = f"{WS}/drafts/threads_riwayat_balasan.json"
LAPORAN = f"{WS}/drafts/threads_laporan_balasan.md"
NAMA = {getattr(ACC, n): n for n in dir(ACC) if not n.startswith("_")}
client = get_client()

print("=== menarik data balasan ===")
semua, page = [], 1
while True:
    d = client.get(f"/public/comment?page={page}&limit=100")
    rows = d.get("docs", []) if isinstance(d, dict) else []
    semua += rows
    if len(rows) < 100:
        break
    page += 1
print(f"   total balasan terbaca: {len(semua)}")


def urai(teks):
    """Field 'content' dan 'comment' berbentuk string JSON — ambil isinya dengan aman."""
    if isinstance(teks, dict):
        return teks
    try:
        return json.loads(str(teks).replace("'", '"'))
    except Exception:
        return {}


baris = []
for c in semua:
    isi = urai(c.get("comment"))
    pos = urai(c.get("content"))
    baris.append({
        "akun": NAMA.get(c.get("accountId"), c.get("accountId")),
        "tanggal": str(c.get("createdAt") or "")[:10],
        "status": c.get("status"),
        "balasan": re.sub(r"\s+", " ", str(isi.get("text") or ""))[:160],
        "postingan": re.sub(r"\s+", " ", str(pos.get("description") or ""))[:80],
        "post_id": str(pos.get("id") or ""),
    })

per_akun = Counter(b["akun"] for b in baris)
per_bulan = defaultdict(Counter)
for b in baris:
    if re.match(r"\d{4}-\d{2}", b["tanggal"]):
        per_bulan[b["tanggal"][:7]][b["akun"]] += 1

print("\n=== balasan masuk per akun (semua data) ===")
for akun, n in per_akun.most_common(12):
    print(f"   {akun:<24} {n}")
print("\n=== per bulan ===")
for bulan in sorted(per_bulan):
    ringkas = ", ".join(f"{a}:{n}" for a, n in per_bulan[bulan].most_common(5))
    print(f"   {bulan}: {sum(per_bulan[bulan].values())} balasan | {ringkas}")

print("\n=== 10 balasan terbaru ===")
for b in sorted(baris, key=lambda x: x["tanggal"], reverse=True)[:10]:
    print(f"   {b['tanggal']} | {b['akun']:<20} | «{b['balasan'][:70]}»")
    print(f"        pada postingan: {b['postingan'][:70]}")

# postingan yang paling banyak dibalas
per_post = Counter((b["akun"], b["postingan"]) for b in baris if b["postingan"])
print("\n=== postingan yang paling banyak dibalas ===")
for (akun, post), n in per_post.most_common(8):
    print(f"   {n}x | {akun:<20} | {post[:66]}")

riwayat = json.load(open(RIWAYAT)) if os.path.exists(RIWAYAT) else []
riwayat.append({"diambil": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
                "total": len(baris), "per_akun": dict(per_akun)})
json.dump(riwayat, open(RIWAYAT, "w"), indent=1, ensure_ascii=False)
json.dump(baris, open(f"{WS}/drafts/threads_balasan_mentah.json", "w"), indent=1, ensure_ascii=False)

with open(LAPORAN, "w") as f:
    f.write("# Laporan Balasan Threads\n\n")
    f.write(f"Diambil: {datetime.now(timezone.utc).strftime('%d %B %Y %H:%M UTC')} · total balasan terekam: {len(baris)}\n\n")
    f.write("## Per akun\n\n")
    for akun, n in per_akun.most_common():
        f.write(f"- {akun}: {n}\n")
    f.write("\n## Per bulan\n\n")
    for bulan in sorted(per_bulan):
        f.write(f"- {bulan}: {sum(per_bulan[bulan].values())}\n")
    f.write("\n## Postingan yang paling banyak dibalas\n\n")
    for (akun, post), n in per_post.most_common(15):
        f.write(f"- {n}x — {akun} — {post}\n")

print(f"\n→ riwayat: {RIWAYAT}")
print(f"→ laporan: {LAPORAN}")
