#!/usr/bin/env python3
"""Tampilkan isi post Instagram StudioSoft terakhir (jenis, judul, awal caption, media)."""
import sys, json, time, urllib.request, urllib.error
from datetime import datetime, timedelta, timezone

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

IG = rc._ACC.STUDIOSOFT_IG
H = {"Authorization": rc.AUTH_HEADER, "Content-Type": "application/json"}
WIB = timezone(timedelta(hours=7))


def ambil(path):
    r = urllib.request.Request("https://api.repliz.com" + path, headers=H)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        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

milik = [j for j in keluar if j.get("accountId") == IG]
milik.sort(key=lambda j: j.get("scheduleAt") or "")
batas = datetime.now(timezone.utc) - timedelta(days=16)
print(f"post IG StudioSoft sejak {batas.astimezone(WIB).date()}:\n")
for j in milik:
    t = datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
    if t < batas:
        continue
    cap = (j.get("description") or "").replace("\n", " ")
    med = j.get("medias") or []
    media = med[0].get("url", "") if med else ""
    print(f"{t.strftime('%d %b %H:%M')} | {j.get('status'):<7} | {j.get('type'):<6} | "
          f"{len(med)} media | {j.get('title') or '-'}")
    print(f"    caption: {cap[:150]}")
    print(f"    media  : {media[:110]}")
