#!/usr/bin/env python3
"""Post remaining images 10-20 — pakai URL (no base64!)"""
import urllib.request, json, os, time, sys, requests
from datetime import datetime, timedelta

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

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

# 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'

remaining = [
    ('10_blue_geo.png',              '2026-07-25T05:00:00'),
    ('11_white_meaning.png',         '2026-07-25T08:00:00'),
    ('12_white_filosofi.png',        '2026-07-25T11:00:00'),
    ('13_orange_website.png',        '2026-07-25T14:00:00'),
    ('14_orange_kesalahan.png',      '2026-07-25T17:00:00'),
    ('15_blue_jangan_post.png',      '2026-07-25T20:00:00'),
    ('16_blue_personal_branding.png','2026-07-25T23:00:00'),
    ('17_white_mindset.png',         '2026-07-26T05:00:00'),
    ('18_white_modal.png',           '2026-07-26T08:00:00'),
    ('19_orange_klien_ideal.png',    '2026-07-26T11:00:00'),
    ('20_orange_klien_pergi.png',    '2026-07-26T14:00:00'),
]

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')

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)

with open(LOG, 'w') as log:
    log.write('Posting remaining images via URL...\n')
    log.flush()
    
    for fname, slot_wib in remaining:
        fpath = os.path.join(IMG_DIR, fname)
        slot_utc = wib_to_utc(slot_wib)
        
        # Upload ke WP dulu
        try:
            image_url = upload_to_wp(fpath, fname)
        except Exception as e:
            log.write(f'  ❌ {fname:35s} -> {slot_wib} | WP upload failed: {str(e)[:60]}\n')
            log.flush()
            time.sleep(3)
            continue
        
        title = ' '.join(fname.replace('.png','').split('_')[1:]).title()
        
        payload = {
            'title': title,
            'description': title,
            'type': 'image',
            'medias': [{'url': image_url, 'type': 'image', 'alt': title}],
            'scheduleAt': slot_utc,
            'accountId': ACCOUNT_ID,
        }
        
        body = json.dumps(payload).encode()
        req = urllib.request.Request(BASE, data=body,
            headers=HEADERS, 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'  ✅ {fname:35s} -> {slot_wib} (sid: {str(sid)[:12]}) | URL✅\n')
        except Exception as e:
            log.write(f'  ❌ {fname:35s} -> {slot_wib} | {type(e).__name__}: {str(e)[:80]}\n')
        log.flush()
        time.sleep(3)
    
    log.write('\n✅ Selesai!\n')

with open(LOG) as f:
    print(f.read())

