#!/usr/bin/env python3
"""Ulangi SATU jadwal tertentu (payload dari dump) di slot baru.

Dipakai kalau reschedule massal gagal di satu item (mis. carousel SS IG yang
media-fetch-nya intermiten). Argumen: <scheduleId-lama> <menit-dari-sekarang>
"""
import json
import sys
import time
from datetime import datetime, timedelta, timezone

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import get_client  # noqa: E402

WIB = timezone(timedelta(hours=7))
sid_lama = sys.argv[1]
menit = int(sys.argv[2]) if len(sys.argv) > 2 else 12
c = get_client()
docs = json.load(open("/home/mantapman/.hermes/profiles/atun/workspace/repliz_all_dump.json"))
d = next((x for x in docs if x.get("id") == sid_lama), None)
if not d:
    sys.exit(f"payload {sid_lama} tidak ada di dump")
at = datetime.now(timezone.utc).replace(second=0, microsecond=0) + timedelta(minutes=menit)
print(f"akun {(d.get('account') or {}).get('name')} | {d.get('type')} | {len(d.get('medias') or [])} media "
      f"-> {at.astimezone(WIB):%H:%M} WIB")
for m in d.get("medias") or []:
    print("   ", m.get("url"))
for attempt in range(1, 6):
    try:
        res = c.create_schedule(d["accountId"], d.get("description") or "",
                                at.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
                                title=d.get("title") or "", topic=d.get("topic") or "",
                                type_=d.get("type") or "text", medias=d.get("medias") or [],
                                replies=d.get("replies") or [], meta=d.get("meta"),
                                additional_info=d.get("additionalInfo"))
        nid = res.get("scheduleId") or res.get("_id") or res.get("id")
        chk = c.get_schedule(nid)
        chk = chk.get("doc") or chk
        print(f"✅ {sid_lama} -> {nid} | status={chk.get('status')} | "
              f"{datetime.fromisoformat(chk['scheduleAt'].replace('Z', '+00:00')).astimezone(WIB):%H:%M} WIB | "
              f"media={len(chk.get('medias') or [])}")
        break
    except Exception as e:
        print(f"⚠️ attempt {attempt}: {e}")
        time.sleep(15)
else:
    print("❌ gagal 5x")
