#!/usr/bin/env python3
"""
Perbaiki caption Threads uky & StudioSoft:
1. Tambahkan ajakan diskusi kalau belum ada
2. Pastikan ≤500 char
"""
import sys, json, re, urllib.request
sys.path.insert(0, "/home/mantapman/.openclaw/workspace-atun")
from repliz_client import HEADERS, BASE
from pangkas_threads import batasi

AKUN = {"6a334e89c5ff4ce3a3225a48": "@ukyhandoko", "6a335b9ec5ff4ce3a3225c2a": "StudioSoft"}
AJAKAN = [
    "Menurut kamu, bagian mana yang paling relevan buat bisnismu? Cerita di komentar! 👇",
    "Gimana pendapat kamu soal ini? Yuk diskusi di kolom komentar! 👇",
    "Setuju atau nggak? Tulis pendapatmu di komentar! 👇",
    "Punya pengalaman serupa? Share di komentar, yuk! 👇",
]
HAS_AJAKAN = re.compile(r'(komentar|diskusi|pendapat|setuju|cerita di|share di|jujur|jawab)', re.I)

def get_all():
    docs = []
    for p in range(1, 90):
        raw = urllib.request.Request(f"{BASE}/public/schedule?page={p}&limit=100", headers=HEADERS)
        with urllib.request.urlopen(raw, timeout=30) as r:
            docs.extend(json.load(r)["docs"])
    return docs

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

docs = get_all()
fixed_ajakan = fixed_len = 0
import random
for accid, nm in AKUN.items():
    pend = [d for d in docs if d.get("accountId") == accid and (d.get("status") or "").lower() == "pending"]
    for d in pend:
        desc = d.get("description") or ""
        new = desc
        needs = False
        if not HAS_AJAKAN.search(desc):
            new = desc.rstrip() + "\n\n" + random.choice(AJAKAN)
            needs = True
        new = batasi(new)
        if len(new) > 500:
            new = batasi(new)
        if new != desc:
            payload = {
                "accountId": d.get("accountId"), "title": d.get("title", ""),
                "description": new, "topic": d.get("topic", ""), "type": d.get("type", ""),
                "medias": d.get("medias") or [], "scheduleAt": d.get("scheduleAt"),
                "replies": d.get("replies") or [],
            }
            try:
                put(d["id"], payload)
                if needs: fixed_ajakan += 1
                fixed_len += 1
                print(f"  ✅ {nm} | {d.get('scheduleAt')} | {'+ajakan ' if needs else ''}{len(desc)}→{len(new)} char")
            except Exception as e:
                print(f"  ❌ {d['id']}: {e}")
print(f"\n📊 diperbaiki: {fixed_len} (tambah ajakan: {fixed_ajakan})")
