#!/usr/bin/env python3
"""Post remaining 19 images to Threads @ukyhandoko"""
import urllib.request, base64, json, os, time, sys
from datetime import datetime, timedelta

from repliz_client import upload_image_to_server, ACC
ACCOUNT_ID = ACC.UKY_THREADS
BASE = 'https://api.repliz.com/public/schedule'


SLOTS_WIB = [
    '2026-07-23T23:00:00',
    '2026-07-24T05:00:00', '2026-07-24T08:00:00', '2026-07-24T11:00:00',
    '2026-07-24T14:00:00', '2026-07-24T17:00:00', '2026-07-24T20:00:00', '2026-07-24T23:00:00',
    '2026-07-25T05:00:00', '2026-07-25T08:00:00', '2026-07-25T11:00:00', '2026-07-25T14:00:00',
    '2026-07-25T17:00:00', '2026-07-25T20:00:00', '2026-07-25T23:00:00', '2026-07-26T05:00:00',
    '2026-07-26T08:00:00', '2026-07-26T11:00:00', '2026-07-26T14:00:00',
]

files = [
    '02_blue_website_optimasi.png', '03_blue_3_hal_bisnis.png',
    '04_white_leadership.png', '05_white_brand.png', '06_white_gagal.png',
    '07_orange_agency_lain.png', '08_orange_bisnis_marathon.png',
    '09_blue_ai.png', '10_blue_geo.png',
    '11_white_meaning.png', '12_white_filosofi.png',
    '13_orange_website.png', '14_orange_kesalahan.png',
    '15_blue_jangan_post.png', '16_blue_personal_branding.png',
    '17_white_mindset.png', '18_white_modal.png',
    '19_orange_klien_ideal.png', '20_orange_klien_pergi.png',
]

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

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

with open(logfile, 'w') as log:
    log.write(f"Mulai posting {len(files)} gambar\n")
    log.flush()
    
    for i, (fname, slot_wib) in enumerate(zip(files, SLOTS_WIB)):
        fpath = os.path.join(IMG_DIR, fname)
        if not os.path.exists(fpath):
            log.write(f"  ❌ [{i+2:2d}] {fname} -> FILE NOT FOUND\n")
            log.flush()
            continue
        
        slot_utc = wib_to_utc(slot_wib)
        
        img_url = upload_image_to_server(fpath)
        # FIX 21/08: no base64 — image via server OpenClaw
        
        title_parts = fname.replace('.png','').split('_')[1:]
        title = ' '.join(title_parts).title()
        
        payload = {
            'title': title,
            'description': title,
            'type': 'image',
            'medias': [{
                'url': img_url,
                'type': 'image',
                'alt': title
            }],
            'scheduleAt': slot_utc,
            'accountId': ACCOUNT_ID,
        }
        
        body = json.dumps(payload).encode()
        req = urllib.request.Request(BASE, data=body,
            headers={'Authorization': auth, 'Content-Type': 'application/json'}, method='POST')
        try:
            with urllib.request.urlopen(req, timeout=180) as resp:
                data = json.loads(resp.read())
                sid = data.get('scheduleId') or 'ok'
            log.write(f"  ✅ [{i+2:2d}] {fname:35s} -> {slot_wib} (sid: {str(sid)[:12]})\n")
        except Exception as e:
            log.write(f"  ❌ [{i+2:2d}] {fname:35s} -> {slot_wib} | {type(e).__name__}: {str(e)[:80]}\n")
        log.flush()
        
        if i < len(files) - 1:
            time.sleep(3)
    
    log.write(f"\n✅ Selesai! {len(files)} gambar diproses.\n")

# Print result
with open(logfile) as f:
    print(f.read())

