#!/usr/bin/env python3
"""Audit hc + slot LI. Simpan dump jadwal ke /tmp/sched_dump_1409.json."""
import json, re, sys
from datetime import datetime, timezone, timedelta

sys.path.insert(0, "/home/mantapman/.openclaw/workspace-atun")
from repliz_client import ReplizClient, ACC

c = ReplizClient()
AIDS = {ACC.STUDIOSOFT_THREADS: "SS_Threads", ACC.STUDIOSOFT_FB: "SS_FB",
        ACC.STUDIOSOFT_LINKEDIN: "SS_LinkedIn"}

scheds = []
page = 1
while True:
    d = c.get("/public/schedule?page=%d&limit=100" % page)
    scheds.extend(d.get("docs", []))
    if page >= (d.get("totalPages") or 1):
        break
    page += 1
json.dump(scheds, open("/tmp/sched_dump_1409.json", "w"))
print("total schedules:", len(scheds))

hc = {}
for s in scheds:
    aid = s.get("accountId")
    if aid not in AIDS:
        continue
    urls = " ".join((m.get("url") or "") for m in (s.get("medias") or []))
    m = re.search(r"ss_hc(\d+)_", urls)
    if not m:
        continue
    idx = int(m.group(1))
    hc.setdefault(idx, []).append({
        "acc": AIDS[aid], "status": (s.get("status") or "").lower(),
        "at": (s.get("scheduleAt") or "")[:16], "err": (s.get("errorMessage") or "")[:70],
        "id": s.get("_id")})

print("\n=== RIWAYAT hc (3 akun SS) ===")
for idx in sorted(hc):
    sts = {}
    for h in hc[idx]:
        sts[h["status"]] = sts.get(h["status"], 0) + 1
    aired = any(h["status"] in ("success", "posted", "published", "completed") for h in hc[idx])
    print("hc%02d %-55s aired=%s" % (idx, sts, aired))
    if not aired:
        for h in hc[idx]:
            print("      ", h)
never = [i for i in sorted(hc) if not any(h["status"] in ("success", "posted", "published", "completed") for h in hc[i])]
print("\nBELUM PERNAH SUKSES:", ["hc%02d" % i for i in never])

# semua jadwal album Threads SS (memory: cek error media)
print("\n=== album Threads/FB SS 12-16 Sep ===")
for s in scheds:
    if s.get("accountId") not in (ACC.STUDIOSOFT_THREADS, ACC.STUDIOSOFT_FB):
        continue
    if s.get("type") != "album":
        continue
    at = s.get("scheduleAt") or ""
    if at[:10] in ("2026-09-12", "2026-09-13", "2026-09-14", "2026-09-15", "2026-09-16"):
        print("%-11s %s %-8s %-42s %s" % (AIDS[s["accountId"]], at[:16], s["status"],
              (s.get("title") or "")[:42], (s.get("errorMessage") or "")[:60]))

# slot LI kosong
busy = set()
for s in scheds:
    if s.get("accountId") == ACC.STUDIOSOFT_LINKEDIN and (s.get("status") or "").lower() in ("pending", "scheduled", "draft"):
        busy.add((s.get("scheduleAt") or "")[:19])
print("\n=== slot LinkedIn SS kosong (7-slot WIB) ===")
SLOT_H = [("05:00 WIB", 22), ("08:00 WIB", 1), ("11:00 WIB", 4), ("14:00 WIB", 7),
          ("17:00 WIB", 10), ("20:00 WIB", 13), ("23:00 WIB", 16)]
found = 0
for day in range(0, 45):
    d0 = datetime(2026, 9, 14, tzinfo=timezone.utc) + timedelta(days=day)
    for label, uh in SLOT_H:
        cand = "%sT%02d:00:00" % (d0.strftime("%Y-%m-%d"), uh)
        if cand not in busy:
            print(cand, label, "(UTC %02d:00)" % uh)
            found += 1
            break
    if found >= 8:
        break
