#!/usr/bin/env python3
"""daily-image-posting-all: item index 35 uky_thread_05_white_brand → Threads @ukyhandoko.
Slot: 08:00 WIB pertama yang kosong = 2026-09-18 (semua slot 6-17 Sep penuh pipeline lain, 08:00 dobel-booking 6-14 Sep).
Media: https://studiosoft.id/wp-content/uploads/2026/07/05_white_brand-1.png (wp_image_map id 6373, 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, HEADERS, BASE

UKY_T = "6a334e89c5ff4ce3a3225a48"
MEDIA_URL = "https://studiosoft.id/wp-content/uploads/2026/07/05_white_brand-1.png"
SCHED_UTC = "2026-09-18T01:00:00.000Z"  # = 08:00 WIB 18 Sep 2026
TITLE = "Brand"

CAPTION = (
    "Banyak yang mengira brand itu logo atau nama yang keren. Padahal brand itu perasaan: bagaimana "
    "orang percaya dan ingin kembali lagi setelah berinteraksi dengan bisnis kita.\n\n"
    "Dulu saya pikir cukup bikin identitas visual yang bagus. Ternyata yang bikin orang ingat bukan "
    "desainnya, tapi pengalamannya — janji ditepati, masalah direspons cepat. Itu yang menempel lebih "
    "lama dari sekadar logo.\n\n"
    "Menurut kamu, kamu percaya sebuah brand karena logo atau pengalamannya? Yuk sharing di 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.replace("@ukyhandoko", ""), "ada mention internal"
    # topic keyword
    topic = "Branding"
    payload = {
        "accountId": UKY_T,
        "title": TITLE,
        "description": CAPTION,
        "topic": topic,
        "type": "image",
        "medias": [{"url": MEDIA_URL, "type": "image", "alt": "05_white_brand.png"}],
        "scheduleAt": SCHED_UTC,
        "replies": [],
    }
    print(json.dumps(payload, ensure_ascii=False, indent=1)[:400])

    c = get_client()
    resp = c.create_schedule(UKY_T, CAPTION, SCHED_UTC, title=TITLE, topic=topic,
                             type_="image",
                             medias=[{"url": MEDIA_URL, "type": "image", "alt": "05_white_brand.png"}],
                             replies=[])
    sid = resp.get("_id") or resp.get("id")
    print("create resp id:", sid, "| full keys:", list(resp.keys()))
    if not sid:
        print("⚠️ create response tanpa id — verifikasi via listing")
    time.sleep(2)

    # ── Verifikasi: re-list pending akun, cari media 05_white_brand ──
    found = []
    r = c.get_schedules(page=1, limit=100)
    pages = (r["totalDocs"] + 99) // 100
    docs = list(r["docs"])
    for p in range(2, pages + 1):
        rr = c.get_schedules(page=p, limit=100)
        docs.extend(rr["docs"])
    for d in docs:
        acc = d.get("account") or {}
        accid = d.get("accountId") or acc.get("id") or ""
        meds = d.get("medias") or []
        urls = [m.get("url", "") for m in meds]
        if accid == UKY_T and any("05_white_brand" in u for u in urls):
            found.append(d)
    print("verifikasi: jadwal berisi 05_white_brand:", 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)
    # ambil yang paling awal sebagai id utama
    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_05_white_brand",
        "brand": "ukyhandoko",
        "source": "uky_threads_images",
        "filename": "05_white_brand.png",
        "topic": "brand",
        "slot_note": "08:00 WIB 6-17 Sep penuh pipeline lain (artikel/quotes/AlbumKorea) → slot bebas 08:00 WIB pertama = 18 Sep",
        "schedule_times": {"threads_uky": f"{SCHED_UTC} (08:00 WIB 2026-09-18) - 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()
