#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""3 Okt 2026 — ganti reel 19:00 (dan story mirror 19:10) jadi BIRU sesuai perintah Bos.

Bos: *"Nanti setelahnya jam 19 : biru. Pagi feed putih. Lalu siang reels biru malam reels putih.
Seterusnya begitu selang seling bergantian warna background"*

Slot 19:00 3 Okt tadinya `ss_reel_putih_14.mp4` (putih) → diganti `ss_reel_biru_19.mp4` (biru).
Caption ikut album 19 (`ALBUM["19"]`) dari `ss_ig_reel_warna.py`. Story mirror 19:10 ikut media baru.

Pakai: python3 fix_reel_19_3okt.py [--go]
"""
import argparse
import os
import subprocess
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_ig_reel_warna as R  # noqa: E402

BASE = "https://mantapserver.tail3947bb.ts.net/openclaw-img/"
INGRESS = ["103.84.155.153", "103.84.155.217"]
REEL_ID = "6abd306f1246a403eda825f8"     # 3 Okt 19:00 WIB (video)
STORY_ID = "6abd30b01733078385f4885c"    # 3 Okt 19:10 WIB (story mirror)
SERI = "19"
WARNA = "biru"


def gate(url):
    ok = True
    for ip in INGRESS:
        p = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "30",
                            "--resolve", f"mantapserver.tail3947bb.ts.net:443:{ip}", url],
                           capture_output=True, text=True)
        kode = p.stdout.strip()
        print(f"    {ip}: {kode}")
        ok = ok and kode == "200"
    return ok


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--go", action="store_true")
    a = ap.parse_args()
    c = get_client()

    video = f"ss_reel_{WARNA}_{SERI}.mp4"
    media_url = BASE + video
    cap = R.caption(SERI)
    judul, warna_asli, link, _ = R.ALBUM[SERI]
    print(f"album {SERI} = {judul} ({warna_asli}) · media {video}")
    print(f"link caption: {link} → hidup={R.link_hidup(link)}")
    masalah = R.valid(cap, cek_link=True)
    print(f"caption {len(cap)} char · masalah: {masalah or 'tidak ada'}")
    if masalah:
        raise SystemExit("caption tidak lolos validasi")
    print("gate media:")
    if not gate(media_url):
        raise SystemExit("media bukan 200 di kedua ingress")

    def media_baru():
        return {"url": media_url, "type": "video", "alt": video,
                "customThumbnail": False, "thumbnail": ""}

    target = [
        (REEL_ID, "REEL 19:00", [media_baru()], cap, f"Reel IG SS {WARNA} ss_opt2_{SERI}"),
        (STORY_ID, "STORY 19:10", [media_baru()], "", f"Story IG SS mirror {video}"),
    ]
    for sid, label, medias, desc, judul_baru in target:
        d = c.get(f"/public/schedule/{sid}")
        d = d.get("data") or d
        lama_m = (d.get("medias") or [{}])[0]
        lama = (lama_m.get("url") or "").split("/")[-1]
        print(f"\n{label} {sid[-6:]} | status={d.get('status')} | media lama: {lama} {lama_m} → baru: {video}")
        print(f"    tipe={d.get('type')} at={d.get('scheduleAt')} judul={d.get('title')!r} "
              f"topic={d.get('topic')!r} replies={(d.get('replies') or [])[:1]}")
        if not a.go:
            continue
        payload = {"accountId": d["accountId"], "title": judul_baru, "topic": d.get("topic") or "",
                   "type": d.get("type") or "", "description": desc, "medias": medias,
                   "scheduleAt": d["scheduleAt"], "replies": d.get("replies") or []}
        for attempt in range(1, 4):
            try:
                c._request("PUT", f"/public/schedule/{sid}", payload)
                break
            except ReplizError as e:
                print(f"    ⚠️ percobaan {attempt}: {e}")
                time.sleep(8)
        d2 = c.get(f"/public/schedule/{sid}")
        d2 = d2.get("data") or d2
        url2 = (d2.get("medias") or [{}])[0].get("url", "").split("/")[-1]
        print(f"    baca balik: media={url2} | status={d2.get('status')} | scheduleAt={d2.get('scheduleAt')}"
              f" | caption={len(d2.get('description') or '')} char | replies={len(d2.get('replies') or [])}")
    if not a.go:
        print("\n(dry run — pakai --go)")


if __name__ == "__main__":
    main()
