#!/usr/bin/env python3
"""Audit seri healthcare StudioSoft (hc) + slot kosong, untuk cron run 14 Sep 2026 02:00 WIB."""
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
print("total schedules fetched:", len(scheds))

# 1) hc index -> statuses (di 3 akun SS)
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], "type": s.get("type"),
        "err": (s.get("errorMessage") or "")[:90], "id": s.get("_id"),
    })

print("\n=== RIWAYAT hc per index ===")
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  %-46s 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("\nKandidat re-air (belum pernah sukses):", never)

# 2) status jadwal carousel 13 Sep 02:00Z (hc35) & 14 Sep 02:00Z
print("\n=== Jadwal 13-15 Sep 00:00-04:00Z di 3 akun SS ===")
for s in scheds:
    aid = s.get("accountId")
    if aid not in AIDS:
        continue
    at = (s.get("scheduleAt") or "")
    if at[:10] in ("2026-09-13", "2026-09-14", "2026-09-15"):
        print("%-12s %s %-9s %-6s %s | %s" % (AIDS[aid], at[:16], (s.get("status") or ""),
              s.get("type"), (s.get("errorMessage") or "")[:60], (s.get("title") or "")[:40]))

# 3) slot kosong 09:00 WIB (02:00Z) Threads+FB & slot LI kosong
busy = {}
for s in scheds:
    if s.get("accountId") in AIDS and (s.get("status") or "").lower() in ("pending", "scheduled", "draft"):
        busy.setdefault(s["accountId"], set()).add((s.get("scheduleAt") or "")[:19])

base = datetime(2026, 9, 14, 7, 0, tzinfo=timezone.utc)  # 14 Sep 14:00 WIB
t0 = (base + timedelta(hours=1)).replace(hour=2, minute=0, second=0)
print("\n=== slot 09:00 WIB (02:00Z) Threads+FB, cek 12 hari ===")
for i in range(12):
    cand = (t0 + timedelta(days=i)).strftime("%Y-%m-%dT02:00:00")
    free = [AIDS[a] for a in (ACC.STUDIOSOFT_THREADS, ACC.STUDIOSOFT_FB) if cand not in busy.get(a, set())]
    print(cand, "free:", free)

# slot LI: cari 7-slot WIB bebas pertama
SLOTS = [1, 4, 7, 10, 13, 16, 21]  # 08,11,14,17,20,23,04 WIB -> UTC hours
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}
li_busy = busy.get(ACC.STUDIOSOFT_LINKEDIN, set())
print("\n=== slot LinkedIn SS kosong (7-slot WIB), hari-hari terdekat ===")
found = 0
for day in range(0, 40):
    d0 = datetime(2026, 9, 14, tzinfo=timezone.utc) + timedelta(days=day)
    for label, uh in sorted(SLOT_H.items(), key=lambda x: x[1]):
        cand = d0.strftime("%Y-%m-%dT%02d:00:00" % uh)
        if cand not in li_busy:
            print(cand, label)
            found += 1
            break
    if found >= 6:
        break
