#!/usr/bin/env python3
"""Post generated images to Threads @ukyhandoko via Repliz
   ── Menggunakan URL (upload ke WP dulu), bukan base64! ──"""
import json, urllib.request, os, time, requests
from datetime import datetime, timedelta

from repliz_client import HEADERS, BASE, ACC
ACCOUNT_ID = ACC.UKY_THREADS

IMG_DIR = '/home/mantapman/.hermes/profiles/atun/workspace/uky_threads_images'

# WordPress untuk media hosting
WP_URL = 'https://studiosoft.id/wp-json/wp/v2/media'
WP_USER = 'bambangbot'
WP_PASS = 'q26r RePo BVy6 pwU2 F3z7 ouyl'

# Slot WIB → UTC conversion
SLOTS_WIB = [
    ('2026-07-23T22:00:00', '22:00 WIB'),
    ('2026-07-23T23:00:00', '23:00 WIB'),
    ('2026-07-24T05:00:00', '05:00 WIB'),
    ('2026-07-24T08:00:00', '08:00 WIB'),
    ('2026-07-24T11:00:00', '11:00 WIB'),
    ('2026-07-24T14:00:00', '14:00 WIB'),
    ('2026-07-24T17:00:00', '17:00 WIB'),
    ('2026-07-24T20:00:00', '20:00 WIB'),
    ('2026-07-24T23:00:00', '23:00 WIB'),
    ('2026-07-25T05:00:00', '05:00 WIB'),
    ('2026-07-25T08:00:00', '08:00 WIB'),
    ('2026-07-25T11:00:00', '11:00 WIB'),
    ('2026-07-25T14:00:00', '14:00 WIB'),
    ('2026-07-25T17:00:00', '17:00 WIB'),
    ('2026-07-25T20:00:00', '20:00 WIB'),
    ('2026-07-25T23:00:00', '23:00 WIB'),
    ('2026-07-26T05:00:00', '05:00 WIB'),
    ('2026-07-26T08:00:00', '08:00 WIB'),
    ('2026-07-26T11:00:00', '11:00 WIB'),
    ('2026-07-26T14:00:00', '14:00 WIB'),
]

def wib_to_utc(wib_str):
    dt = datetime.strptime(wib_str, '%Y-%m-%dT%H:%M:%S')
    dt_utc = dt - timedelta(hours=7)
    return dt_utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')

def upload_to_wp(filepath, filename):
    """FIXED 21/08: semua image → server OpenClaw (mantapserver), NO WP, NO base64."""
    from repliz_client import upload_image_to_server
    return upload_image_to_server(filepath, filename)

def post_image(fpath, title, slot_utc, fname):
    """Upload ke WP dulu, baru schedule ke Repliz dengan URL"""
    image_url = upload_to_wp(fpath, fname)
    
    payload = {
        'title': title,
        'description': title,
        'type': 'image',
        'medias': [{'url': image_url, 'type': 'image', 'alt': title}],
        'scheduleAt': slot_utc,
        'accountId': ACCOUNT_ID,
    }
    
    url = BASE + '/public/schedule'
    req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers=HEADERS, method='POST')
    with urllib.request.urlopen(req, timeout=120) as resp:
        data = json.loads(resp.read())
        return data.get('_id') or data.get('id') or 'ok'

def run():
    files = sorted(os.listdir(IMG_DIR))
    print(f'📦 Akan posting {len(files)} gambar ke Threads @ukyhandoko')
    print()
    
    success = 0
    for i, (fname, (slot_wib, slot_label)) in enumerate(zip(files, SLOTS_WIB)):
        fpath = os.path.join(IMG_DIR, fname)
        if not os.path.isfile(fpath):
            continue
        
        slot_utc = wib_to_utc(slot_wib)
        name_noext = fname.replace('.png', '').replace('.jpg', '')
        title = ' '.join(name_noext.split('_')[1:]).title()
        
        try:
            sid = post_image(fpath, title, slot_utc, fname)
            print(f'  ✅ [{i+1:2d}] {fname:35s} @ {slot_label}')
            success += 1
        except urllib.error.HTTPError as e:
            body = e.read().decode()
            print(f'  ❌ [{i+1:2d}] {fname:35s} @ {slot_label} | HTTP {e.code}: {body[:100]}')
        except Exception as e:
            print(f'  ❌ [{i+1:2d}] {fname:35s} @ {slot_label} | {str(e)[:100]}')
        
        if i < len(files) - 1:
            time.sleep(1)
    
    print()
    print(f'✅ {success}/{len(files)} gambar berhasil dijadwalkan!')
    print(f'📎 Threads @ukyhandoko — Account ID: {ACCOUNT_ID}')
    
    # Summary by color
    blue = [f for f in files if 'blue' in f]
    white = [f for f in files if 'white' in f]
    orange = [f for f in files if 'orange' in f]
    print(f'\n📊 Ringkasan per background:')
    print(f'   🔵 Biru (#1E40AF):  {len(blue)} gambar')
    print(f'   ⚪ Putih (#FFFFFF): {len(white)} gambar')
    print(f'   🟠 Orange (#F97316): {len(orange)} gambar')

if __name__ == '__main__':
    run()

