#!/usr/bin/env python3
"""Download gambar sesuai tema dari Pexels/Unsplash, crop, upload ke WP"""
import requests, os, subprocess, sys
from PIL import Image

USER = "watibot"
PASS = "HDLe Wkuz el12 U2cd MRqT 1z48"
BASE = "https://www.theskincodeclinic.com/wp-json/wp/v2"
AUTH = (USER, PASS)

# Gambar yang cocok dari Pexels (direct URLs, aman)
PEKELS_IMAGES = {
    # 10 artikel lama — general skincare/beauty
    "tsc_01_facial_medis.webp": ("https://images.pexels.com/photos/5069616/pexels-photo-5069616.jpeg", 8831, "Facial skincare treatment woman"),
    "tsc_02_botox_dan_filler.webp": ("https://images.pexels.com/photos/6629314/pexels-photo-6629314.jpeg", 8834, "Doctor injection botox treatment"),
    "tsc_03_chemical_peeling.webp": ("https://images.pexels.com/photos/5069665/pexels-photo-5069665.jpeg", 8837, "Chemical peel facial treatment"),
    "tsc_04_laser_rejuvenation.webp": ("https://images.pexels.com/photos/3997361/pexels-photo-3997361.jpeg", 8840, "Laser treatment skincare clinic"),
    "tsc_05_microneedling.webp": ("https://images.pexels.com/photos/6629315/pexels-photo-6629315.jpeg", 8843, "Microneedling facial dermatology"),
    "tsc_06_perawatan_kulit_berminyak.webp": ("https://images.pexels.com/photos/5069617/pexels-photo-5069617.jpeg", 8846, "Oily skin facial treatment"),
    "tsc_07_body_contouring.webp": ("https://images.pexels.com/photos/6514704/pexels-photo-6514704.jpeg", 8849, "Body contouring massage therapy"),
    "tsc_08_anti_aging.webp": ("https://images.pexels.com/photos/5069618/pexels-photo-5069618.jpeg", 8852, "Anti aging skincare rejuvenation"),
    "tsc_09_manfaat_facial_medis.webp": ("https://images.pexels.com/photos/5069664/pexels-photo-5069664.jpeg", 8855, "Facial treatment skincare glow"),
    "tsc_010_tips_memilih_klinik.webp": ("https://images.pexels.com/photos/4386467/pexels-photo-4386467.jpeg", 8858, "Choosing best clinic consultation"),
    
    # 5 Dermatology 
    "tsc_01_flek_hitam.webp": ("https://images.pexels.com/photos/5069666/pexels-photo-5069666.jpeg", 8860, "Skin melasma dark spot check"),
    "tsc_02_jerawat.webp": ("https://images.pexels.com/photos/5069620/pexels-photo-5069620.jpeg", 8863, "Acne skin problem teenager"),
    "tsc_03_kulit_kering.webp": ("https://images.pexels.com/photos/5779340/pexels-photo-5779340.jpeg", 8864, "Dry skin moisturizer hand cream"),
    "tsc_04_eksim.webp": ("https://images.pexels.com/photos/3997360/pexels-photo-3997360.jpeg", 8867, "Eczema dermatitis skin allergy"),
    "tsc_05_sunscreen.webp": ("https://images.pexels.com/photos/5069622/pexels-photo-5069622.jpeg", 8870, "Sunscreen sunblock protection cream"),
    
    # 5 Venereology 
    "tsc_06_kenali_pms.webp": ("https://images.pexels.com/photos/7659404/pexels-photo-7659404.jpeg", 8871, "STD sexual health checkup clinic"),
    "tsc_07_kutil_kelamin.webp": ("https://images.pexels.com/photos/4386466/pexels-photo-4386466.jpeg", 8874, "HPV vaccine sexual health"),
    "tsc_08_herpes.webp": ("https://images.pexels.com/photos/7659405/pexels-photo-7659405.jpeg", 8877, "Herpes virus medical consultation"),
    "tsc_09_sifilis.webp": ("https://images.pexels.com/photos/7659403/pexels-photo-7659403.jpeg", 8879, "Syphilis blood test medical"),
    "tsc_10_cegah_pms.webp": ("https://images.pexels.com/photos/4386465/pexels-photo-4386465.jpeg", 8881, "Prevent STD sexual education"),
    
    # 5 Aesthetic
    "tsc_11_kulit_kenyal.webp": ("https://images.pexels.com/photos/5069619/pexels-photo-5069619.jpeg", 8884, "Skin elasticity firm healthy glow"),
    "tsc_12_hidung.webp": ("https://images.pexels.com/photos/6005187/pexels-photo-6005187.jpeg", 8885, "Nose aesthetic rhinoplasty beauty"),
    "tsc_13_bibir.webp": ("https://images.pexels.com/photos/7659275/pexels-photo-7659275.jpeg", 8886, "Lip care beauty aesthetic smile"),
    "tsc_14_tubuh.webp": ("https://images.pexels.com/photos/6514705/pexels-photo-6514705.jpeg", 8887, "Body aesthetic treatment contouring"),
    "tsc_15_perawatan.webp": ("https://images.pexels.com/photos/5069621/pexels-photo-5069621.jpeg", 8889, "Aesthetic beauty treatment clinic"),
}

