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

# Artikel 3: Balancing Spooring — pakai gambar car wheel
url = "https://images.pexels.com/photos/1310234/pexels-photo-1310234.jpeg"
OUTPUT_DIR = "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das/featured-images"

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}")

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, "artikel-3-balancing-spooring.webp")
img.save(outpath, "WEBP", quality=85)
size_kb = os.path.getsize(outpath) / 1024
print(f"  Saved: {outpath} ({size_kb:.1f} KB)")
