#!/usr/bin/env python3
"""Rincian isi story & reel IG StudioSoft 14 hari terakhir: jenis berkas, pengulangan, jam."""
import sys, json, re, time, urllib.request, urllib.error
from collections import Counter
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

batas = datetime.now(timezone.utc) - timedelta(days=14)
milik = [j for j in keluar if j.get("accountId") == IG and j.get("status") == "success"
         and datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00")) >= batas]

grup, jam = Counter(), Counter()
for j in milik:
    u = ((j.get("medias") or [{}])[0].get("url") or "").split("/")[-1]
    t = datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
    jam[(j.get("type"), t.strftime("%H:%M"))] += 1
    if re.match(r"ss_storyvid_hc\d", u):
        grup["story video seri klinik/healthcare (hc…)"] += 1
    elif u.startswith("ss_reel_"):
        grup["reel bank lama (ss_reel_*)"] += 1
    elif u.startswith("ss_car10"):
        grup["carousel 10 slide (ss_car10_*)"] += 1
    elif u.startswith("ss_story_canvas"):
        grup["story canvas dari carousel"] += 1
    elif u.startswith("SSIGSEP"):
        grup["carousel 4 slide lama (SSIGSEP_*)"] += 1
    else:
        grup[f"lain: {u[:34]}"] += 1

print(f"post sukses 14 hari terakhir: {len(milik)}\n")
print("=== jenis berkas yang dipakai ===")
for k, v in grup.most_common():
    print(f"  {v:>3}× {k}")
print("\n=== jam posting ===")
for (tp, jm), v in sorted(jam.items(), key=lambda x: (x[0][1], x[0][0])):
    print(f"  {jm} {tp:<6} {v}×")
