#!/usr/bin/env python3
"""Analisis pola posting IG StudioSoft: jumlah per hari, pengulangan media, dan komposisi jenis."""
import sys, json, 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

milik = [j for j in keluar if j.get("accountId") == IG and j.get("status") == "success"]
milik.sort(key=lambda j: j["scheduleAt"])
sekarang = datetime.now(timezone.utc)

print("=== jumlah post IG per hari (30 hari terakhir) ===")
per_hari = Counter()
for j in milik:
    t = datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
    if (sekarang - t) <= timedelta(days=30):
        per_hari[t.date().isoformat()] += 1
for h in sorted(per_hari):
    print(f"  {h}: {per_hari[h]:>2} post")
print(f"\n  rata-rata 7 hari terakhir: "
      f"{sum(v for k, v in per_hari.items() if k >= (sekarang.astimezone(WIB).date() - timedelta(days=7)).isoformat()) / 7:.1f} post/hari")

print("\n=== pengulangan media (30 hari terakhir) ===")
pakai = Counter()
for j in milik:
    t = datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00"))
    if (sekarang - t) > timedelta(days=30):
        continue
    for m in (j.get("medias") or []):
        pakai[m.get("url", "")] += 1
ulang = {u: n for u, n in pakai.items() if n > 1}
print(f"  berkas media unik: {len(pakai)} · berkas yang dipakai lebih dari sekali: {len(ulang)}")
for u, n in pakai.most_common(12):
    tanda = f"  ← dipakai {n}×" if n > 1 else ""
    print(f"    {n}× {u.split('/')[-1][:64]}{tanda}")

print("\n=== komposisi jenis post 30 hari ===")
jenis = Counter()
for j in milik:
    t = datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00"))
    if (sekarang - t) <= timedelta(days=30):
        jenis[j.get("type")] += 1
print("  " + ", ".join(f"{k}={v}" for k, v in jenis.most_common()))

print("\n=== 10 caption reel terakhir ===")
reel = [j for j in milik if j.get("type") == "video"
        and (sekarang - datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00"))) <= timedelta(days=14)]
for j in reel[-10:]:
    t = datetime.fromisoformat(j["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
    print(f"  {t.strftime('%d %b %H:%M')} | {(j.get('title') or '')[:40]} | {(j.get('description') or '')[:80].replace(chr(10), ' ')}")
