#!/usr/bin/env python3
"""Post images with 600s timeout — 1 at a time, logging each."""
import urllib.request, base64, json, os, time
from datetime import datetime, timedelta

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

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

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

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

def post_one_auth(account_id, fpath, title, slot_utc):
    img_url = upload_image_to_server(fpath)
    # FIX 21/08: no base64 — image via server OpenClaw
    payload = json.dumps({
        'title': title, 'type': 'image',
        'medias': [{'url': img_url, 'type': 'image', 'alt': title}],
        'scheduleAt': slot_utc, 'accountId': account_id,
    }).encode()
    
    # Use a fresh connection each time
    req = urllib.request.Request(BASE, data=payload,
        headers={'Authorization': f'Basic {AUTH_STR}', 'Content-Type': 'application/json'},
        method='POST')
    with urllib.request.urlopen(req, timeout=600) as resp:
        d = json.loads(resp.read())
        return d.get('scheduleId') or d.get('_id') or 'ok'

def run():
    # Threads slots (after yg udah terposting jadwal sebelumnya)
    threads_slots = [
        '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',
        '2026-08-01T17:00:00', '2026-08-01T20: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')])
    
    # Skip the 4 already posted (bedaa, belajar, content, data already posted above)
    # Actually let's just use yang belom
    threads_imgs = files_biru[4:] + files_putih
    
    with open(LOG, 'w') as log:
        log.write(f"Memulai... Threads: {len(threads_imgs)} (setelah 4 biru pertama) + LinkedIn: {len(linkedin_slots)}\n\n")
        log.flush()
        
        # === THREADS ===
        log.write("=== THREADS ===\n")
        t_ok = 0
        for i, (fname, slot_wib) in enumerate(zip(threads_imgs, 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()
            
            print(f"  [{i+1}/{len(threads_imgs)}] Threads: {fname} @ {slot_wib} ...", end=' ', flush=True)
            try:
                sid = post_one_auth(ACCOUNTS['threads'], fpath, title, slot_utc)
                log.write(f"✅ [{i+1:2d}] {fname:35s} @ {slot_wib} (sid: {str(sid)[:12]})\n")
                print(f"✅ {str(sid)[:12]}")
                t_ok += 1
            except Exception as e:
                log.write(f"❌ [{i+1:2d}] {fname:35s} @ {slot_wib} | {str(e)[:100]}\n")
                print(f"❌ {str(e)[:60]}")
            log.flush()
        
        # === LINKEDIN ===
        lin_imgs = files_putih[:15]
        log.write("\n=== LINKEDIN ===\n")
        l_ok = 0
        for i, (fname, slot_wib) in enumerate(zip(lin_imgs, 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()
            
            print(f"  [{i+1}/{len(lin_imgs)}] LinkedIn: {fname} @ {slot_wib} ...", end=' ', flush=True)
            try:
                sid = post_one_auth(ACCOUNTS['linkedin'], fpath, title, slot_utc)
                log.write(f"✅ [{i+1:2d}] {fname:35s} @ {slot_wib} (sid: {str(sid)[:12]})\n")
                print(f"✅ {str(sid)[:12]}")
                l_ok += 1
            except Exception as e:
                log.write(f"❌ [{i+1:2d}] {fname:35s} @ {slot_wib} | {str(e)[:100]}\n")
                print(f"❌ {str(e)[:60]}")
            log.flush()
        
        log.write(f"\n✅ DONE! Threads: {t_ok}/{len(threads_imgs)} | LinkedIn: {l_ok}/{len(lin_imgs)}\n")
        print(f"\n✅ Selesai! Threads: {t_ok}, LinkedIn: {l_ok}")

if __name__ == '__main__':
    run()

