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

IMAGES = [
    # Artikel 3: Balancing Spooring — car wheel/alignment
    ("https://images.pexels.com/photos/164274/pexels-photo-164274.jpeg", "artikel-3-balancing-spooring.webp"),
    # Artikel 5: Ban Mobil — car tire closeup
    ("https://images.pexels.com/photos/1005631/pexels-photo-1005631.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
        w, h = img.size
        current_ratio = w / h
        
        if current_ratio > target_ratio:
            new_w = int(h * target_ratio)
            left = (w - new_w) // 2
            img = img.crop((left, 0, left + new_w, h))
        else:
            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}")
        img = img.resize((1000, 567), Image.LANCZOS)
        
        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

for url, fn in IMAGES:
    download_and_process(url, fn)
    print()
