#!/usr/bin/env python3
"""Download, crop to 1000x567, upload & set featured image for 10 EveryBe articles."""
import requests, base64, time, io, sys
from PIL import Image

WP_URL = "https://www.everybeofficial.com/wp-json/wp/v2"
USER = "bambangbot"
APP_PASS = "2Aa0 OwYY NJaL Oc8b 9OCo Owcw"
auth_b64 = base64.b64encode(f"{USER}:{APP_PASS}".encode()).decode()
HEADERS = {"Authorization": f"Basic {auth_b64}"}

TARGET_W, TARGET_H = 1000, 567

# Upload gambar baru untuk tiap artikel dari source gambar fresh Pexels
artikel_gambar = {
    3051: {
        "label": "Panduan Pijat Otot Sendiri",
        "url": "https://images.pexels.com/photos/6560303/pexels-photo-6560303.jpeg"
    },
    3052: {
        "label": "Sering Duduk Lama",
        "url": "https://images.pexels.com/photos/11716938/pexels-photo-11716938.jpeg"
    },
    3053: {
        "label": "Feminine V Spray vs Sabun",
        "url": "https://images.pexels.com/photos/4046318/pexels-photo-4046318.jpeg"
    },
    3054: {
        "label": "5 Aktivitas Ganggu Organ Intim",
        "url": "https://images.pexels.com/photos/4057698/pexels-photo-4057698.jpeg"
    },
    3055: {
        "label": "Skin Barrier Rusak",
        "url": "https://images.pexels.com/photos/3762454/pexels-photo-3762454.jpeg"
    },
    3056: {
        "label": "Skincare Sesuai Budget",
        "url": "https://images.pexels.com/photos/5076520/pexels-photo-5076520.jpeg"
    },
    3057: {
        "label": "Body Lotion vs Tone Up",
        "url": "https://images.pexels.com/photos/4465125/pexels-photo-4465125.jpeg"
    },
    3058: {
        "label": "Bahan Alami Body Care",
        "url": "https://images.pexels.com/photos/4602526/pexels-photo-4602526.jpeg"
    },
    3059: {
        "label": "Self-Care Pekerja Sibuk",
        "url": "https://images.pexels.com/photos/3770597/pexels-photo-3770597.jpeg"
    },
    3060: {
        "label": "Self-Love Wanita Modern",
        "url": "https://images.pexels.com/photos/4046319/pexels-photo-4046319.jpeg"
    }
}

print("CROP 1000x567 & UPLOAD FEATURED IMAGES - 10 ARTIKEL\n")

for post_id, info in artikel_gambar.items():
    label = info["label"]
    url = info["url"]
    
    print(f"[{post_id}] {label}")
    print(f"  Download: {url[:60]}...")
    
    # Download gambar
    try:
        r = requests.get(url, timeout=60)
        if r.status_code != 200:
            print(f"  ❌ Download gagal: {r.status_code}")
            continue
    except Exception as e:
        print(f"  ❌ Download error: {e}")
        continue
    
    # Crop 1000x567 center
    try:
        img = Image.open(io.BytesIO(r.content))
        w, h = img.size
        target_ratio = TARGET_W / TARGET_H
        orig_ratio = w / h
        
        if orig_ratio > target_ratio:
            nw = int(h * target_ratio)
            nh = h
            left = (w - nw) // 2
            top = 0
        else:
            nw = w
            nh = int(w / target_ratio)
            left = 0
            top = (h - nh) // 2
        
        cropped = img.crop((left, top, left + nw, top + nh))
        resized = cropped.resize((TARGET_W, TARGET_H), Image.LANCZOS)
        
        buf = io.BytesIO()
        resized.save(buf, format="JPEG", quality=92, optimize=True)
        img_data = buf.getvalue()
        print(f"  Original: {w}x{h} -> Cropped: {TARGET_W}x{TARGET_H} ({len(img_data)} bytes)")
    except Exception as e:
        print(f"  ❌ Crop error: {e}")
        continue
    
    # Upload ke media library
    filename = f"everybe-{post_id}-1000x567.jpg"
    media_headers = {**HEADERS,
        "Content-Disposition": f'attachment; filename="{filename}"',
        "Content-Type": "image/jpeg"
    }
    
    try:
        up = requests.post(f"{WP_URL}/media", headers=media_headers, data=img_data, timeout=120)
        if up.status_code not in (200, 201):
            print(f"  ❌ Upload gagal: {up.status_code} {up.text[:200]}")
            continue
        mid = up.json()["id"]
        print(f"  Upload OK, media ID: {mid}")
    except Exception as e:
        print(f"  ❌ Upload error: {e}")
        continue
    
    # Update alt text
    try:
        requests.post(f"{WP_URL}/media/{mid}", headers=HEADERS, json={
            "alt_text": f"EveryBe - {label} - 1000x567"
        }, timeout=10)
    except:
        pass
    
    # Set featured image
    try:
        f = requests.post(f"{WP_URL}/posts/{post_id}", headers=HEADERS, json={
            "featured_media": mid
        }, timeout=10)
        if f.status_code in (200, 201):
            print(f"  ✅ Featured image SET (1000x567)!")
        else:
            print(f"  ⚠️ Gagal set featured: {f.status_code}")
    except Exception as e:
        print(f"  ⚠️ Featured set error: {e}")
    
    time.sleep(1)
    print()

print("=== SELESAI! Semua featured image 1000x567 terpasang ===")
