#!/usr/bin/env python3
"""Update featured image 5 artikel listikel DMark — ganti pake Pexels baru tanpa teks"""

import base64, json, os, urllib.request

WP_URL = "https://dmark.id"
WP_AUTH = base64.b64encode(b"bambangbot:fMqR O6jE Tj7t nvqh AMjv PP1V").decode()
WORKSPACE = os.path.expanduser("~/.openclaw/workspace-atun")

# Post IDs dari hasil publish sebelumnya
POSTS = [
    {"id": 3156, "file": "featured_seo_surabaya.webp", "alt": "Laptop menampilkan data dashboard analisis SEO digital marketing profesional"},
    {"id": 3158, "file": "featured_digital_marketing_surabaya.webp", "alt": "Smartphone dan laptop untuk strategi digital marketing modern"},
    {"id": 3160, "file": "featured_digital_creative_surabaya.webp", "alt": "Peralatan desain kreatif digital dengan warna-warna cerah"},
    {"id": 3162, "file": "featured_website_surabaya.webp", "alt": "Monitor menampilkan kode coding pembuatan website profesional"},
    {"id": 3164, "file": "featured_seo_digital_2026.webp", "alt": "Ruang kerja modern tim SEO dan digital marketing"},
]

def upload_featured(filepath, filename, alt_text):
    """Upload featured image ke WP"""
    with open(filepath, "rb") as f:
        img_data = f.read()
    
    boundary = "----" + os.urandom(8).hex()
    body = bytearray()
    body.extend(f"--{boundary}\r\n".encode())
    body.extend(f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'.encode())
    body.extend(b"Content-Type: image/webp\r\n")
    body.extend(b"\r\n")
    body.extend(img_data)
    body.extend(f"\r\n--{boundary}--\r\n".encode())
    
    req = urllib.request.Request(
        f"{WP_URL}/wp-json/wp/v2/media",
        data=bytes(body),
        headers={
            "Authorization": f"Basic {WP_AUTH}",
            "Content-Type": f"multipart/form-data; boundary={boundary}",
            "User-Agent": "Mozilla/5.0"
        },
        method="POST"
    )
    with urllib.request.urlopen(req, timeout=30) as r:
        resp = json.loads(r.read())
        media_id = resp["id"]
        source_url = resp.get("source_url", "")
        print(f"    ✅ Uploaded media ID={media_id}")
    
    # Update alt text
    body2 = json.dumps({"alt_text": alt_text}).encode()
    req2 = urllib.request.Request(
        f"{WP_URL}/wp-json/wp/v2/media/{media_id}",
        data=body2,
        headers={
            "Authorization": f"Basic {WP_AUTH}",
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0"
        },
        method="POST"
    )
    with urllib.request.urlopen(req2, timeout=15) as r:
        print(f"    ✅ Alt text set: '{alt_text}'")
    
    return media_id, source_url

def update_post_featured(post_id, media_id):
    """Update featured_media post"""
    body = json.dumps({"featured_media": media_id}).encode()
    req = urllib.request.Request(
        f"{WP_URL}/wp-json/wp/v2/posts/{post_id}",
        data=body,
        headers={
            "Authorization": f"Basic {WP_AUTH}",
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0"
        },
        method="POST"
    )
    with urllib.request.urlopen(req, timeout=15) as r:
        resp = json.loads(r.read())
        print(f"    ✅ Post #{post_id} featured image updated!")

print("=" * 60)
print("🖼️ UPDATE FEATURED IMAGES — 5 ARTIKEL LISTIKEL DMARK")
print("=" * 60)

for i, post in enumerate(POSTS):
    print(f"\n{'─'*50}")
    print(f"📌 #{i+1} Post ID {post['id']} → {post['file']}")
    
    filepath = os.path.join(WORKSPACE, post["file"])
    
    # Upload featured image baru
    media_id, url = upload_featured(filepath, post["file"], post["alt"])
    
    # Update post featured_media
    update_post_featured(post["id"], media_id)
    
    print(f"    🔗 {url}")

print(f"\n{'='*60}")
print("✅ SELESAI! Semua featured image udah diganti dari Pexels!")
print(f"{'='*60}")
