#!/usr/bin/env python3
"""Perbaiki 3 jadwal skincare EveryBe (19-21 Sep): caption netral, tanpa produk salah."""
import sys, json, re, urllib.request
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE

EB = '6a44ed1920e4f4f195d8ecf7'

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

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("accountId") == EB and (d.get("status") or "").lower() == "pending":
            at = d.get("scheduleAt") or ""
            if at[:10] >= "2026-09-02":
                pend.append(d)

# 3 judul skincare (tidak termasuk kebugaran/kewanitaan)
SKINCARE = ["Kulit Glowing", "Body Lotion vs Tone Up", "Skin Barrier"]

updated = 0
for d in sorted(pend, key=lambda x: x.get("scheduleAt") or ""):
    desc = d.get("description") or ""
    m_judul = re.search(r"Edukasi hari ini: (.+?)\.", desc)
    judul = m_judul.group(1) if m_judul else ""
    if not any(s in judul for s in SKINCARE):
        continue
    m = re.search(r"https?://\S+", desc)
    link = m.group(0) if m else "https://www.everybeofficial.com"
    new_caption = (
        f"Edukasi hari ini: {judul}. 🌿\n\n"
        f"Perawatan yang tepat dimulai dari memahami kebutuhan kulitmu sendiri. Banyak yang salah pilih produk karena ikut tren, padahal kulit tiap orang punya kondisi yang berbeda-beda.\n\n"
        f"Simak artikel lengkapnya di sini 👇\n{link}\n\n"
        f"Menurut kamu, kebiasaan sehat apa yang paling susah dijaga? Share di komentar! 👇\n\n"
        f"#EveryBe #EdukasiKesehatan #SelfCare #PerawatanKulit"
    )
    payload = {
        "accountId": d.get("accountId"),
        "title": d.get("title", ""),
        "description": new_caption,
        "topic": d.get("topic", ""),
        "type": d.get("type", ""),
        "medias": d.get("medias") or [],
        "scheduleAt": d.get("scheduleAt"),
        "replies": d.get("replies") or [],
    }
    try:
        st = put(d["id"], payload)
        updated += 1
        print(f"  ✅ {d.get('scheduleAt')[:10]} | {judul[:50]} | netral")
    except Exception as e:
        print(f"  ❌ {d.get('scheduleAt')[:10]} | {e}")

print(f"\n📊 Updated skincare: {updated}")
