#!/usr/bin/env python3
"""Crop featured images of 10 EveryBe articles to 1000x567 and re-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}"}

artikel = {
    3051: "Panduan Pijat Otot Sendiri",
    3052: "Sering Duduk Lama - Risiko Otot",
    3053: "Feminine V Spray vs Sabun",
    3054: "5 Aktivitas Ganggu Organ Intim",
    3055: "Skin Barrier Rusak",
    3056: "Skincare Sesuai Budget",
    3057: "Body Lotion vs Tone Up",
    3058: "Bahan Alami Body Care Glowing",
    3059: "Self-Care Pekerja Sibuk",
    3060: "Self-Love Wanita Modern"
}

TARGET_W, TARGET_H = 1000, 567

for post_id, label in artikel.items():
    print(f"\n[{post_id}] {label}")
    
    # Get current featured media
    r = requests.get(f"{WP_URL}/posts/{post_id}", headers=HEADERS, timeout=10)
    if r.status_code != 200:
        print(f"  ❌ Gagal ambil post")
        continue
    post = r.json()
    media_id = post.get("featured_media")
    if not media_id:
        print(f"  ⚠️ Tidak punya featured image")
        continue
    
    # Get media URL
    r2 = requests.get(f"{WP_URL}/media/{media_id}", headers=HEADERS, timeout=10)
    if r2.status_code != 200:
        print(f"  ❌ Gagal ambil media")
        continue
    media = r2.json()
    src_url = media.get("source_url")
    if not src_url:
        print(f"  ❌ Tidak ada source_url")
        continue
    print(f"  Source: {src_url[:80]}...")
    
    # Download image
    try:
        img_resp = requests.get(src_url, timeout=30)
        if img_resp.status_code != 200:
            print(f"  ❌ Gagal download")
            continue
    except Exception as e:
        print(f"  ❌ Download error: {e}")
        continue
    
    # Crop to 1000x567 (center crop, maintain aspect ratio)
    try:
        img = Image.open(io.BytesIO(img_resp.content))
        orig_w, orig_h = img.size
        print(f"  Original: {orig_w}x{orig_h}")
        
        # Hitung aspect ratio target
        target_ratio = TARGET_W / TARGET_H
        orig_ratio = orig_w / orig_h
        
        if orig_ratio > target_ratio:
            # Gambar lebih lebar -> crop horizontal
            new_w = int(orig_h * target_ratio)
            new_h = orig_h
            left = (orig_w - new_w) // 2
            top = 0
        else:
            # Gambar lebih tinggi -> crop vertikal
            new_w = orig_w
            new_h = int(orig_w / target_ratio)
            left = 0
            top = (orig_h - new_h) // 2
        
        img_cropped = img.crop((left, top, left + new_w, top + new_h))
        img_resized = img_cropped.resize((TARGET_W, TARGET_H), Image.LANCZOS)
        
        buf = io.BytesIO()
        img_resized.save(buf, format="JPEG", quality=92, optimize=True)
        img_data = buf.getvalue()
        print(f"  Cropped: {TARGET_W}x{TARGET_H} ({len(img_data)} bytes)")
    except Exception as e:
        print(f"  ❌ Crop error: {e}")
        continue
    
    # Upload as new media
    filename = f"everybe-article-{post_id}-1000x567.jpg"
    media_headers = {**HEADERS,
        "Content-Disposition": f'attachment; filename="{filename}"',
        "Content-Type": "image/jpeg"
    }
    
    try:
        up_resp = requests.post(f"{WP_URL}/media", headers=media_headers, data=img_data, timeout=30)
        if up_resp.status_code not in (200, 201):
            print(f"  ❌ Gagal upload: {up_resp.status_code}")
            continue
        new_media_id = up_resp.json()["id"]
        print(f"  Upload OK, media ID: {new_media_id}")
    except Exception as e:
        print(f"  ❌ Upload error: {e}")
        continue
    
    # Update title & alt text
    alt = label
    requests.post(f"{WP_URL}/media/{new_media_id}", headers=HEADERS, json={
        "title": f"EveryBe - {label}",
        "alt_text": f"EveryBe {label} - 1000x567"
    }, timeout=10)
    
    # Set as featured image
    feat_resp = requests.post(f"{WP_URL}/posts/{post_id}", headers=HEADERS, json={
        "featured_media": new_media_id
    }, timeout=10)
    
    if feat_resp.status_code in (200, 201):
        print(f"  ✅ Featured image terpasang (1000x567)")
    else:
        print(f"  ⚠️ Gagal set featured: {feat_resp.status_code}")
    
    time.sleep(0.5)

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