#!/usr/bin/env python3
"""Crop featured images to 1000x567 WebP & upload."""
import requests, base64, time, io
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

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 WebP & UPLOAD - 10 ARTIKEL\n")

for post_id, info in artikel_gambar.items():
    label = info["label"]
    url = info["url"]
    
    print(f"[{post_id}] {label}")
    
    # Download
    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 & save as WebP
    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)
        
        # Convert to RGB if RGBA
        if resized.mode == 'RGBA':
            resized = resized.convert('RGB')
        
        buf = io.BytesIO()
        resized.save(buf, format="WEBP", quality=85, optimize=True)
        img_data = buf.getvalue()
        print(f"  {w}x{h} -> 1000x567 WebP ({len(img_data)} bytes)")
    except Exception as e:
        print(f"  ❌ Crop/convert error: {e}")
        continue
    
    # Upload
    filename = f"everybe-{post_id}.webp"
    media_headers = {**HEADERS,
        "Content-Disposition": f'attachment; filename="{filename}"',
        "Content-Type": "image/webp"
    }
    
    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}")
            continue
        mid = up.json()["id"]
        alt = f"EveryBe - {label}"
        requests.post(f"{WP_URL}/media/{mid}", headers=HEADERS, json={
            "title": alt,
            "alt_text": alt
        }, timeout=10)
    except Exception as e:
        print(f"  ❌ Upload error: {e}")
        continue
    
    # Set featured
    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 WebP)")
        else:
            print(f"  ⚠️ Gagal set featured: {f.status_code} {f.text[:100]}")
    except Exception as e:
        print(f"  ⚠️ Error: {e}")
    
    time.sleep(1)
    print()

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