#!/usr/bin/env python3
"""
Post images satu per satu via subprocess biar gak stuck.
Setiap image di-post sendiri-sendiri via curl.
"""
import base64, json, os, subprocess, sys, time
from datetime import datetime, timedelta

ACCESS_KEY = '4654609866'
SECRET_KEY = 'soOoH2IRy6BkaIrHSAf1nGly2Rcoiw9Z'
AUTH_B64 = base64.b64encode(f'{ACCESS_KEY}:{SECRET_KEY}'.encode()).decode()
BASE = 'https://api.repliz.com/public/schedule'

ACCOUNTS = {
    'threads': '6a334e89c5ff4ce3a3225a48',
    'linkedin': '6a334c49c5ff4ce3a32259c9',
}

IMG_DIR = '/home/mantapman/.hermes/profiles/atun/workspace/uky3_output'
LOG_FILE = '/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_one(account_id, fpath, title, slot_utc, timeout=300):
    """Post 1 image via urllib"""
    img_url = upload_image_to_server(fpath)
    # FIX 21/08: no base64 — image via server OpenClaw
    
    payload = json.dumps({
        'title': title,
        'description': title,
        'type': 'image',
        'medias': [{'url': img_url, 'type': 'image', 'alt': title}],
        'scheduleAt': slot_utc,
        'accountId': account_id,
    }).encode()
    
    import urllib.request

from repliz_client import upload_image_to_server, AUTH_HEADER
AUTH_B64 = AUTH_HEADER
BASE = 'https://api.repliz.com/public/schedule'

ACCOUNTS = {
    'threads': '6a334e89c5ff4ce3a3225a48',
    'linkedin': '6a334c49c5ff4ce3a32259c9',
}

IMG_DIR = '/home/mantapman/.hermes/profiles/atun/workspace/uky3_output'
LOG_FILE = '/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_one(account_id, fpath, title, slot_utc, timeout=300):
    """Post 1 image via urllib"""
    img_url = upload_image_to_server(fpath)
    # FIX 21/08: no base64 — image via server OpenClaw
    
    payload = json.dumps({
        'title': title,
        'description': title,
        'type': 'image',
        'medias': [{'url': img_url, 'type': 'image', 'alt': title}],
        'scheduleAt': slot_utc,
        'accountId': account_id,
    }).encode()
    
    import urllib.request
    req = urllib.request.Request(BASE, data=payload,
        headers={'Authorization': f'Basic {AUTH_B64}', 'Content-Type': 'application/json'},
        method='POST')
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        data = json.loads(resp.read())
        return data.get('scheduleId') or data.get('_id') or 'ok'

def run():
    # Threads: 51 images but limited to 30 slots (biru + putih)
    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',
        '2026-07-29T05:00:00', '2026-07-29T08:00:00', '2026-07-29T11:00:00',
        '2026-07-29T14:00:00', '2026-07-29T17:00:00', '2026-07-29T20:00:00',
        '2026-07-29T23:00:00',
        '2026-07-30T05:00:00', '2026-07-30T08:00:00', '2026-07-30T11:00:00',
        '2026-07-30T14:00:00', '2026-07-30T17:00:00', '2026-07-30T20:00:00',
        '2026-07-30T23:00:00',
        '2026-07-31T05:00:00', '2026-07-31T08:00:00', '2026-07-31T11:00:00',
        '2026-07-31T14:00:00', '2026-07-31T17:00:00', '2026-07-31T20:00:00',
        '2026-07-31T23:00:00',
        '2026-08-01T05:00:00', '2026-08-01T08:00:00', '2026-08-01T11:00:00',
        '2026-08-01T14:00:00',
    ]
    
    linkedin_slots = [
        '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', '2026-07-29T05:30:00',
    ]
    
    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')])
    
    all_threads = files_biru + files_putih + files_orange  # 51
    all_linkedin = files_biru[:15]
    
    with open(LOG_FILE, 'w') as log:
        log.write(f"Schedule: {len(all_threads)} Threads + {len(all_linkedin)} LinkedIn\n\n")
        log.flush()
        
        # === THREADS ===
        log.write("=== THREADS ===\n")
        t_ok = 0
        for i, (fname, slot_wib) in enumerate(zip(all_threads, threads_slots)):
            fpath = os.path.join(IMG_DIR, fname)
            if not os.path.exists(fpath):
                continue
            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_one(ACCOUNTS['threads'], fpath, title, slot_utc, timeout=300)
                log.write(f"✅ [{i+1:2d}] Threads: {fname:35s} @ {slot_wib}\n")
                t_ok += 1
            except Exception as e:
                log.write(f"❌ [{i+1:2d}] Threads: {fname:35s} @ {slot_wib} | {str(e)[:80]}\n")
            log.flush()
            time.sleep(2)
        
        # === LINKEDIN ===
        log.write("\n=== LINKEDIN ===\n")
        l_ok = 0
        for i, (fname, slot_wib) in enumerate(zip(all_linkedin, linkedin_slots)):
            fpath = os.path.join(IMG_DIR, fname)
            if not os.path.exists(fpath):
                continue
            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_one(ACCOUNTS['linkedin'], fpath, title, slot_utc, timeout=300)
                log.write(f"✅ [{i+1:2d}] LinkedIn: {fname:35s} @ {slot_wib}\n")
                l_ok += 1
            except Exception as e:
                log.write(f"❌ [{i+1:2d}] LinkedIn: {fname:35s} @ {slot_wib} | {str(e)[:80]}\n")
            log.flush()
            time.sleep(2)
        
        log.write(f"\n✅ Threads: {t_ok} | LinkedIn: {l_ok}\n")

if __name__ == '__main__':
    with open(LOG_FILE, 'w') as f:
        f.write("Starting...\n")
    run()

