#!/usr/bin/env python3
"""daily-image-posting-all: item index 36 uky_thread_06_white_gagal → Threads @ukyhandoko.
Slot: 08:00 WIB berikutnya setelah 05_white_brand (18 Sep 2026) = 2026-09-19 (Sabtu).
Konteks: slot 08:00 WIB 6-17 Sep penuh pipeline lain (artikel/quotes/storytelling); 18 Sep sudah
dipakai image 05_white_brand (index 35). Seri image diurutkan: 06 tayang SETELAH 05.
Media: https://studiosoft.id/wp-content/uploads/2026/07/06_white_gagal-1.png (wp_image_map, HTTP 200, SSL valid).
"""
import json, sys, time, urllib.request
from datetime import datetime, timezone

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

UKY_T = "6a334e89c5ff4ce3a3225a48"
MEDIA_URL = "https://studiosoft.id/wp-content/uploads/2026/07/06_white_gagal-1.png"
SCHED_UTC = "2026-09-19T01:00:00.000Z"  # = 08:00 WIB Sabtu 19 Sep 2026
TITLE = "Gagal"

CAPTION = (
    "Pernah kehilangan klien besar gara-gara miskomunikasi. Waktu itu rasanya "
    "pengen banget tutup usaha. 😅\n\n"
    "Tapi justru dari situ saya belajar: sehebat apa pun sistemnya, komunikasi "
    "manusiawi tetap yang utama. Saya benahi cara mendengar dan menjelaskan — "
    "tanpa drama, tanpa ngeyel.\n\n"
    "Yang menarik? Klien yang dulu pergi malah balik lagi. Gagal satu proyek "
    "ternyata bukan gagal total.\n\n"
    "Menurut kamu, gagal di satu proyek bikin orang berhenti atau malah bangkit? "
    "Yuk sharing di kolom komentar."
)

def main():
    print("caption chars:", len(CAPTION))
    assert len(CAPTION) <= 500, "caption > 500"
    low = CAPTION.lower()
    assert "komentar" in low or "menurut" in low, "pancingan diskusi hilang"
    assert "@" not in CAPTION, "ada mention internal"

    # ── Anti-dobel: cek jadwal yang sudah ada utk media ini (SEMUA status) ──
    c = get_client()
    r = c.get_schedules(page=1, limit=100)
    pages = (r["totalDocs"] + 99) // 100
    docs = list(r["docs"])
    for p in range(2, pages + 1):
        docs.extend(c.get_schedules(page=p, limit=100)["docs"])
    dup = [d for d in docs
           if (d.get("accountId") or (d.get("account") or {}).get("id")) == UKY_T
           and any("06_white_gagal" in (m.get("url") or "") for m in (d.get("medias") or []))]
    if dup:
        print("❌ 06_white_gagal SUDAH pernah dijadwalkan — SKIP:")
        for d in dup:
            print("  ", d.get("id"), d.get("status"), d.get("scheduleAt"))
        sys.exit(1)
    print("anti-dobel OK: 0 jadwal 06_white_gagal di akun uky threads")

    # ── Cek slot 19 Sep 08:00 WIB tidak bentrok dgn pending lain akun uky ──
    clash = [d for d in docs
             if (d.get("accountId") or (d.get("account") or {}).get("id")) == UKY_T
             and (d.get("scheduleAt") or "")[:16] == SCHED_UTC[:16]
             and d.get("status") == "pending"]
    if clash:
        print("❌ slot", SCHED_UTC, "sudah ada pending lain:", [d.get("id") for d in clash])
        sys.exit(1)
    print("slot OK: 19 Sep 01:00Z kosong utk uky threads")

    # ── Create ──
    payload = {
        "accountId": UKY_T,
        "title": TITLE,
        "description": CAPTION,
        "topic": "Kegagalan",
        "type": "image",
        "medias": [{"url": MEDIA_URL, "type": "image", "alt": "06_white_gagal.png"}],
        "scheduleAt": SCHED_UTC,
        "replies": [],
    }
    resp = c.create_schedule(UKY_T, CAPTION, SCHED_UTC, title=TITLE, topic="Kegagalan",
                             type_="image",
                             medias=[{"url": MEDIA_URL, "type": "image", "alt": "06_white_gagal.png"}],
                             replies=[])
    sid = resp.get("_id") or resp.get("id")
    print("create resp id:", sid, "| keys:", list(resp.keys()))
    time.sleep(2)

    # ── Verifikasi: re-list, cari media 06_white_gagal ──
    r = c.get_schedules(page=1, limit=100)
    pages = (r["totalDocs"] + 99) // 100
    docs = list(r["docs"])
    for p in range(2, pages + 1):
        docs.extend(c.get_schedules(page=p, limit=100)["docs"])
    found = [d for d in docs
             if (d.get("accountId") or (d.get("account") or {}).get("id")) == UKY_T
             and any("06_white_gagal" in (m.get("url") or "") for m in (d.get("medias") or []))]
    print("verifikasi: jadwal berisi 06_white_gagal:", len(found))
    for d in found:
        print(json.dumps({
            "id": d.get("id"), "status": d.get("status"), "scheduleAt": d.get("scheduleAt"),
            "type": d.get("type"), "title": d.get("title"),
            "media": (d.get("medias") or [{}])[0].get("url"),
            "desc_len": len(d.get("description") or ""),
            "replies": len(d.get("replies") or []),
        }, ensure_ascii=False))
    if not found:
        print("❌ TIDAK ADA jadwal terverifikasi — jangan update state!")
        sys.exit(1)
    main_id = found[0].get("id")
    for d in found:
        if (d.get("scheduleAt") or "") == SCHED_UTC:
            main_id = d.get("id")
            break

    # ── Update state + log ──
    st = json.load(open("image_posting_state.json"))
    nxt = (st["index"] + 1) % st["total"]
    st["index"] = nxt
    json.dump(st, open("image_posting_state.json", "w"), indent=2)

    log = []
    try:
        log = json.load(open("image_posting_log.json"))
    except Exception:
        log = []
    entry = {
        "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"),
        "item_id": "uky_thread_06_white_gagal",
        "brand": "ukyhandoko",
        "source": "uky_threads_images",
        "filename": "06_white_gagal.png",
        "topic": "gagal",
        "slot_note": "08:00 WIB 7-17 Sep penuh pipeline lain (artikel/storytelling) & 18 Sep dipakai image 05_white_brand → slot bebas 08:00 WIB berikutnya utk seri = 19 Sep",
        "schedule_times": {"threads_uky": f"{SCHED_UTC} (08:00 WIB 2026-09-19) - image 1"},
        "repliz_ids": {"threads_uky": main_id},
        "caption_chars": len(CAPTION),
        "next_index": nxt,
    }
    log.append(entry)
    json.dump(log, open("image_posting_log.json", "w"), indent=1, ensure_ascii=False)
    print("✅ state index ->", nxt, "| log entries:", len(log))

if __name__ == "__main__":
    main()
