#!/usr/bin/env python3
"""
Pindahkan SEMUA carousel pending ke jam 09:00 WIB (FIXED 11 Sep 2026, Bos).
Anti-bentrok: kalau slot 09:00 akun itu sudah terisi → geser ke hari berikutnya.
"""
import sys, json, urllib.request
from datetime import datetime, timedelta, timezone
sys.path.insert(0, "/home/mantapman/.openclaw/workspace-atun")
from repliz_client import HEADERS, BASE

WIB = timezone(timedelta(hours=7))

def get_all():
    docs = []
    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.extend(json.load(r)["docs"])
    return docs

def put(sid, payload):
    req = urllib.request.Request(f"{BASE}/public/schedule/{sid}",
                                 data=json.dumps(payload).encode(),
                                 headers={**HEADERS, "Content-Type": "application/json"},
                                 method="PUT")
    with urllib.request.urlopen(req, timeout=30) as r:
        return r.status

docs = get_all()
pend = [d for d in docs if (d.get("status") or "").lower() == "pending"]
albums = [d for d in pend if (d.get("type") or "").lower() in ("album", "carousel")]
print(f"carousel pending: {len(albums)}")

# slot 09:00 yang sudah terisi per akun
occupied = {}
for d in pend:
    at = d.get("scheduleAt") or ""
    try:
        dt = datetime.fromisoformat(at.replace("Z", "+00:00")).astimezone(WIB)
    except Exception:
        continue
    if dt.hour == 9:
        occupied.setdefault(d.get("accountId"), set()).add(dt.strftime("%Y-%m-%d"))

plan = []
for d in sorted(albums, key=lambda x: x.get("scheduleAt") or ""):
    at = d.get("scheduleAt") or ""
    try:
        dt = datetime.fromisoformat(at.replace("Z", "+00:00")).astimezone(WIB)
    except Exception:
        continue
    if dt.hour == 9 and dt.minute == 0:
        continue  # sudah jam 9
    accid = d.get("accountId")
    # cari tanggal mulai dari tanggal jadwal aslinya
    day = dt.replace(hour=9, minute=0, second=0, microsecond=0)
    if dt.hour < 9:
        pass  # tetap hari sama
    # kalau hari itu sudah ada carousel jam 9 di akun sama → maju hari
    while day.strftime("%Y-%m-%d") in occupied.get(accid, set()):
        day += timedelta(days=1)
    occupied.setdefault(accid, set()).add(day.strftime("%Y-%m-%d"))
    new_at = day.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    plan.append((d, dt, day, new_at))

print(f"\n=== RENCANA PEMINDAHAN ({len(plan)}) ===")
for d, old, new, new_at in plan:
    acc = (d.get("account") or {}).get("name", "?")
    print(f"  {acc:22s} | {old.strftime('%d/%m %H:%M')} → {new.strftime('%d/%m %H:%M')} WIB")

if len(sys.argv) > 1 and sys.argv[1] == "exec":
    print("\n=== EKSEKUSI ===")
    ok = fail = 0
    for d, old, new, new_at in plan:
        payload = {
            "accountId": d.get("accountId"),
            "title": d.get("title", ""),
            "description": d.get("description", ""),
            "topic": d.get("topic", ""),
            "type": d.get("type", ""),
            "medias": d.get("medias") or [],
            "scheduleAt": new_at,
            "replies": d.get("replies") or [],
        }
        try:
            put(d["id"], payload)
            ok += 1
            print(f"  ✅ {d['id']} → {new_at}")
        except Exception as e:
            fail += 1
            print(f"  ❌ {d['id']}: {e}")
    print(f"\n📊 dipindah: {ok} | gagal: {fail}")
else:
    print("\n(dry-run — jalankan dengan 'exec')")
