#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""atur_pola_reel.py — selaraskan urutan warna REEL IG StudioSoft dengan pola harian baru.

Perintah Bos 2 Okt 2026 12:2x WIB:
  *"Atur polanya. Begitupun reels. Hari ini putih n biru. Besoknya biru n putih. Begitu terus"*

Patokan (satu sumber kebenaran: `ss_carousel_lib.warna_ke`) — DIPERBAIKI 3 Okt 2026:
  urutan 1 = carousel feed 08:30 · urutan 2 = reel 11:00 · urutan 3 = reel 19:00.

  3 Okt (ganjil): carousel BIRU → 11:00 PUTIH → 19:00 BIRU
  4 Okt (genap) : carousel PUTIH → 11:00 BIRU → 19:00 PUTIH

Ritmenya: tiap post feed IG SS selalu kebalikan dari post sebelumnya. Patokan 2 Okt (11:00 = warna
pertama hari itu) membuat reel 11:00 kembar dengan carousel 08:30 (2-3 Okt dua BIRU berurutan) —
itu yang dikoreksi. Jadwal reel yang sudah ada masih memakai patokan lama, jadi pasangan 4 Okt
ke atas kebalik. Skrip ini menukar `scheduleAt` antara slot 11:00 dan 19:00 pada hari yang sama
(media + caption ikut medianya masing-masing, tidak diubah), plus story mirror +10 menitnya.
Slot yang sudah lewat / bukan `pending` dilewati.

Pakai:
  python3 atur_pola_reel.py            # dry run
  python3 atur_pola_reel.py --go
  python3 atur_pola_reel.py --mulai 2026-10-03 --go    # batasi mulai tanggal tertentu