def process_image(url, post_id, alt_text=""):
    print(f"\n📷 Post ID {post_id}: download {url[:70]}...")
    sys.stdout.flush()
    
    r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=30)
    if r.status_code != 200:
        print(f"  ❌ Download gagal: status {r.status_code}")
        return False
    
    tmp_jpg = f"/tmp/tsc_new/{post_id}.jpg"
    tmp_webp = f"/tmp/tsc_new/{post_id}.webp"
    
    with open(tmp_jpg, 'wb') as f:
        f.write(r.content)
    print(f"  ✅ Downloaded: {len(r.content)} bytes")
    
    # Crop ke 1000x567 center
    img = Image.open(tmp_jpg)
    # Landscape crop center
    w, h = img.size
    target_ratio = 1000 / 567
    current_ratio = w / h
    
    if current_ratio > target_ratio:
        # Too wide, crop width
        new_w = int(h * target_ratio)
        left = (w - new_w) // 2
        img = img.crop((left, 0, left + new_w, h))
    elif current_ratio < target_ratio:
        # Too tall, crop height
        new_h = int(w / target_ratio)
        top = (h - new_h) // 2
        img = img.crop((0, top, w, top + new_h))
    
    img = img.resize((1000, 567), Image.LANCZOS)
    img.save(tmp_webp, 'WEBP', quality=88)
    print(f"  ✅ Cropped 1000x567 webp: {os.path.getsize(tmp_webp)} bytes")
    
    # Upload ke WP
    fname = f"tsc_{post_id}_{os.path.basename(url).split('.')[0][:30]}.webp"
    with open(tmp_webp, 'rb') as f:
        r2 = requests.post(f'{BASE}/media', auth=AUTH,
            files={'file': (fname, f, 'image/webp')},
            data={'alt_text': alt_text},
            timeout=30)
    
    if r2.status_code == 201:
        mid = r2.json()['id']
        # Set sebagai featured image
        r3 = requests.post(f"{BASE}/posts/{post_id}", auth=AUTH, json={"featured_media": mid}, timeout=15)
        if r3.status_code in (200, 201):
            print(f"  ✅ Featured IMG ID {mid} SET for post {post_id} ✨")
        else:
            print(f"  ⚠️ Set featured gagal: {r3.status_code}")
        
        # Hapus media lama
        os.remove(tmp_jpg)
        os.remove(tmp_webp)
        return True
    else:
        print(f"  ❌ Upload gagal: {r2.status_code} {r2.text[:150]}")
        return False

os.makedirs("/tmp/tsc_new", exist_ok=True)

success = 0
for fname, (url, post_id, alt) in sorted(PEKELS_IMAGES.items()):
    if process_image(url, post_id, alt):
        success += 1

print(f"\n{'='*50}")
print(f"Selesai! {success}/{len(PEKELS_IMAGES)} gambar berhasil diganti ✅")
