#!/usr/bin/env python3
"""Tambahkan ajakan diskusi ke caption SS-image yang sudah terpasang (7 jadwal)."""
import sys, json, urllib.request
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE

SS = '6a335b9ec5ff4ce3a3225c2a'
AJAKAN = "Menurut kamu, bagian mana yang paling susah dari membangun kehadiran online? Yuk diskusi di komentar! 👇"

def get(sid):
    req = urllib.request.Request(f"{BASE}/public/schedule/{sid}", headers=HEADERS)
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)

def put(sid, payload):
    req = urllib.request.Request(f"{BASE}/public/schedule/{sid}",
                                 data=json.dumps(payload).encode(),
                                 headers={**HEADERS, "Content-Type": "application/json"},
                                 method="PUT")
    with urllib.request.urlopen(req, timeout=30) as r:
        return r.status

# jadwal image SS yang captionnya belum ada ajakan diskusi
targets = [
    "6a969e4ef197bea38583b0d5",  # 2 Sep 01_cover
    "6a969e4f0f4e8a4dace70971",  # 3 Sep 02_kenapa
    "6a969e50f197bea38583b132",  # 4 Sep 03_keuntungan
    "6a969e510f4e8a4dace709cf",  # 5 Sep 04_langkah
    "6a969e52f197bea38583b194",  # 6 Sep 05_cta
    "6a96a01af197bea38583e3ef",  # 7 Sep ss_hc20_edukasi_01_cover
    "6a96a01b0f4e8a4dace74df3",  # 8 Sep ss_hc20_edukasi_02_kenapa
]

for sid in targets:
    d = get(sid)
    desc = d.get("description") or ""
    if "komentar" in desc.lower() or "diskusi" in desc.lower():
        print(f"  ⏭️  {d.get('scheduleAt')[:10]} | sudah ada ajakan")
        continue
    # sisipkan ajakan sebelum hashtag (baris terakhir)
    lines = desc.split("\n")
    # cari baris hashtag
    idx = None
    for i, l in enumerate(lines):
        if l.strip().startswith("#"):
            idx = i
            break
    if idx is not None:
        new_desc = "\n".join(lines[:idx]) + "\n\n" + AJAKAN + "\n\n" + "\n".join(lines[idx:])
    else:
        new_desc = desc + "\n\n" + AJAKAN
    payload = {
        "accountId": d.get("accountId"),
        "title": d.get("title", ""),
        "description": new_desc,
        "topic": d.get("topic", ""),
        "type": d.get("type", ""),
        "medias": d.get("medias") or [],
        "scheduleAt": d.get("scheduleAt"),
        "replies": d.get("replies") or [],
    }
    try:
        put(sid, payload)
        print(f"  ✅ {d.get('scheduleAt')[:10]} | ajakan diskusi ditambahkan")
    except Exception as e:
        print(f"  ❌ {sid}: {e}")
