#!/usr/bin/env python3
"""Ringkas jadwal Repliz 7 hari terakhir: tayang vs gagal, plus jadwal terlambat."""
import collections
import json
from datetime import datetime, timedelta, timezone
from repliz_client import get_client

c = get_client()
docs = []
page = 1
while True:
    r = c.get_schedules(page, 100)
    docs += r.get("docs", [])
    if not r.get("hasNextPage"):
        break
    page += 1

WIB = timezone(timedelta(hours=7))
now = datetime.now(WIB)
awal = (now - timedelta(days=7)).replace(hour=0, minute=0, second=0, microsecond=0)


def wib(s):
    try:
        return datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone(WIB)
    except Exception:
        return None


rows = []
for d in docs:
    t = wib(d.get("scheduleAt") or "")
    if t:
        acc = (d.get("account") or {}).get("name") or d.get("accountId", "?")
        rows.append((t, acc, d))

print("total jadwal ditarik:", len(rows))

tbl = collections.defaultdict(lambda: collections.Counter())
for t, acc, d in rows:
    if t < awal:
        continue
    tbl[t.strftime("%d %b")][str(d.get("status"))] += 1
print("\nPER HARI (tayang/gagal):")
for hari in sorted(tbl, key=lambda x: datetime.strptime(x + " 2026", "%d %b %Y")):
    c2 = tbl[hari]
    print(f"  {hari}: success={c2.get('success',0)} error={c2.get('error',0)} pending={c2.get('pending',0)+c2.get('scheduled',0)} total={sum(c2.values())}")

gagal = [(t, acc, d) for t, acc, d in rows if str(d.get("status")) == "error" and t >= awal]
print("\nGAGAL 7 HARI:", len(gagal))
per = collections.Counter((t.strftime("%d %b"), acc) for t, acc, d in gagal)
for (tgl, acc), n in sorted(per.items(), key=lambda x: (datetime.strptime(x[0][0] + " 2026", "%d %b %Y"), x[0][1])):
    print(f"  {tgl} {acc}: {n}")

lewat = [(t, acc, d) for t, acc, d in rows if t < now - timedelta(minutes=45) and str(d.get("status")) not in ("success", "error")]
print("\nTERLAMBAT (lewat jam, belum tayang & bukan error):", len(lewat))
for t, acc, d in sorted(lewat, key=lambda x: x[0])[:20]:
    print(" ", t.strftime("%d %b %H:%M"), acc, d.get("type"), str(d.get("title"))[:45], d.get("status"))

besok = [(t, acc, d) for t, acc, d in rows if now <= t <= now + timedelta(hours=30)]
print("\nAKAN TAYANG 30 jam ke depan:", len(besok))
for t, acc, d in sorted(besok, key=lambda x: x[0])[:40]:
    print(" ", t.strftime("%d %b %H:%M"), acc, d.get("type"), str(d.get("title"))[:45], d.get("status"))

# simpan detail gagal
with open("rekap_gagal_7hari.json", "w") as f:
    json.dump([{"waktu_wib": t.strftime("%Y-%m-%d %H:%M"), "akun": acc, "platform": d.get("type"),
                "judul": d.get("title"), "status": d.get("status"), "postId": d.get("postId"),
                "id": d.get("id"), "err": d.get("errorMessage")} for t, acc, d in gagal], f, indent=1, ensure_ascii=False)
print("\ndetail → rekap_gagal_7hari.json")
