"""
Retry: Thread #2 dari threads_nested3_v4.py — A/B Testing (@ss)
"""
import base64, json, urllib.request
from datetime import datetime, timedelta, timezone

AUTH = 'NDY1NDYwOTg2Njpzb09vSDJJUnk2QmthSXJIU0FmMW5HbHkyUmNvaXc5Wg=='
HEADERS = {'Authorization': AUTH, 'Content-Type': 'application/json'}
BASE = 'https://api.repliz.com'

A = {
    'uky':      '6a334e89c5ff4ce3a3225a48',
    'ss':       '6a335b9ec5ff4ce3a3225c2a',
    'leit':     '6a5f4af462caae1e04e8b9a6',
    'tsc':      '6a4bbc5920e4f4f195e52960',
    'das':      '6a39e461c5ff4ce3a3233e09',
    'everybe':  '6a44ed1920e4f4f195d8ecf7',
}

poster = 'ss'
post = (
    "Strategi digital "
    "paling underrated: "
    "A/B TESTING. Banyak "
    "keluar duit buat "
    "desain website & "
    "poster, tapi gak "
    "pernah di-test "
    "yang mana lebih "
    "efektif. Ganti "
    "warna tombol, "
    "judul, atau "
    "posisi CTA aja "
    "bisa naikin "
    "konversi 30%. "
    "Test, jangan tebak."
)
l1 = ('uky', (
    "Saya dulu pasang "
    "iklan asal-asalan. "
    "Pas A/B testing "
    "baru tau satu "
    "kata di headline "
    "bisa bedain "
    "ribuan rupiah. "
    "Data > feeling."
))
l2 = ('everybe', (
    "Di website EveryBe "
    "kami juga A/B test. "
    "Ternyata foto "
    "produk dengan "
    "latar putih "
    "konversinya 25% "
    "lebih tinggi. "
    "Hal kecil, "
    "dampak besar."
))
l3 = ('tsc', (
    "Di klinik kami "
    "A/B test konten "
    "edukasi. Ternyata "
    "konten sebelum-"
    "sesudah (bukan "
    "cuma edukasi) "
    "lebih banyak "
    "dibooking. "
    "Data pasien "
    "ngasih tau."
))

now = datetime.now(timezone.utc)
# Slot 06:00 WIB = 23:00 UTC prev day, tapi kita schedule ke besok
schedule_at = (now + timedelta(days=1)).strftime('%Y-%m-%dT06:00:00.000Z')

payload = {
    'accountId': A['ss'],
    'title': '',
    'description': post.strip(),
    'scheduleAt': schedule_at,
    'type': 'text',
    'medias': [],
    'topic': '',
    'replies': [
        {
            'accountId': A['uky'],
            'description': l1[1].strip(),
            'replies': [
                {
                    'accountId': A['everybe'],
                    'description': l2[1].strip(),
                    'replies': [
                        {
                            'accountId': A['tsc'],
                            'description': l3[1].strip(),
                        }
                    ]
                }
            ]
        }
    ]
}

data = json.dumps(payload).encode('utf-8')
req = urllib.request.Request(f'{BASE}/public/schedule', data=data, headers=HEADERS, method='POST')

# Increase timeout for retry
try:
    with urllib.request.urlopen(req, timeout=60) as resp:
        result = json.loads(resp.read())
        sid = result.get('scheduleId', result)
        print(f"✅ Retry sukses! Schedule ID: {sid}")
        print(f"📅 @ss → A/B Testing → 06:00 WIB")
except Exception as e:
    print(f"❌ Retry gagal: {e}")
