#!/usr/bin/env python3
"""daily-image-posting-all: item index 39 uky_thread_09_blue_ai → Threads @ukyhandoko.
Slot: 08:00 WIB bebas pertama SETELAH 21 Sep 2026 (08_orange_bisnis_marathon). Image 05=18 Sep,
06=19 Sep, 07=20 Sep, 08=21 Sep, seri diurutkan: 09 tayang SETELAH 08 → scan mulai 2026-09-22.
Media: https://studiosoft.id/wp-content/uploads/2026/07/09_blue_ai.png (wp_image_map id 6377, HTTP 200).
Tema gambar (generate_uky_threads_images.py): "AI Bukan Pengganti, Tapi Akselerator":
banyak yang takut AI gantiin pekerjaan; saya pakai AI buat ngebut (riset & drafting konten,
analisis data lebih cepat, optimasi campaign), bukan ngilangin manusia — manusia tetap pegang
strategi & kreativitas.
"""
import json, sys, time
from datetime import datetime, timezone, timedelta

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/09_blue_ai.png"
TITLE = "AI"
TOPIC = "AI"

CAPTION = """Banyak yang takut AI bakal menggantikan pekerjaan manusia. Saya justru memilih menjadikannya akselerator — bukan pengganti.

Di tim kami, AI dipakai untuk riset, drafting konten, analisis data, sampai optimasi campaign. Tapi strategi dan kreativitas tetap di tangan manusia. AI mempercepat, manusia yang menentukan arah.

Menurut kamu, AI lebih banyak membantu atau mengancam pekerjaanmu? Yuk cerita di komentar! 👇"""

def fetch_all(client):
    r = client.get_schedules(page=1, limit=100)
    pages = (r["totalDocs"] + 99) // 100
    docs = list(r["docs"])
    for p in range(2, pages + 1):
        docs.extend(client.get_schedules(page=p, limit=100)["docs"])
    return docs

def acc_id(d):
    return d.get("accountId") or (d.get("account") or {}).get("id")

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"

    c = get_client()
    docs = fetch_all(c)

    # ── Anti-dobel: cek jadwal utk media ini (SEMUA status) di akun uky threads ──
    dup = [d for d in docs
           if acc_id(d) == UKY_T
           and any("09_blue_ai" in (m.get("url") or "") for m in (d.get("medias") or []))]
    if dup:
        print("❌ 09_blue_ai 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 09_blue_ai di akun uky threads")

    # ── Cari slot 08:00 WIB (01:00 UTC) bebas pertama mulai 22 Sep 2026 ──
    pend = [d for d in docs if acc_id(d) == UKY_T and d.get("status") == "pending"]
    occupied = sorted({(d.get("scheduleAt") or "")[:16] for d in pend})
    print("pending uky threads (scheduleAt[:16]) count:", len(occupied))

    sched_utc = None
    day = datetime(2026, 9, 22, tzinfo=timezone.utc)
    for _ in range(20):  # scan maks 20 hari
        cand = day.strftime("%Y-%m-%dT01:00:00")
        if cand not in occupied:
            sched_utc = cand + ".000Z"
            break
        day = day + timedelta(days=1)
    if not sched_utc:
        print("❌ tidak ada slot 08:00 WIB bebas s/d +20 hari — STOP, lapor Bos")
        sys.exit(1)
    print("slot terpilih:", sched_utc, "=", "08:00 WIB", day.strftime("%Y-%m-%d"))

    # ── Create ──
    payload_media = [{"url": MEDIA_URL, "type": "image", "alt": "09_blue_ai.png"}]
    resp = c.create_schedule(UKY_T, CAPTION, sched_utc, title=TITLE, topic=TOPIC,
                             type_="image", medias=payload_media, 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 09_blue_ai ──
    docs = fetch_all(c)
    found = [d for d in docs
             if acc_id(d) == UKY_T
             and any("09_blue_ai" in (m.get("url") or "") for m in (d.get("medias") or []))]
    print("verifikasi: jadwal berisi 09_blue_ai:", 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 "").startswith(sched_utc[:16]):
            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_09_blue_ai",
        "brand": "ukyhandoko",
        "source": "uky_threads_images",
        "filename": "09_blue_ai.png",
        "topic": "AI",
        "slot_note": f"08:00 WIB 10-17 Sep penuh pipeline lain (artikel/storytelling); 18 Sep=image 05, 19 Sep=image 06, 20 Sep=image 07, 21 Sep=image 08 → slot bebas 08:00 WIB pertama utk seri = {day.strftime('%d %b')}",
        "schedule_times": {"threads_uky": f"{sched_utc} (08:00 WIB {day.strftime('%Y-%m-%d')}) - 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()
