#!/usr/bin/env python3
"""threads_pasang_reply.py — pasang reply sendiri (pola TSC: 2 reply per postingan) ke jadwal
Threads yang sudah ada.

Pakai:
  python3 threads_pasang_reply.py berkas.json            # dry-run
  python3 threads_pasang_reply.py berkas.json --go       # PUT ke Repliz + baca ulang

Format berkas.json (menulis TAMBAHAN reply, bukan menimpa):
  {"<schedule_id>": ["teks reply tambahan"], ...}

Aturan:
  • Reply yang sudah ada (description/text tidak kosong) DIPERTAHANKAN. Isi berkas = tambahan.
  • Total reply setelah ditambah harus <= 2 (kecuali --paksa). Kalau sudah 2 → SKIP.
  • Teks tambahan maks 500 char (batas Threads), tanpa CJK (guard repliz_client).
  • Payload PUT = objek jadwal utuh hasil GET (PATCH /public/schedule balas 404 di Repliz).
"""
import argparse
import json
import sys
import time

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
from repliz_client import get_client  # noqa: E402

MAKS = 500


def isi_ada(d):
    """Reply yang sudah ada dan berisi teks."""
    return [r for r in (d.get("replies") or [])
            if isinstance(r, dict) and ((r.get("description") or r.get("text") or "").strip())]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("berkas")
    ap.add_argument("--go", action="store_true")
    ap.add_argument("--paksa", action="store_true")
    ap.add_argument("--tidur", type=float, default=1.0)
    a = ap.parse_args()

    data = json.load(open(a.berkas))
    c = get_client()
    sukses = lewat = gagal = 0
    for sid, tambahan in data.items():
        if not isinstance(tambahan, list) or not tambahan:
            print(f"❌ {sid}: isi tidak valid")
            gagal += 1
            continue
        salah = False
        for i, r in enumerate(tambahan, 1):
            if not isinstance(r, str) or not r.strip():
                print(f"❌ {sid}: reply tambahan {i} kosong")
                salah = True
            elif len(r) > MAKS:
                print(f"❌ {sid}: reply tambahan {i} {len(r)} char > {MAKS}")
                salah = True
        if salah:
            gagal += 1
            continue

        d = c.get_schedule(sid)
        if isinstance(d, dict) and "docs" in d:
            d = d["docs"][0]
        d = (d.get("data") or d) if isinstance(d, dict) else {}
        judul = (d.get("title") or (d.get("description") or "")[:40]).replace("\n", " ")
        ada = isi_ada(d)
        total = len(ada) + len(tambahan)
        if total > 2 and not a.paksa:
            print(f"⏭️  {sid} | sudah {len(ada)} reply, +{len(tambahan)} = {total} → SKIP | {judul}")
            lewat += 1
            continue
        if len(ada) >= 2 and not a.paksa:
            print(f"⏭️  {sid} | sudah 2 reply berisi → SKIP | {judul}")
            lewat += 1
            continue

        print(f"{'PUT' if a.go else 'DRY'} {sid} | reply lama={len(ada)} +{len(tambahan)} = {total} | {judul}")
        for i, r in enumerate(tambahan, 1):
            print(f"    + ({len(r)}) {r[:120]}{'…' if len(r) > 120 else ''}")
        if not a.go:
            sukses += 1
            continue

        baru = list(d.get("replies") or []) + [{"type": "text", "description": r} for r in tambahan]
        try:
            c.update_schedule(sid, {"replies": baru})
        except Exception as e:
            print(f"    ❌ PUT gagal: {str(e)[:160]}")
            gagal += 1
            continue
        time.sleep(a.tidur)
        d2 = c.get_schedule(sid)
        if isinstance(d2, dict) and "docs" in d2:
            d2 = d2["docs"][0]
        d2 = (d2.get("data") or d2) if isinstance(d2, dict) else {}
        baru2 = isi_ada(d2)
        teks_akhir = [(x.get("description") or x.get("text") or "") for x in baru2]
        ok = len(baru2) == total and all(t in teks_akhir for t in tambahan)
        print(f"    {'✅' if ok else '⚠️'} tersimpan={len(baru2)} status="
              f"{[x.get('status') for x in (d2.get('replies') or [])]} cocok={ok}")
        if ok:
            sukses += 1
        else:
            gagal += 1

    print(f"\nringkas: {sukses} berhasil/siap · {lewat} dilewati · {gagal} masalah")


if __name__ == "__main__":
    main()
