#!/usr/bin/env python3
"""Recreate leit_ig_49 di slot kosong berikutnya (hapus jadwal error lama)."""
import sys, json, urllib.request
from datetime import datetime, timedelta, timezone
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE

WIB = timezone(timedelta(hours=7))
LEIT_IG = "6a7d765862caae1e04f7ded3"
SLOTS = [5, 8, 11, 14, 17, 20, 23]
IMG = "https://mantapserver.tail3947bb.ts.net/openclaw-img/leit_ig_49-1.jpg"
OLD_SID = "6a81e186c93a8f645a5bf5bf"

# 1) ambil caption dari jadwal error lama
def get(sid):
    req = urllib.request.Request(f"{BASE}/public/schedule/{sid}", headers=HEADERS)
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)

d = get(OLD_SID)
caption = d.get("description") or ""
title = d.get("title") or ""
print(f"caption asli ({len(caption)} chars):")
print(caption[:200])
print("...")
print(f"title: {title} | topic: {d.get('topic')}")

# 2) hapus jadwal error
req = urllib.request.Request(f"{BASE}/public/schedule/{OLD_SID}", headers=HEADERS, method="DELETE")
with urllib.request.urlopen(req, timeout=30) as r:
    print(f"\n🗑️ DEL jadwal error: HTTP {r.status}")

# 3) cari slot kosong berikutnya
pend = []
for p in range(1, 80):
    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 x in docs:
        if x.get("accountId") == LEIT_IG and (x.get("status") or "").lower() == "pending":
            pend.append(x)
taken = {(x.get("scheduleAt") or "")[:13] for x in pend}
now = datetime.now(WIB)
day = now.replace(minute=0, second=0, microsecond=0)
slot = None
for _ in range(14):
    for h in SLOTS:
        cand = day.replace(hour=h)
        if cand <= now:
            continue
        utc_h = cand.astimezone(timezone.utc).strftime("%Y-%m-%dT%H")
        if utc_h not in taken:
            slot = cand
            break
    if slot:
        break
    day += timedelta(days=1)
if slot is None:
    print("❌ tidak ada slot kosong")
    sys.exit(1)

at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
print(f"\n🎯 slot kosong: {slot.strftime('%d/%m %H:00 WIB')} (UTC {at})")

# 4) create ulang
payload = {
    "accountId": LEIT_IG,
    "title": title,
    "description": caption,
    "topic": d.get("topic") or "",
    "type": "image",
    "medias": [{"url": IMG, "type": "image", "alt": "leit_ig_49-1.jpg"}],
    "scheduleAt": at,
    "replies": d.get("replies") or [],
}
req = urllib.request.Request(f"{BASE}/public/schedule",
                             data=json.dumps(payload).encode(),
                             headers={**HEADERS, "Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=30) as r:
    res = json.load(r)
print(f"✅ CREATE ulang leit_ig_49 → {at} | id={res.get('_id') or res.get('id') or '?'}")
