import base64, json, os, urllib.request
WP_URL = "https://yasmanatura.co.id"
WP_AUTH = base64.b64encode(b"bambangbot:LFp4 LXBh kMYG 84qC 2DDc 5bLc").decode()
POST_ID = 4532
IMG_URL = "https://images.pexels.com/photos/13428094/pexels-photo-13428094.jpeg"
ALT = "Ilustrasi maklon minuman serbuk dengan bahan herbal alami Yasma Natura"
filename = "yasma_maklon_minuman_serbuk.jpg"

# download
print("1. Download image Pexels...")
req_img = urllib.request.Request(IMG_URL, headers={"User-Agent":"Mozilla/5.0"})
with urllib.request.urlopen(req_img, timeout=40) as r:
    img_data = r.read()
print(f"   -> {len(img_data)} bytes")

# upload media
print("2. Upload ke WP media...")
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/jpeg\r\n\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=40) as r:
    resp = json.loads(r.read())
    media_id = resp["id"]
    print(f"   -> Media ID={media_id} | {resp.get('source_url')}")

# set alt
print("3. Set alt text...")
b2 = json.dumps({"alt_text": ALT}).encode()
r2 = urllib.request.Request(f"{WP_URL}/wp-json/wp/v2/media/{media_id}", data=b2,
    headers={"Authorization": f"Basic {WP_AUTH}", "Content-Type":"application/json","User-Agent":"Mozilla/5.0"}, method="POST")
with urllib.request.urlopen(r2, timeout=20) as r:
    print("   -> Alt OK")

# set featured_media
print("4. Set featured image post...")
b3 = json.dumps({"featured_media": media_id}).encode()
r3 = urllib.request.Request(f"{WP_URL}/wp-json/wp/v2/posts/{POST_ID}", data=b3,
    headers={"Authorization": f"Basic {WP_AUTH}", "Content-Type":"application/json","User-Agent":"Mozilla/5.0"}, method="POST")
with urllib.request.urlopen(r3, timeout=20) as r:
    resp3 = json.loads(r.read())
    print(f"   -> Featured media post #{POST_ID} = {resp3.get('featured_media')}")
print("SELESAI ✅")
