#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""geser_jam_seri.py — geser jam tayang jadwal SERI (berdasar topic + jam) ke jam lain, hari yang sama.

Contoh:
  python3 geser_jam_seri.py --akun 6a334c49c5ff4ce3a32259c9 --topik "Seri SEO" --dari 5 --ke 14 --go

Pitfall: PATCH /public/schedule/{id} selalu 404 ("Cannot PATCH") → WAJIB pakai PUT dengan payload lengkap.
"""
import argparse
import sys
from datetime import datetime, timedelta, timezone

from repliz_client import get_client, ReplizError

WIB = timezone(timedelta(hours=7))

ap = argparse.ArgumentParser()
ap.add_argument("--akun", required=True)
ap.add_argument("--topik", required=True, help="awalan field topic jadwal")
ap.add_argument("--dari", type=int, required=True, help="jam WIB yang ingin digeser")
ap.add_argument("--ke", type=int, required=True, help="jam WIB tujuan")
ap.add_argument("--go", action="store_true")
a = ap.parse_args()

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") != a.akun:
            continue
        if not (d.get("topic") or "").startswith(a.topik):
            continue
        sa = d.get("scheduleAt") or ""
        if len(sa) < 16:
            continue
        jam_wib = datetime.strptime(sa, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc).astimezone(WIB)
        if jam_wib.hour == a.dari:
            target.append((d, jam_wib))
    if len(docs) < 100:
        break
    page += 1

print(f"jadwal {a.topik}* di akun {a.akun} pada jam {a.dari:02d}:00 WIB: {len(target)}")
for d, jam in target:
    baru = jam.replace(hour=a.ke, minute=0)
    print(f"  {d['_id']} | {d.get('title','')[:45]:<47} {jam.strftime('%d %b %H:%M')} → "
          f"{baru.strftime('%d %b %H:%M')} WIB | status={d.get('status')}")
    if not a.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.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"),
               "replies": d.get("replies") or []}
    try:
        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"      → {d2.get('status')} {d2.get('scheduleAt')}")
    except ReplizError as e:
        print(f"      ❌ {e}")
print("(dry run)" if not a.go else "selesai")
