#!/usr/bin/env python3
"""Revisi caption: hapus ** standalone + **teks** jadi teks biasa (Threads/IG tidak render markdown)."""
import sys, json, re, 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

def clean(desc):
    # 1) hapus baris yang isinya hanya ** (standalone)
    lines = [l for l in desc.split("\n") if l.strip() != "**"]
    # 2) inline **teks** → teks (platform tidak render bold)
    txt = "\n".join(lines)
    txt = re.sub(r"\*\*([^*]+)\*\*", r"\1", txt)
    # 3) sisa ** yang nyangkut → hapus
    txt = txt.replace("**", "")
    # rapikan 3+ newline jadi 2
    txt = re.sub(r"\n{3,}", "\n\n", txt).strip()
    return txt

# kumpulkan semua pending dengan **
pend = []
for p in range(1, 80):
    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("status") or "").lower() == "pending" and "**" in (d.get("description") or ""):
            pend.append(d)

print(f"jadwal pending dengan **: {len(pend)}")
fixed = 0
for d in pend:
    desc = d.get("description") or ""
    new_desc = clean(desc)
    if new_desc == desc:
        continue
    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(d["id"], payload)
        fixed += 1
        print(f"  ✅ {d.get('scheduleAt')} | {(d.get('account') or {}).get('name','?')}")
    except Exception as e:
        print(f"  ❌ {d['id']}: {e}")
print(f"\n📊 Total di-revisi: {fixed}")
