#!/usr/bin/env python3
"""Fix 4 caption tersisa: tambahkan ajakan diskusi eksplisit (kata 'komentar')."""
import sys, json, urllib.request
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE

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 yang captionnya belum eksplisit "komentar"
TARGETS = {
    "6a969e500f4e8a4dace709af": "Kamu nulis konten berdasarkan riset atau feeling aja? Jujur, tulis di komentar! 👇",  # SS 4 Sep evening
}

# cari 3 jadwal uky (6 Sep AI, 8 Sep bisnis sehat, 8 Sep kesuksesan)
pend_ids = []
for p in range(1, 60):
    raw = urllib.request.Request(f"{BASE}/public/schedule?page={p}&limit=100", headers=HEADERS)
    with urllib.request.urlopen(raw, timeout=30) as r:
        docs = json.load(r)["docs"]
    for d in docs:
        if d.get("accountId") == "6a334e89c5ff4ce3a3225a48" and (d.get("status") or "").lower() == "pending":
            at = d.get("scheduleAt") or ""
            if at[:10] in ("2026-09-06", "2026-09-08"):
                pend_ids.append(d["id"])

for sid in pend_ids:
    d = get(sid)
    desc = d.get("description") or ""
    if "AI bukan pengganti kamu" in desc:
        TARGETS[sid] = None  # sudah ada "Share di sini! 🚀" — tambah kata komentar
    elif "Bisnis yang sehat itu bukan" in desc:
        TARGETS[sid] = None
    elif "Kesuksesan itu bukan soal seberapa cepat" in desc:
        TARGETS[sid] = None

# update: untuk setiap target, tambah kalimat komentar eksplisit sebelum hashtag
for sid, extra in TARGETS.items():
    d = get(sid)
    desc = d.get("description") or ""
    lines = desc.split("\n")
    idx = None
    for i, l in enumerate(lines):
        if l.strip().startswith("#"):
            idx = i
            break
    # cari kalimat ajakan yang sudah ada (akhiri dengan 👇 atau ?) lalu ganti
    if extra is not None:
        new_desc = "\n".join(lines[:idx]) + "\n\n" + extra + "\n\n" + "\n".join(lines[idx:])
    else:
        # ganti "Share di sini! 🚀" → "Share di sini di kolom komentar! 🚀", dll
        new_desc = desc.replace("Share di sini! 🚀", "Share pengalamanmu di kolom komentar! 🚀")
        new_desc = new_desc.replace("Bisnismu punya identitas yang jelas belum? 👇", "Bisnismu punya identitas yang jelas belum? Cerita di komentar! 👇")
        new_desc = new_desc.replace("Menurutmu, apa kunci supaya bisnis tidak cuma 'naik' tapi 'naik kelas'? 👇", "Menurutmu, apa kunci supaya bisnis tidak cuma 'naik' tapi 'naik kelas'? Tulis di komentar! 👇")
    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]} | {sid}")
    except Exception as e:
        print(f"  ❌ {sid}: {e}")
