#!/usr/bin/env python3
"""Perbaiki carousel Flek yang error: PNG besar → JPEG ringan, recreate di slot 09:00 berikutnya."""
import sys, os, json, urllib.request
from datetime import datetime, timedelta, timezone
from PIL import Image
sys.path.insert(0, "/home/mantapman/.openclaw/workspace-atun")
from repliz_client import HEADERS, BASE

WIB = timezone(timedelta(hours=7))
IMG_DIR = "/home/mantapman/.openclaw/workspace-atun/openclaw-img"
IMG_URL = "https://mantapserver.tail3947bb.ts.net/openclaw-img/"
IG_TSC = "6a86a7e062caae1e04ff8244"
TH_TSC = "6a4bbc5920e4f4f195e52960"

# 1) konversi PNG → JPEG ringan
print("=== 1) Konversi PNG → JPEG ringan ===")
for i in (1, 2, 3):
    src = os.path.join(IMG_DIR, f"tsc_flek_0{i}.png")
    dst = os.path.join(IMG_DIR, f"tsc_flek_0{i}.jpg")
    img = Image.open(src)
    if img.mode in ("RGBA", "LA", "P"):
        bg = Image.new("RGB", img.size, (255, 255, 255))
        img = img.convert("RGBA")
        bg.paste(img, mask=img.split()[-1])
        img = bg
    else:
        img = img.convert("RGB")
    q = 85
    while q >= 60:
        img.save(dst, "JPEG", quality=q, optimize=True, progressive=True)
        if os.path.getsize(dst) <= 300 * 1024 or q <= 60:
            break
        q -= 5
    print(f"  {os.path.getsize(src)//1024} KB → {os.path.getsize(dst)//1024} KB | tsc_flek_0{i}.jpg")

# 2) hapus jadwal error (12 Sep)
print("\n=== 2) Hapus jadwal error 12 Sep ===")
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"])
to_del = [d for d in docs if d.get("accountId") in (IG_TSC, TH_TSC) and (d.get("scheduleAt") or "").startswith("2026-09-12T02:")]
for d in to_del:
    req = urllib.request.Request(f"{BASE}/public/schedule/{d['id']}", headers=HEADERS, method="DELETE")
    with urllib.request.urlopen(req, timeout=30) as r:
        print(f"  🗑️ del {d['id']} ({d.get('accountId')[:8]}) HTTP {r.status}")

# 3) cek slot 09:00 kosong berikutnya
print("\n=== 3) Cari slot 09:00 kosong ===")
docs2 = []
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:
        docs2.extend(json.load(r)["docs"])

def slot09_free(accid):
    busy = set()
    for d in docs2:
        if d.get("accountId") == accid and (d.get("status") or "").lower() == "pending":
            at = d.get("scheduleAt") or ""
            try:
                dt = datetime.fromisoformat(at.replace("Z", "+00:00")).astimezone(WIB)
                if dt.hour == 9:
                    busy.add(dt.strftime("%Y-%m-%d"))
            except Exception:
                continue
    day = datetime.now(WIB).replace(hour=9, minute=0, second=0, microsecond=0)
    for _ in range(14):
        if day > datetime.now(WIB) and day.strftime("%Y-%m-%d") not in busy:
            return day
        day += timedelta(days=1)
    return None

CAP = """Flek di wajah bikin nggak percaya diri? Mencegahnya bisa dimulai dari kebiasaan sederhana! ✨

3 KEBIASAAN MENCEGAH FLEK:
1️⃣ Gunakan sunscreen setiap pagi — termasuk saat di dalam ruangan
2️⃣ Reapply saat banyak beraktivitas di luar ruangan
3️⃣ Hindari memencet jerawat & iritasi berulang

RAWAT KULIT DENGAN LEMBUT:
• Pilih skincare sesuai kebutuhan kulit
• Jaga kelembapan kulit setiap hari
• Konsultasikan flek yang menetap dengan ahlinya

Kulit sehat dimulai dari kebiasaan kecil yang konsisten.

Punya pengalaman dengan flek? Cerita di komentar, yuk diskusi! 👇

📲 Konsultasi & booking via WhatsApp: 0851-1744-4417

#theskincodeclinic #flek #hiperpigmentasi #dokterkulit #klinikkulit #perawatankulit #kulitsehat #sunscreen"""

SLIDES = [{"url": IMG_URL + f"tsc_flek_0{i}.jpg", "type": "image", "alt": f"tsc_flek_0{i}"} for i in (1, 2, 3)]

ok = fail = 0
for accid, nm in [(IG_TSC, "IG TSC"), (TH_TSC, "Threads TSC")]:
    slot = slot09_free(accid)
    if slot is None:
        print(f"  ❌ {nm}: tidak ada slot 09:00")
        fail += 1
        continue
    at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    payload = {"accountId": accid, "title": "The Skin Code Clinic — Carousel Flek",
               "description": CAP, "topic": "Edukasi Kulit", "type": "album",
               "medias": SLIDES, "scheduleAt": at, "replies": []}
    req = urllib.request.Request(f"{BASE}/public/schedule", data=json.dumps(payload).encode(),
                                 headers={**HEADERS, "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            res = json.load(r)
        ok += 1
        print(f"  ✅ {nm} | {slot.strftime('%d/%m %H:%M WIB')} | id={res.get('_id') or res.get('id') or '?'}")
    except Exception as e:
        fail += 1
        print(f"  ❌ {nm}: {e}")
print(f"\n📊 Total: {ok} OK, {fail} gagal")
