#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Geser jadwal seri LinkedIn StudioSoft dari 05:00 WIB → 11:00 WIB (jam kerja B2B).

Hanya menyentuh jadwal milik seri ini (title diawali 'StudioSoft — ' + topic 'Seri ...'),
status pending, dan HANYA yang jam 05:00 WIB. Payload PUT harus lengkap.
"""
import json
import sys
from datetime import datetime, timedelta, timezone

from repliz_client import get_client, ReplizError

WIB = timezone(timedelta(hours=7))
ACC_LI = "6a334c49c5ff4ce3a32259c9"
GO = "--go" in sys.argv

c = get_client()
target = []
page = 1
while True:
    r = c.get_schedules(page=page, limit=100)
    docs = r.get("docs") or r.get("data") or []
    if not docs:
        break
    for d in docs:
        if d.get("accountId") != ACC_LI:
            continue
        if (d.get("topic") or "").startswith("Seri ") and (d.get("scheduleAt") or "")[11:13] == "22":
            target.append(d)
    if len(docs) < 100:
        break
    page += 1

print(f"jadwal seri LinkedIn jam 05:00 WIB: {len(target)}")
for d in target:
    lama = datetime.strptime(d["scheduleAt"], "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
    baru = lama.astimezone(WIB).replace(hour=11, minute=0)
    baru_utc = baru.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    print(f"  {d['_id']} | {d.get('title','')[:45]:<47} {lama.astimezone(WIB).strftime('%d %b %H:%M')} → "
          f"{baru.strftime('%d %b %H:%M')} WIB")
    if not GO:
        continue
    payload = {
        "accountId": d["accountId"],
        "title": d.get("title") or "",
        "topic": d.get("topic") or "",
        "type": d.get("type") or "text",
        "description": d.get("description") or "",
        "medias": d.get("medias") or [],
        "scheduleAt": baru_utc,
        "replies": d.get("replies") or [],
    }
    try:
        # PATCH tidak didukung API (404 "Cannot PATCH") → pakai PUT.
        c._request("PUT", f"/public/schedule/{d['_id']}", payload)
        d2 = c.get(f"/public/schedule/{d['_id']}")
        d2 = d2.get("data") or d2
        print(f"     → status={d2.get('status')} scheduleAt={d2.get('scheduleAt')}")
    except ReplizError as e:
        print(f"     ❌ {e}")
print("(dry run)" if not GO else "selesai")
