import os, io, json, base64
from PIL import Image, ImageOps

SRC = "/sessions/optimistic-stoic-mendel/mnt/outputs/poe_src/Lethabo_POE"
OUT = "/sessions/optimistic-stoic-mendel/mnt/outputs/assets.json"

# key: (filename, mode, target_w, target_h_or_None, quality)
# mode "cover" = centre-crop to ratio; "fit" = keep natural aspect, cap width
JOBS = {
    "headshot":   ("Headshot.PNG",                 "cover", 1000, 1250, 76),
    "garden":     ("Community garden.JPG",         "cover", 1200, 1500, 74),
    "garden2":    ("Community garden2.JPG",        "cover", 1100, 1100, 74),
    "library":    ("Library.jpg",                  "cover", 1100, 1100, 76),
    "library_w":  ("Library.jpg",                  "cover", 1400,  900, 76),
    "theoday":    ("Theological Day.JPG",          "cover", 1400,  900, 74),
    "theoday2":   ("Theological Day2.JPG",         "cover", 1100, 1100, 74),
    "service":    ("Theological_Day_Service_2026_.jpg", "fit", 1100, None, 80),
    "banner":     ("wall_banner_Page_1.jpg",       "fit", 1200, None, 80),
    "mandela":    ("2025 Mandela Day  copy.png",   "fit", 1100, None, 80),
    "cal1":       ("Final_Theology and Religion 2026 Bookmark Calendar PRINT - Lethabo Machabaphala[66]_Page_1.jpg", "fit", 900, None, 80),
    "cal2":       ("Final_Theology and Religion 2026 Bookmark Calendar PRINT - Lethabo Machabaphala[66]_Page_2.jpg", "fit", 900, None, 80),
}

out = {}
total = 0
for key, (fn, mode, tw, th, q) in JOBS.items():
    p = os.path.join(SRC, fn)
    im = Image.open(p)
    im = ImageOps.exif_transpose(im).convert("RGB")
    if mode == "cover":
        im = ImageOps.fit(im, (tw, th), Image.LANCZOS, centering=(0.5, 0.4))
    else:
        if im.width > tw:
            im = im.resize((tw, round(im.height * tw / im.width)), Image.LANCZOS)
    buf = io.BytesIO()
    im.save(buf, "WEBP", quality=q, method=6)
    b = buf.getvalue()
    total += len(b)
    out[key] = "data:image/webp;base64," + base64.b64encode(b).decode()
    print(f"{key:10s} {im.width}x{im.height} {len(b)/1024:8.1f} KB")

json.dump(out, open(OUT, "w"))
print(f"TOTAL raw {total/1024/1024:.2f} MB  -> base64 approx {total*1.34/1024/1024:.2f} MB")
