#!/usr/bin/env python3
"""
Pangkas caption Threads yang >500 char (batas maksimal Threads) — FIXED 11 Sep 2026.
Pertahankan: pembuka, link (kalau ada), ajakan diskusi, sebagian hashtag.
"""
import sys, json, re, urllib.request
sys.path.insert(0, "/home/mantapman/.openclaw/workspace-atun")
from repliz_client import HEADERS, BASE

LIMIT = 500
AKUN = {"6a334e89c5ff4ce3a3225a48": "@ukyhandoko", "6a335b9ec5ff4ce3a3225c2a": "StudioSoft"}

def pangkas(text):
    """Pangkas caption ke <=500 char, pertahankan link + ajakan + hashtag."""
    text = text.strip()
    if len(text) <= LIMIT:
        return text
    # pisahkan hashtag di akhir
    tag_match = re.search(r'(\n\s*#[^\n]*(?:\s+#[^\n]*)*)\s*$', text)
    tags = ""
    body = text
    if tag_match:
        tags = tag_match.group(1).strip()
        body = text[:tag_match.start()].strip()
    # ambil hashtag maksimal 4 biar hemat
    tag_list = re.findall(r'#\w+', tags)
    if tag_list:
        tags = " ".join(tag_list[:4])
    # link
    link_match = re.search(r'https?://\S+', body)
    link = link_match.group(0) if link_match else ""
    # ajakan diskusi (cari kalimat tanya/ajakan di akhir)
    ajakan = ""
    for pat in [r'[^\n]*komentar[^\n]*', r'[^\n]*diskusi[^\n]*', r'[^\n]*pendapat[^\n]*', r'[^\n]*cerita[^\n]*']:
        m = re.findall(pat, body, re.I)
        if m:
            ajakan = m[-1].strip()
            break
    # hitung budget
    extra = len(link) + len(ajakan) + len(tags) + 8
    budget = LIMIT - extra
    if budget < 100:
        budget = 100
    # ambil isi utama: buang baris yang mengandung link/ajakan
    lines = [l for l in body.split("\n") if l.strip()]
    inti = []
    for l in lines:
        if link and link in l:
            continue
        if ajakan and ajakan[:30] in l:
            continue
        inti.append(l)
    core = "\n".join(inti).strip()
    if len(core) > budget:
        # potong dari TENGAH — pertahankan pembuka + kesimpulan (biar cerita tetap utuh maknanya)
        head_len = int(budget * 0.55)
        tail_len = int(budget * 0.40)
        head = core[:head_len].rsplit(" ", 1)[0]
        tail = core[-tail_len:]
        tail = tail.split(" ", 1)[-1] if " " in tail else tail
        core = head + "\n…\n" + tail
        if len(core) > budget:
            core = core[:budget].rsplit(" ", 1)[0]
    parts = [core]
    if link:
        parts.append(link)
    if ajakan:
        parts.append(ajakan)
    if tags:
        parts.append(tags)
    hasil = "\n\n".join(parts)
    if len(hasil) > LIMIT:
        hasil = hasil[:LIMIT-1].rsplit(" ", 1)[0] + "…"
    return hasil

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()
targets = []
for accid, nm in AKUN.items():
    for d in docs:
        if d.get("accountId") == accid and (d.get("status") or "").lower() == "pending":
            desc = d.get("description") or ""
            if len(desc) > LIMIT:
                targets.append((d, len(desc)))

print(f"jadwal >500 char: {len(targets)}\n")
fixed = 0
for d, n in targets:
    new = pangkas(d.get("description") or "")
    ok = len(new) <= LIMIT
    print(f"  {n} → {len(new)} char | {(d.get('title') or '')[:40]} | {'✅' if ok else '❌'}")
    if len(sys.argv) > 1 and sys.argv[1] == "exec" and ok:
        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)
            fixed += 1
        except Exception as e:
            print(f"    ❌ {d['id']}: {e}")
if len(sys.argv) > 1 and sys.argv[1] == "exec":
    print(f"\n📊 dipangkas: {fixed}")
else:
    print("\n(dry-run — jalankan dengan 'exec')")