"""
import argparse
import datetime
import os
import re
import sys
import time

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

IG_SS = "6a38ac33c5ff4ce3a3231232"
WIB = datetime.timezone(datetime.timedelta(hours=7))
RE_VID = re.compile(r"ss_reel_(putih|biru)_\d\d\.mp4$")


def semua(c):
    docs, page = [], 1
    while page <= 60:
        r = None
        for a in range(5):
            try:
                r = c.get_schedules(page=page, limit=100)
                break
            except Exception:
                time.sleep(4 + 2 * a)
        if r is None:
            raise SystemExit("gagal baca jadwal Repliz")
        b = r.get("docs") or []
        docs += b
        if len(b) < 100:
            break
        page += 1
    return docs


def nama_media(d):
    m = d.get("medias") or []
    return (m[0].get("url") or "").split("/")[-1] if m else ""


def warna_dari(nama):
    mm = RE_VID.search(nama or "")
    return mm.group(1) if mm else None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--go", action="store_true")
    ap.add_argument("--mulai", default=None, help="YYYY-MM-DD (default: hari ini WIB)")
    ap.add_argument("--sampai", default=None, help="YYYY-MM-DD (opsional)")
    a = ap.parse_args()

    hari_ini = datetime.datetime.now(WIB).date()
    mulai = datetime.date.fromisoformat(a.mulai) if a.mulai else hari_ini
    sampai = datetime.date.fromisoformat(a.sampai) if a.sampai else None

    c = get_client()
    docs = [d for d in semua(c) if d.get("accountId") == IG_SS]

    # kelompokkan per tanggal WIB
    per_hari = {}
    for d in docs:
        sa = str(d.get("scheduleAt") or "")
        if len(sa) < 16:
            continue
        try:
            dt = datetime.datetime.fromisoformat(sa.replace("Z", "+00:00")).astimezone(WIB)
        except Exception:
            continue
        per_hari.setdefault(dt.date(), []).append((dt, d))

    sekarang = datetime.datetime.now(datetime.timezone.utc)
    print(f"hari ini {hari_ini} WIB | jadwal IG SS {len(docs)} | "
          f"patokan: reel = lanjutan urutan warna carousel (11:00 = urutan 2, 19:00 = urutan 3)\n")

    rencana = []      # (jam_lama, d, jam_baru)
    for tgl in sorted(per_hari):
        if tgl < mulai or (sampai and tgl > sampai):
            continue
        slot = {}
        for dt, d in per_hari[tgl]:
            tipe = str(d.get("type") or "").lower()
            w = warna_dari(nama_media(d))
            if tipe == "video" and dt.hour in (11, 19) and dt.minute == 0 and w:
                slot[dt.hour] = (d, w)
            elif tipe == "story" and dt.hour in (11, 19) and dt.minute == 10 and w:
                slot[f"story{dt.hour}"] = (d, w)
        if 11 not in slot or 19 not in slot:
            continue
        mau = {11: L.warna_ke(tgl, 2), 19: L.warna_ke(tgl, 3)}
        d11, w11 = slot[11]
        d19, w19 = slot[19]
        perlu = (w11 != mau[11]) or (w19 != mau[19])
        print(f"{tgl} | 11:00 {w11:5s} ({d11['_id'][-6:]}) · 19:00 {w19:5s} ({d19['_id'][-6:]}) "
              f"| seharusnya {mau[11]}/{mau[19]} → {'TUKAR' if perlu else 'sudah benar ✅'}")
        if not perlu:
            continue
        # tolak tukar kalau salah satu slot sudah lewat / bukan pending (mis. sudah tayang)
        for d in (d11, d19):
            st = str(d.get("status") or "").lower()
            dt = datetime.datetime.fromisoformat(str(d["scheduleAt"]).replace("Z", "+00:00"))
            if st != "pending" or dt <= sekarang:
                print(f"      ⚠️ slot {dt.astimezone(WIB):%H:%M} status={st} — TIDAK bisa ditukar, dilewati")
                perlu = False
                break
        if not perlu:
            continue
        # pasangan story mirror ikut ditukar (11:10 ↔ 19:10)
        pasangan = [(d11, d19)]
        if "story11" in slot and "story19" in slot:
            s11, sw11 = slot["story11"]
            s19, sw19 = slot["story19"]
            if (sw11, sw19) == (w11, w19):
                pasangan.append((s11, s19))
            else:
                print("      ⚠️ story mirror tidak sepadan warnanya — story tidak ikut ditukar")
        for da, db in pasangan:
            t_a = da["scheduleAt"]
            t_b = db["scheduleAt"]
            rencana.append((da, t_b))
            rencana.append((db, t_a))
            print(f"      tukar {da['_id'][-6:]} ({t_a[11:16]}) ↔ {db['_id'][-6:]} ({t_b[11:16]})")

    print(f"\ntotal slot yang ditukar: {len(rencana)} ({len(rencana)//2} pasang)")
    if not rencana:
        print("tidak ada yang perlu diubah ✅")
        return
    if not a.go:
        print("\n(dry run — pakai --go untuk eksekusi)")
        return

    print("\n=== eksekusi ===")
    for d, at_baru in rencana:
        payload = {"accountId": d["accountId"], "title": d.get("title") or "",
                   "topic": d.get("topic") or "", "type": d.get("type") or "video",
                   "description": d.get("description") or "", "medias": d.get("medias") or [],
                   "scheduleAt": at_baru, "replies": d.get("replies") or []}
        try:
            c._request("PUT", f"/public/schedule/{d['_id']}", payload)
        except ReplizError as e:
            print(f"  ❌ {d['_id']}: {e}")
            continue
        d2 = c.get(f"/public/schedule/{d['_id']}")
        d2 = d2.get("data") or d2
        jam = datetime.datetime.fromisoformat(str(d2.get("scheduleAt")).replace("Z", "+00:00")) \
            .astimezone(WIB).strftime("%d %b %H:%M")
        print(f"  ✅ {d['_id'][-6:]} {nama_media(d2)} → {jam} WIB | status={d2.get('status')}")
    print("\nselesai.")


if __name__ == "__main__":
    main()
