#!/usr/bin/env python3
"""Fix pancingan ganda: ganti hook caption jadwal uky_quote_beda_itu_bagus
(hook sebelumnya sudah dipakai di uky_thread_20 / 19 Sep) dengan pancingan
netral yang belum pernah dipakai. Update via PATCH; kalau gagal → delete+recreate.
"""
import json, os, re, sys
from datetime import datetime, timezone, timedelta

ROOT = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, ROOT)
from repliz_client import get_client, ACC
import repliz_openssl_transport
repliz_openssl_transport.install(verbose=False)

SID = "6ab1710202078a414af46615"
ITEM_ID = "uky_quote_beda_itu_bagus"
UKY_T = ACC.UKY_THREADS

BODY = (
    "Saya pernah meniru gaya agency lain biar kelihatan \u201caman\u201d. Ternyata itu keliru. \U0001F4A1\n\n"
    "Waktu semua brand terlihat sama, klien gak punya alasan buat pilih kita. "
    "Yang akhirnya bekerja: berani beda di SATU hal yang penting buat audiens \u2014 bukan di semua hal.\n\n"
    "Beda itu bukan soal sok unik. Beda itu soal punya alasan buat diingat."
)
HOOK = "Kalau harus pilih satu platform untuk fokus tahun ini, pilih yang mana \u2014 dan kenapa?"
CAP = BODY + "\n\n" + HOOK

c = get_client()
print("NEW CAPTION", len(CAP), "chars")
assert len(CAP) <= 500 and "@" not in CAP and "#" not in CAP

cur = c.get_schedule(SID)
print("BEFORE:", cur.get("id"), cur.get("status"), len(cur.get("description") or ""))
print("OLD TAIL:", (cur.get("description") or "")[-120:].replace("\n", " | "))

ok = False
try:
    r = c.update_schedule(SID, {"description": CAP})
    print("PATCH RESP:", json.dumps(r)[:300])
    ok = True
except Exception as e:
    print("PATCH GAGAL:", type(e).__name__, e)

if not ok:
    print("\u2192 fallback: delete + recreate")
    medias = cur.get("medias") or []
    slot = cur.get("scheduleAt")
    print("DELETE:", json.dumps(c.delete_schedule(SID))[:200])
    res = c.create_schedule(UKY_T, CAP, slot, title=cur.get("title") or "",
                            topic=cur.get("topic") or "", type_="image",
                            medias=medias, replies=[])
    print("RECREATE:", json.dumps(res)[:300])
    SID = res.get("scheduleId") or res.get("_id") or res.get("id")

# VERIFIKASI lewat re-list
r = c.get_schedules(page=1, limit=100)
pages = (r["totalDocs"] + 99) // 100
docs = list(r["docs"])
for p in range(2, pages + 1):
    docs.extend(c.get_schedules(page=p, limit=100)["docs"])
hits = []
for d in docs:
    acc = d.get("account") or {}
    if (d.get("accountId") or acc.get("id") or acc.get("_id")) != UKY_T:
        continue
    for m in (d.get("medias") or []):
        if "beda_itu_bagus" in (m.get("url") or ""):
            hits.append(d)
            break
print("\nVERIFIKASI:", len(hits), "jadwal")
for d in hits:
    wib = datetime.fromisoformat(d["scheduleAt"].replace("Z", "+00:00")) + timedelta(hours=7)
    desc = d.get("description") or ""
    print(f"  id={d.get('id')} status={d.get('status')} at={wib.strftime('%Y-%m-%d %H:%M')} WIB chars={len(desc)} replies={len(d.get('replies') or [])}")
    print("  tail:", desc[-110:].replace("\n", " | "))
    assert desc.strip() == CAP.strip(), "caption di server != caption final"
assert len(hits) == 1 and hits[0].get("status") == "pending", "harus 1 & pending"

# UPDATE LOG
lp = os.path.join(ROOT, "image_posting_log.json")
log = json.load(open(lp))
for e in log:
    if e.get("item_id") == ITEM_ID:
        e["caption_chars"] = len(CAP)
        e["caption_final"] = CAP
        e["repliz_ids"]["threads_uky"] = hits[0].get("id")
        e["fix_note"] = "hook diganti (pancingan opini sebelumnya sudah dipakai uky_thread_19/20)"
json.dump(log, open(lp, "w"), indent=2, ensure_ascii=False)
print("\n\u2705 LOG diperbarui; sid final =", hits[0].get("id"))
