#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Catch-up story IG StudioSoft yang gagal 30 Sep 20:00 WIB (hc26).

Error: `Internal Server Error: ... Video download failed with: HTTP error code 503. Service Unavailable`
(gagal dari sisi Instagram saat menarik video dari media server; file kita sendiri sehat —
h264 1080x1920 17,5 dtk, 200 di kedua ingress).

Pola baku: jadwal `error` TIDAK bisa tayang walau waktu digeser → DELETE lalu CREATE baru
di waktu lain. Per aturan Bos "gagal → jadwalkan ulang mulai hari berikutnya", retry taruh
di 1 Okt 22:00 WIB (slot 07/14/20 tetap utuh, tidak menabrak reel putih 23:00).

Idempoten: kalau sudah ada jadwal IG SS (bukan story lain) dengan media hc26 pada 1 Okt, SKIP.

Pakai: python3 ss_ig_story_retry_hc26.py [--go]
"""
import datetime
import os
import subprocess
import sys
import time

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
IMG = f"{WS}/openclaw-img"
BASE = "https://mantapserver.tail3947bb.ts.net/openclaw-img/"
INGRESS = ["103.84.155.153", "103.84.155.217"]
sys.path.insert(0, WS)
from repliz_client import get_client  # noqa: E402

IG_SS = "6a38ac33c5ff4ce3a3231232"
GAGAL = "6abb94701733078385934b3b"          # story hc26, 30 Sep 2026 20:00 WIB
MEDIA = "ss_storyvid_hc26.mp4"
WIB = datetime.timezone(datetime.timedelta(hours=7))
TARGET = datetime.datetime(2026, 10, 1, 22, 0, tzinfo=WIB)   # 1 Okt 22:00 WIB


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


def cek_ingress(u):
    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}", u],
                           capture_output=True, text=True)
        print(f"    {ip}: {p.stdout.strip()}")


def main():
    go = "--go" in sys.argv
    at = TARGET.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    c = get_client()
    docs = semua_jadwal(c)

    gagal = next((d for d in docs if d.get("_id") == GAGAL), None)
    print(f"jadwal gagal: {GAGAL} → {gagal.get('status') if gagal else 'TIDAK ADA'} "
          f"| err: {str((gagal or {}).get('errorMessage'))[:90]}")

    sudah = [d for d in docs if d.get("accountId") == IG_SS and MEDIA in
             [(m.get("url") or "").split("/")[-1] for m in (d.get("medias") or [])]
             and str(d.get("scheduleAt")) == at]
    if sudah:
        print(f"⏭️  sudah ada jadwal pengganti di {at} — SKIP (idempoten)")
        return

    u = BASE + MEDIA
    print(f"media: {u}")
    cek_ingress(u)

    if not go:
        print(f"\n(dry-run) rencana: HAPUS {GAGAL} + CREATE story {MEDIA} @ {at} (1 Okt 22:00 WIB)")
        return

    try:
        c.delete_schedule(GAGAL)
        print(f"🗑️  jadwal error {GAGAL} dihapus")
    except Exception as e:
        print(f"⚠️ gagal hapus {GAGAL}: {str(e)[:120]}")

    cap = (gagal or {}).get("description") or ""
    sid = None
    for attempt in range(1, 4):
        try:
            res = c.create_schedule(IG_SS, cap, at, title=f"Story IG SS retry hc26 1 Okt",
                                    topic="IG StudioSoft Story Harian", type_="story",
                                    medias=[{"url": u, "type": "video", "alt": MEDIA}], replies=[])
            sid = res.get("scheduleId") or res.get("_id") or res.get("id")
            break
        except Exception as e:
            print(f"    ⚠️ percobaan {attempt}: {str(e)[:120]}")
            time.sleep(8)
    print(f"{'✅' if sid else '❌'} create @ {at} | id={sid}")
    if not sid:
        return

    d = c.get_schedule(sid)
    d = d.get("data") or d
    if isinstance(d, dict) and "docs" in d:
        d = d["docs"][0]
    print(f"  verifikasi: status={d.get('status')} type={d.get('type')} at={d.get('scheduleAt')} "
          f"media={(d.get('medias') or [{}])[0].get('url', '').split('/')[-1]}")


if __name__ == "__main__":
    main()
