#!/usr/bin/env python3
"""Compress PNG images to JPEG with adjustable quality"""
from PIL import Image
import os, sys, glob, base64

quality = int(sys.argv[1]) if len(sys.argv) > 1 else 70

for png in sorted(glob.glob("/tmp/sadi-pages/page-*.png")):
    base = os.path.basename(png).replace('.png', '')
    jpg_path = f"/tmp/sadi-pages/{base}.jpg"
    img = Image.open(png)
    img = img.convert('RGB')
    # Resize if too large (max 2048px on longest side for API efficiency)
    max_dim = 2048
    w, h = img.size
    if max(w, h) > max_dim:
        ratio = max_dim / max(w, h)
        new_w = int(w * ratio)
        new_h = int(h * ratio)
        img = img.resize((new_w, new_h), Image.LANCZOS)
        print(f"{base}: resized {w}x{h} -> {new_w}x{new_h}", flush=True)
    img.save(jpg_path, 'JPEG', quality=quality, optimize=True)
    png_size = os.path.getsize(png)
    jpg_size = os.path.getsize(jpg_path)
    with open(jpg_path, 'rb') as f:
        b64 = base64.b64encode(f.read()).decode()
    print(f"{base}: PNG={png_size/1024/1024:.1f}MB -> JPG={jpg_size/1024/1024:.1f}MB (b64={len(b64)/1024:.0f}KB)", flush=True)
