#!/usr/bin/env python3
"""Rapikan sisa story: urutkan TS Law 13-22 dan pasang TSC story 24-25.

- TS Law: 13 (4 Nov), 17 (5), 18 (6), 19 (7), 20 (8), 21 (9), 22 (10) WIB 12:00.
- TSC: story 24 Okt (8 Nov) dan 25 Okt (9 Nov) WIB 12:10.

Pakai: python3 rapikan_story_okt.py [--run]
"""
import sys
import json
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))
RUN = "--run" in sys.argv
c = get_client()

sisa = {x["lama"]: x["baru"] for x in json.load(open("catatan/pasang_ulang_sisa_okt.json"))}

# (id jadwal yang sudah ada / id gagal, tanggal, jam)
PINDAH = {
    sisa["6ad4b78b83496b501fbf05fc"]: ("2026-11-04", "12:00"),   # story 13 IG
    sisa["6ad4b7f383496b501fbf2744"]: ("2026-11-04", "12:00"),   # story 13 FB
    sisa["6ac108e107008e0e919fa366"]: ("2026-11-05", "12:00"),   # story 17 IG
    sisa["6ac108e81733078385ce31d2"]: ("2026-11-05", "12:00"),   # story 17 FB
    sisa["6ac108ec1733078385ce3247"]: ("2026-11-06", "12:00"),   # story 18 IG
    sisa["6ac108f407008e0e919fa6f9"]: ("2026-11-06", "12:00"),   # story 18 FB
    sisa["6ac108f91733078385ce3584"]: ("2026-11-07", "12:00"),   # story 19 IG
    sisa["6ac108ff07008e0e919fa9f8"]: ("2026-11-07", "12:00"),   # story 19 FB
    sisa["6ac1090907008e0e919faade"]: ("2026-11-08", "12:00"),   # story 20 IG
    sisa["6ac1090e1733078385ce38de"]: ("2026-11-08", "12:00"),   # story 20 FB
}

BARU = {
    "6ac1091b07008e0e919fadab": ("2026-11-09", "12:00"),  # story 21 IG
    "6ac1091f1733078385ce3b31": ("2026-11-09", "12:00"),  # story 21 FB
    "6ac109261733078385ce3ce9": ("2026-11-10", "12:00"),  # story 22 IG
    "6ac1092b07008e0e919fb0b4": ("2026-11-10", "12:00"),  # story 22 FB
    "6ad1c96ea38329b44d126852": ("2026-11-08", "12:10"),  # TSC story 24 Okt
    "6ad1c96e0f680841e48ce588": ("2026-11-09", "12:10"),  # TSC story 25 Okt
}
KOSONGKAN = {"_id", "id", "createdAt", "updatedAt", "__v", "status", "postId", "account", "userId"}


def at(tgl, jam):
    d = datetime.strptime(f"{tgl} {jam}", "%Y-%m-%d %H:%M").replace(tzinfo=WIB)
    return (d - timedelta(hours=7)).strftime("%Y-%m-%dT%H:%M:%S.000Z")


hasil = {"pindah": 0, "baru": 0, "gagal": []}

print("== geser jam (PUT) ==")
for sid, (tgl, jam) in PINDAH.items():
    d = c.get_schedule(sid) or {}
    print(f"  {tgl} {jam} WIB | {d.get('account', {}).get('name')} | {str(d.get('title'))[:40]}")
    if not RUN:
        continue
    try:
        c.update_schedule(sid, {"scheduleAt": at(tgl, jam)})
        hasil["pindah"] += 1
    except Exception as e:
        hasil["gagal"].append((sid, str(e)[:90]))

print("== pasang story yang belum ada ==")
for sid, (tgl, jam) in BARU.items():
    d = c.get_schedule(sid) or {}
    acc = d.get("account") or {}
    medias = [dict(m) for m in (d.get("medias") or [])]
    for m in medias:
        if not m.get("type"):
            m["type"] = "video" if str(m.get("url", "")).lower().endswith((".mp4", ".mov")) else "image"
    print(f"  {tgl} {jam} WIB | {acc.get('name')} [{acc.get('type')}] | {str(d.get('title'))[:40]}")
    if not RUN:
        continue
    r = c.create_schedule(acc.get("id") or d.get("accountId"), d.get("description") or "", at(tgl, jam),
                          title=d.get("title") or "", topic=d.get("topic") or "",
                          type_=d.get("type") or "story", medias=medias,
                          replies=d.get("replies") or [], meta=d.get("meta"),
                          additional_info=d.get("additionalInfo"))
    if (r or {}).get("scheduleId") or (r or {}).get("_id"):
        hasil["baru"] += 1
    else:
        hasil["gagal"].append((sid, str(r)[:90]))

print(f"\npindah: {hasil['pindah']} | baru: {hasil['baru']} | gagal: {len(hasil['gagal'])}")
for g in hasil["gagal"]:
    print("  ❌", g)
if not RUN:
    print("(dry-run, tambahkan --run)")
