#!/usr/bin/env python3
"""Upload images to WordPress, then post URLs to Repliz (no base64!)"""
import os, json, urllib.request, time, requests
from datetime import datetime, timedelta

from repliz_client import ACC, HEADERS

ACCOUNT_ID = ACC.UKY_THREADS
IMG_DIR = '/home/mantapman/.hermes/profiles/atun/workspace/uky_threads_images'
LOG = '/home/mantapman/.hermes/profiles/atun/workspace/post_threads_images_url.log'

# WP credentials (Studiosoft — upload media here)
WP_URL = 'https://studiosoft.id/wp-json/wp/v2/media'
WP_USER = 'bambangbot'
WP_PASS = 'q26r RePo BVy6 pwU2 F3z7 ouyl'

API = 'https://api.repliz.com/public/schedule'

SCHEDULES = [
    ('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)

def post_to_repliz(image_url, title, slot_utc):
    """Post ke Repliz dengan URL (no base64!)"""
    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(
        API, data=body, headers=HEADERS, method='POST'
    )
    with urllib.request.urlopen(req, timeout=60) as resp:
        data = json.loads(resp.read())
        return data.get('scheduleId') or data.get('_id') or 'ok'

# === MAIN ===
log_lines = [f"=== Posting {len(SCHEDULES)} images via URL ==="]
print(log_lines[0])

success = 0
for fname, slot_wib in SCHEDULES:
    fpath = os.path.join(IMG_DIR, fname)
    if not os.path.isfile(fpath):
        msg = f"  ⚠️ {fname} — file not found"
        log_lines.append(msg); print(msg)
        continue
    
    title = ' '.join(fname.replace('.png','').split('_')[1:]).title()
    slot_utc = wib_to_utc(slot_wib)
    
    try:
        # 1. Upload to WP
        image_url = upload_to_wp(fpath, fname)
        
        # 2. Post to Repliz with URL
        sid = post_to_repliz(image_url, title, slot_utc)
        
        msg = f"  ✅ {fname:35s} @ {slot_wib} | {title} | {image_url}"
        log_lines.append(msg); print(msg)
        success += 1
    except Exception as e:
        msg = f"  ❌ {fname:35s} @ {slot_wib} | {str(e)[:100]}"
        log_lines.append(msg); print(msg)
    
    time.sleep(2)

# Summary
summary = f"\n✅ {success}/{len(SCHEDULES)} berhasil!"
log_lines.append(summary); print(summary)

with open(LOG, 'w') as f:
    f.write('\n'.join(log_lines))
