#!/usr/bin/env python3
"""Inventaris jadwal FEED (image/video/album, bukan story) per akun Instagram.
Menjawab: akun IG mana yang feed-nya habis lebih awal → perlu dilanjutkan s/d akhir Okt."""
import json, sys, collections
from datetime import datetime, timezone
from repliz_client import get_client, ACCOUNTS

IG = {
    "6a8bfbe462caae1e04046553": "@_ukyhandoko (uky_handoko_ig)",
    "6a83c90262caae1e04fc83b8": "uky_ig",
    "6a38ac33c5ff4ce3a3231232": "studiosoft_ig",
    "6a3ba04ac5ff4ce3a329a7f3": "dmark_ig",
    "6a7d765862caae1e04f7ded3": "leit_ig",
    "6a76a54d62caae1e04f30968": "tslaw_ig",
    "6a37287bc5ff4ce3a322dab5": "arelancor_ig",
    "6a39e461c5ff4ce3a3233e09": "das_ig",
    "6a86a7e062caae1e04ff8244": "tsc_ig",
    "6a86d6e962caae1e04ffedaa": "soto_ig",
    "6a88416362caae1e040147d2": "dojo_ksatria_ig",
}

def fetch_all():
    c = get_client()
    docs, page = [], 1
    while True:
        r = c.get(f"/public/schedule?page={page}&limit=100")
        d = r.get("docs") or []
        docs += d
        tp = r.get("totalPages") or 0
        if page >= tp or not d:
            break
        page += 1
    return docs

if __name__ == "__main__":
    cache = "/tmp/ig_feed_inv.json"
    if "--fresh" in sys.argv:
        docs = fetch_all()
        json.dump(docs, open(cache, "w"))
        print(f"fetched {len(docs)} schedules -> {cache}")
    else:
        docs = json.load(open(cache))
    now = datetime.now(timezone.utc)
    per = collections.defaultdict(lambda: collections.defaultdict(list))
    for d in docs:
        acc = (d.get("account") or {}).get("_id") or d.get("accountId")
        if acc not in IG:
            continue
        t = d.get("type")
        st = d.get("status")
        sa = d.get("scheduleAt") or ""
        per[IG[acc]][t].append((sa, st, d.get("_id")))
    for name in sorted(per):
        print(f"\n=== {name} ===")
        for t in sorted(per[name]):
            rows = sorted(per[name][t])
            fut = [r for r in rows if r[0] >= now.strftime("%Y-%m-%dT%H:%M") and r[1] in ("pending", "draft", "processing")]
            past_err = [r for r in rows if r[0] < now.strftime("%Y-%m-%dT%H:%M") and r[1] == "error"]
            print(f"  {t:8s} total={len(rows):4d} pending-future={len(fut):4d} err-past={len(past_err):4d}"
                  f" | future {fut[0][0][:16] if fut else '-'} .. {fut[-1][0][:16] if fut else '-'}")
            st_count = collections.Counter(r[1] for r in rows)
            print(f"           status: {dict(st_count)}")
    # ringkas: feed pending per hari 15 hari ke depan
    print("\n=== feed pending per hari (image/video/album, 1-31 Okt) ===")
    for name in sorted(per):
        days = collections.Counter()
        for t in ("image", "video", "album", "reel"):
            for sa, st, _ in per[name].get(t, []):
                if sa.startswith("2026-10") and st in ("pending", "draft", "processing"):
                    days[sa[:10]] += 1
        if days:
            print(f"  {name:28s} {dict(sorted(days.items()))}")
        else:
            print(f"  {name:28s} (0 pending feed di Oktober)")
