#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Ganti seri carousel DAS 9 Okt: "6 mitos servis mobil" -> "6 salah paham servis mobil".

Alasan (Bos 6 Okt 2026): *"itu Mitos n fakta untuk klien Tslaw. awas jangan salah ya"* —
seri "Mitos atau Fakta" milik klien TS LAW, jangan dipakai di akun lain.

Yang dilakukan:
  1. copy media baru (/tmp/das_car_paham) -> openclaw-img/das_car_paham_01..10.jpg + gate 200
  2. PUT jadwal Threads & Facebook 9 Okt 09:00: medias + description + title + topic baru
  3. verifikasi baca balik

Pakai: python3 ganti_seri_das_9okt.py [--go]
"""
import os, sys, json, shutil, subprocess, urllib.parse, urllib.request

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE, get_client

THREADS = "6a39e461c5ff4ce3a3233e09"
FB = "6a3b41e1c5ff4ce3a327543e"
SRC = "/tmp/das_car_paham"
PREFIX = "das_car_paham_"
LAMA = "das_car_mitos_"
IMG = "https://mantapserver.tail3947bb.ts.net/openclaw-img/"
INGRESS = ["103.84.155.153", "103.84.155.217"]
SLIDES = [f"{PREFIX}{i:02d}.jpg" for i in range(1, 11)]
URLS = [IMG + f for f in SLIDES]
JUDUL = "DAS — 6 Salah Paham Servis Mobil"
TOPIK = "Salah Paham Servis Mobil"
CAP_TH = open("caption_das_paham_threads.txt").read().strip()
CAP_FB = open("caption_das_paham_fb.txt").read().strip()
go = "--go" in sys.argv


def gate(url):
    out = {}
    for label, extra in (("lokal", []), *[(ip, ["--resolve", f"mantapserver.tail3947bb.ts.net:443:{ip}"]) for ip in INGRESS]):
        p = subprocess.run(["curl", "-4", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                            "--max-time", "25", *extra, url], capture_output=True, text=True)
        out[label] = (p.stdout or "000").strip()
    return out


# 1. media
os.makedirs("openclaw-img", exist_ok=True)
for i in range(1, 11):
    shutil.copyfile(os.path.join(SRC, f"das_car_{i:02d}.jpg"), os.path.join("openclaw-img", SLIDES[i - 1]))
print(f"copy {len(SLIDES)} file -> openclaw-img/{PREFIX}*.jpg")
for u in URLS:
    g = gate(u)
    print(f"  {'✅' if all(v == '200' for v in g.values()) else '❌'} {u.split('/')[-1]} {g}")

# 2. cari jadwal lama
c = get_client()
docs, page = [], 1
while True:
    q = urllib.parse.urlencode({"page": page, "limit": 100})
    req = urllib.request.Request(f"{BASE}/public/schedule?{q}", headers=HEADERS)
    with urllib.request.urlopen(req, timeout=60) as r:
        d = json.loads(r.read().decode())
    batch = d.get("docs") or []
    docs += batch
    if not batch or page * 100 >= (d.get("totalDocs") or 0):
        break
    page += 1

target = []
for x in docs:
    aid = (x.get("account") or {}).get("_id")
    if aid not in (THREADS, FB) or x.get("status") != "pending":
        continue
    nama_media = [(m.get("url") or "").split("/")[-1] for m in (x.get("medias") or [])]
    if nama_media and nama_media[0].startswith(LAMA):
        target.append((x, aid, nama_media[0]))

print(f"\njadwal lama yang ketemu ({LAMA}): {len(target)}")
for x, aid, m in target:
    ket = "Threads" if aid == THREADS else "Facebook"
    cap = CAP_TH if aid == THREADS else CAP_FB
    print(f"  {ket} | {x.get('scheduleAt')} | {m} | desc lama {len(x.get('description') or '')} -> baru {len(cap)}")
    if not go:
        continue
    c.update_schedule(x["_id"], {"description": cap, "title": JUDUL, "topic": TOPIK,
                                 "medias": [{"url": u} for u in URLS]})
    b = c.get_schedule(x["_id"])
    bb = b.get("data", b) if isinstance(b, dict) else b
    med = [(m_.get("url") or "").split("/")[-1] for m_ in (bb.get("medias") or [])]
    ok = (bb.get("status") == "pending" and med == SLIDES
          and "mitos" not in (bb.get("description") or "").lower()
          and bb.get("title") == JUDUL)
    print(f"     -> {'✅ OK' if ok else '❌'} status={bb.get('status')} media={len(med)} "
          f"judul={bb.get('title')!r} ada_kata_mitos={'mitos' in (bb.get('description') or '').lower()}")
