#!/usr/bin/env python3
"""Hapus SEMUA jadwal carousel (album) pending di IG StudioSoft & LinkedIn StudioSoft.
Instruksi Bos 5 Sep 2026: hentikan tampilan carousel di IG StudioSoft; jangan generate image di LinkedIn StudioSoft.
"""
import sys, json, urllib.request
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE

SS_IG = "6a38ac33c5ff4ce3a3231232"
SS_LI = "6a334c49c5ff4ce3a32259c9"

def get_pending(accid):
    out = []
    for p in range(1, 90):
        raw = urllib.request.Request(f"{BASE}/public/schedule?page={p}&limit=100", headers=HEADERS)
        with urllib.request.urlopen(raw, timeout=30) as r:
            docs = json.load(r)["docs"]
        for d in docs:
            if d.get("accountId") == accid and (d.get("status") or "").lower() == "pending":
                out.append(d)
    return out

def delete(sid):
    req = urllib.request.Request(f"{BASE}/public/schedule/{sid}", headers=HEADERS, method="DELETE")
    with urllib.request.urlopen(req, timeout=30) as r:
        return r.status

# 1) IG StudioSoft — semua album (carousel)
ig = get_pending(SS_IG)
ig_albums = [d for d in ig if (d.get("type") or "").lower() in ("album", "carousel")]
print(f"IG StudioSoft pending: {len(ig)} | album/carousel: {len(ig_albums)}")

# 2) LinkedIn StudioSoft — semua album (image generate)
li = get_pending(SS_LI)
li_albums = [d for d in li if (d.get("type") or "").lower() in ("album", "carousel", "image")]
print(f"LinkedIn StudioSoft pending: {len(li)} | album/image: {len(li_albums)}")

if len(sys.argv) > 1 and sys.argv[1] == "exec":
    ok = fail = 0
    print("\n=== DELETE IG carousel ===")
    for d in ig_albums:
        try:
            delete(d["id"])
            ok += 1
            print(f"  ✅ DEL {d.get('scheduleAt')} | {d['id']}")
        except Exception as e:
            fail += 1
            print(f"  ❌ {d['id']}: {e}")
    print("\n=== DELETE LinkedIn album/image ===")
    for d in li_albums:
        try:
            delete(d["id"])
            ok += 1
            print(f"  ✅ DEL {d.get('scheduleAt')} | {d['id']}")
        except Exception as e:
            fail += 1
            print(f"  ❌ {d['id']}: {e}")
    print(f"\n📊 deleted: {ok} | gagal: {fail}")
else:
    print("\n(dry-run — jalankan dengan 'exec')")
    for d in ig_albums[:5]:
        print(f"  IG: {d.get('scheduleAt')} | {d['id']} | {(d.get('title') or '')[:40]}")
    for d in li_albums[:5]:
        print(f"  LI: {d.get('scheduleAt')} | {d['id']} | {(d.get('title') or '')[:40]}")
