#!/usr/bin/env python3
"""EveryBe: periksa akun & kegagalan posting (terutama Threads 88%) dari sistem pengelolaan."""
import json, re, sys
from collections import Counter

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

NAMA = {getattr(ACC, n): n for n in dir(ACC) if not n.startswith("_")}
client = get_client()

print("=== 1. akun EveryBe yang terhubung ===")
d = client.get("/public/account?page=1&limit=100")
akun = d.get("docs", []) if isinstance(d, dict) else []
ever = [a for a in akun if re.search(r"everybe|theeverybe", str(a.get("name") or "") + str(a.get("username") or ""), re.I)]
for a in ever:
    print(f"   {a.get('_id')} | {a.get('name')} | @{a.get('username')} | platform {a.get('platform')} | ACC: {NAMA.get(a.get('_id'), '-')}")
if not ever:
    print("   (tidak ditemukan dari nama)")

ids = {a["_id"] for a in ever} | {getattr(ACC, n) for n in dir(ACC) if not n.startswith("_") and "EVERYBE" in n}
print(f"\n   total akun terkait EveryBe: {len(ids)}")

print("\n=== 2. semua jadwal EveryBe + status ===")
semua, page = [], 1
while True:
    dd = client.get_schedules(page=page, limit=100)
    rows = dd.get("docs", []) if isinstance(dd, dict) else []
    semua += rows
    if len(rows) < 100:
        break
    page += 1

milik = [s for s in semua if s.get("accountId") in ids]
print(f"   jadwal EveryBe: {len(milik)} dari total {len(semua)}")
per_akun = Counter((NAMA.get(s.get("accountId"), s.get("accountId")), s.get("status")) for s in milik)
for (ak, st), n in sorted(per_akun.items()):
    print(f"      {ak:<20} {st:<9} {n}")

print("\n=== 3. pesan kegagalan (yang gagal, terbaru) ===")
gagal = [s for s in milik if s.get("status") == "error"]
print(f"   total gagal: {len(gagal)}")
for s in sorted(gagal, key=lambda x: str(x.get("scheduleAt")), reverse=True)[:10]:
    ak = NAMA.get(s.get("accountId"), s.get("accountId"))
    err = ""
    for k in ("error", "errorMessage", "message", "note", "reason", "response"):
        if s.get(k):
            err = f"{k}={str(s[k])[:150]}"
            break
    med = s.get("medias") or s.get("media") or []
    media = str(med[0].get("url") if isinstance(med, list) and med and isinstance(med[0], dict) else (med[0] if med else ""))[:70]
    print(f"\n   {str(s.get('scheduleAt'))[:16]} | {ak} | jenis {s.get('type')}")
    print(f"      {err or '(tidak ada pesan)'}")
    if media:
        print(f"      media: {media}")
    print(f"      caption: {str(s.get('description'))[:80]}")
