#!/usr/bin/env python3
"""Post all 51 images from uky3_output to Threads & LinkedIn @ukyhandoko"""
import urllib.request, base64, json, os, time, sys
from datetime import datetime, timedelta
from PIL import Image

from repliz_client import upload_image_to_server, AUTH_HEADER, ACC
AUTH = AUTH_HEADER
BASE = 'https://api.repliz.com/public/schedule'
ACCOUNTS = {'threads': ACC.UKY_THREADS, 'linkedin': ACC.STUDIOSOFT_LINKEDIN}


ACCOUNTS = {
    'threads': '6a334e89c5ff4ce3a3225a48',
    'linkedin': '6a334c49c5ff4ce3a32259c9',  # LinkedIn @ukyhandoko
}

IMG_DIR = '/home/mantapman/.hermes/profiles/atun/workspace/uky3_output'
LOG = '/home/mantapman/.hermes/profiles/atun/workspace/post_uky3_log.txt'

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 post_to_repliz(account_id, fpath, title, schedule_at):
    img_url = upload_image_to_server(fpath)
    # FIX 21/08: no base64 — image via server OpenClaw
    
    payload = {
        'title': title,
        'description': title,
        'type': 'image',
        'medias': [{'url': img_url, 'type': 'image', 'alt': title}],
        'scheduleAt': schedule_at,
        'accountId': account_id,
    }
    
    body = json.dumps(payload).encode()
    req = urllib.request.Request(BASE, data=body,
        headers={'Authorization': AUTH, 'Content-Type': 'application/json'}, method='POST')
    with urllib.request.urlopen(req, timeout=180) as resp:
        data = json.loads(resp.read())
        return data.get('scheduleId') or data.get('_id') or 'ok'

def schedule_batch():
    # === SLOT UNTUK THREADS ===
    # Mulai dari slot kosong setelah jadwal sebelumnya (yg terakhir 26 Jul 14:00 WIB)
    threads_slots = [
        '2026-07-26T17:00:00',
        '2026-07-26T20:00:00',
        '2026-07-26T23:00:00',
        '2026-07-27T05:00:00',
        '2026-07-27T08:00:00',
        '2026-07-27T11:00:00',
        '2026-07-27T14:00:00',
        '2026-07-27T17:00:00',
        '2026-07-27T20:00:00',
        '2026-07-27T23:00:00',
        '2026-07-28T05:00:00',
        '2026-07-28T08:00:00',
        '2026-07-28T11:00:00',
        '2026-07-28T14:00:00',
        '2026-07-28T17:00:00',
        '2026-07-28T20:00:00',
        '2026-07-28T23:00:00',
    ]
    
    # === SLOT UNTUK LINKEDIN ===
    linkedin_slots = [
        '2026-07-26T17:30:00',
        '2026-07-27T05:30:00',
        '2026-07-27T08:30:00',
        '2026-07-27T11:30:00',
        '2026-07-27T14:30:00',
        '2026-07-27T17:30:00',
        '2026-07-27T20:30:00',
        '2026-07-27T23:30:00',
        '2026-07-28T05:30:00',
        '2026-07-28T08:30:00',
        '2026-07-28T11:30:00',
        '2026-07-28T14:30:00',
        '2026-07-28T17:30:00',
        '2026-07-28T20:30:00',
        '2026-07-28T23:30:00',
    ]
    
    # Collect all files by group
    files_biru = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('_biru.png')])
    files_putih = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('_putih.png')])
    files_orange = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('_orange.png')])
    
    # For Threads: post all 51 (17×3) but limited by slots
    # Let's start with 17 biru, then putih, then orange
    # Slots cukup untuk 17 image (biru) + sebagian putih
    
    all_threads = files_biru + files_putih + files_orange
    all_linkedin = files_biru[:15]  # 15 untuk linkedin dulu
    
    with open(LOG, 'w') as log:
        log.write(f"Mulai posting {len(all_threads)} ke Threads + {len(all_linkedin)} ke LinkedIn\n")
        log.flush()
        
        # === THREADS ===
        log.write("\n=== THREADS ===\n")
        threads_ok = 0
        for i, (fname, slot_wib) in enumerate(zip(all_threads, threads_slots)):
            fpath = os.path.join(IMG_DIR, fname)
            slot_utc = wib_to_utc(slot_wib)
            
            name = fname.replace('_biru.png','').replace('_putih.png','').replace('_orange.png','')
            title = name.replace('_', ' ').title()
            
            try:
                sid = post_to_repliz(ACCOUNTS['threads'], fpath, title, slot_utc)
                log.write(f"  ✅ [{i+1:2d}] {fname:35s} -> Threads @ {slot_wib} (sid: {str(sid)[:12]})\n")
                threads_ok += 1
            except Exception as e:
                log.write(f"  ❌ [{i+1:2d}] {fname:35s} -> Threads @ {slot_wib} | {type(e).__name__}: {str(e)[:80]}\n")
            log.flush()
            time.sleep(3)
        
        # === LINKEDIN ===
        log.write("\n=== LINKEDIN ===\n")
        lin_ok = 0
        for i, (fname, slot_wib) in enumerate(zip(all_linkedin, linkedin_slots)):
            fpath = os.path.join(IMG_DIR, fname)
            slot_utc = wib_to_utc(slot_wib)
            
            name = fname.replace('_biru.png','').replace('_putih.png','').replace('_orange.png','')
            title = name.replace('_', ' ').title()
            
            try:
                sid = post_to_repliz(ACCOUNTS['linkedin'], fpath, title, slot_utc)
                log.write(f"  ✅ [{i+1:2d}] {fname:35s} -> LinkedIn @ {slot_wib} (sid: {str(sid)[:12]})\n")
                lin_ok += 1
            except Exception as e:
                log.write(f"  ❌ [{i+1:2d}] {fname:35s} -> LinkedIn @ {slot_wib} | {type(e).__name__}: {str(e)[:80]}\n")
            log.flush()
            time.sleep(3)
        
        log.write(f"\n✅ SELESAI! Threads: {threads_ok}/{len(all_threads[:len(threads_slots)])} | LinkedIn: {lin_ok}/{len(all_linkedin)}\n")

if __name__ == '__main__':
    schedule_batch()
    with open(LOG) as f:
        print(f.read())

