import requests
import sys
import os
from PIL import Image
from io import BytesIO

IMAGES = [
    # Artikel 1: Transmisi Matic — interior mobil, dashboard
    ("https://images.pexels.com/photos/919073/pexels-photo-919073.jpeg", "artikel-1-transmisi-matic.webp"),
    # Artikel 2: AC Mobil — dashboard AC mobil
    ("https://images.pexels.com/photos/3394666/pexels-photo-3394666.jpeg", "artikel-2-ac-mobil.webp"),
    # Artikel 3: Balancing Spooring — ban/velg mobil
    ("https://images.pexels.com/photos/3145815/pexels-photo-3145815.jpeg", "artikel-3-balancing-spooring.webp"),
    # Artikel 4: BMW Servis — mobil BMW
    ("https://images.pexels.com/photos/1429777/pexels-photo-1429777.jpeg", "artikel-4-biaya-servis-bmw.webp"),
    # Artikel 5: Ban Mobil — ban mobil
    ("https://images.pexels.com/photos/3802001/pexels-photo-3802001.jpeg", "artikel-5-memilih-ban-mobil.webp"),
]

OUTPUT_DIR = "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das/featured-images"

def download_and_process(url, filename):
    try:
        print(f"Downloading {url}...")
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        
        img = Image.open(BytesIO(r.content))
        print(f"  Original size: {img.size}")
        
        # Center crop to 1000:567 ratio
        target_ratio = 1000 / 567  # ~1.764
        w, h = img.size
        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))
        else:
            # Too tall, crop height
            new_h = int(w / target_ratio)
            top = (h - new_h) // 2
            img = img.crop((0, top, w, top + new_h))
        
        print(f"  After crop: {img.size}")
        
        # Resize to 1000x567
        img = img.resize((1000, 567), Image.LANCZOS)
        
        # Save as WebP
        outpath = os.path.join(OUTPUT_DIR, filename)
        img.save(outpath, "WEBP", quality=85)
        size_kb = os.path.getsize(outpath) / 1024
        print(f"  Saved: {outpath} ({size_kb:.1f} KB)")
        return True
    except Exception as e:
        print(f"  ERROR: {e}")
        return False

os.makedirs(OUTPUT_DIR, exist_ok=True)
success = 0
for url, fn in IMAGES:
    if download_and_process(url, fn):
        success += 1
    print()

print(f"\nDone! {success}/{len(IMAGES)} images processed.")
