#!/usr/bin/env python3
"""Verifikasi akhir jadwal IG StudioSoft: 1 album + 1 story + 1 reel per hari, tanpa konten klinik."""
import sys, json, re, time, urllib.request, urllib.error
from collections import Counter, defaultdict
from datetime import datetime, timezone, timedelta

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
import repliz_client as rc

IG = rc._ACC.STUDIOSOFT_IG
WIB = timezone(timedelta(hours=7))
KUNCI = {"Authorization": rc.AUTH_HEADER}
KATA_KLINIK = ("klinik", "pasien", "dokter", "rumah sakit", "rsia", "praktik dokter", "medis")


def ambil(path):
    r = urllib.request.Request("https://api.repliz.com" + path, headers=KUNCI)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(3)
    return {}


keluar, page = [], 1
while True:
    d = ambil(f"/public/schedule?page={page}&limit=100")
    docs = (d or {}).get("docs") or []
    if not docs:
        break
    keluar += docs
    if len(docs) < 100:
        break
    page += 1

now = datetime.now(timezone.utc)
per_hari = defaultdict(list)
for j in keluar:
    if j.get("accountId") != IG or j.get("status") != "pending":
        continue
    t = datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00"))
    if t <= now:
        continue
    per_hari[t.astimezone(WIB).date().isoformat()].append((t.astimezone(WIB), j))

print(f"hari: {len(per_hari)} · total jadwal: {sum(len(v) for v in per_hari.values())}\n")
jenis = Counter()
masalah = []
for hari in sorted(per_hari):
    isi = sorted(per_hari[hari])
    label = []
    for t, j in isi:
        tp = str(j.get("type")).lower()
        jenis[tp] += 1
        nama = ((j.get("medias") or [{}])[0].get("url") or "").split("/")[-1]
        label.append(f"{t.strftime('%H:%M')} {tp}")
        cap = (j.get("description") or "").lower()
        kena = [k for k in KATA_KLINIK if k in cap]
        if kena or re.search(r"hc\d|klinik|pasien|dokter", nama, re.I):
            masalah.append(f"{hari} {t.strftime('%H:%M')} {tp} — {nama} {kena}")
    c = Counter(tp for _, j in isi for tp in [str(j.get("type")).lower()])
    if not (c.get("album") == 1 and c.get("story") == 1 and c.get("video") == 1):
        masalah.append(f"{hari} — komposisi janggal: {dict(c)}")
    print(f"  {hari}: {len(isi)} post → " + " · ".join(label))

print(f"\nkomposisi total: {dict(jenis)}")
print(f"masalah: {len(masalah)}")
for m in masalah[:20]:
    print(f"  ⚠ {m}")
