#!/usr/bin/env python3
"""Koldflux: WebP vs JPEG vs PNG measurement, October 27, 2026.
Inputs (same folder): photo-ref.png (CC0 Commons photo "Harbour chapel, red boat, Nea Artaki, Evia Greece",
scaled to 2000 px wide by measure.sh) and graphic-ref.png (our own 1600x720 chart and table, rendered by Chromium).
Encoders: cjpeg (libjpeg-turbo) -quality Q -optimize; cwebp (libwebp) -q Q -m 6; cwebp -lossless -z 9; PNG by Pillow optimize=True.
Every file is decoded with the reference decoder (djpeg / dwebp) and compared with the reference using ffmpeg's SSIM filter on RGB.
Writes results.json and prints the log."""
import json, os, re, subprocess, hashlib, sys
from PIL import Image

def run(cmd): return subprocess.run(cmd, check=True, capture_output=True, text=True)
def ssim(dec, ref):
    r = subprocess.run(["ffmpeg", "-hide_banner", "-i", dec, "-i", ref, "-lavfi", "[0:v]format=gbrp[a];[1:v]format=gbrp[b];[a][b]ssim", "-f", "null", "-"], capture_output=True, text=True)
    return float(re.search(r"All:([0-9.]+)", r.stderr).group(1))
def rgbhash(p): return hashlib.sha256(Image.open(p).convert("RGB").tobytes()).hexdigest()

out = {"versions": {"cjpeg": run(["cjpeg", "-version"]).stderr.strip().splitlines()[0], "cwebp": run(["cwebp", "-version"]).stdout.strip().splitlines()[0],
                    "ffmpeg": run(["ffmpeg", "-version"]).stdout.splitlines()[0], "pillow": Image.__version__}, "images": {}}
os.makedirs("enc", exist_ok=True)
for name in ["photo", "graphic"]:
    ref = f"{name}-ref.png"; ppm = f"enc/{name}-ref.ppm"; Image.open(ref).convert("RGB").save(ppm)
    w, h = Image.open(ref).size
    res = {"size": [w, h], "jpeg": [], "webp": []}
    for q in range(10, 101):
        j = f"enc/{name}-q{q}.jpg"; run(["cjpeg", "-quality", str(q), "-optimize", "-outfile", j, ppm]); run(["djpeg", "-outfile", j + ".ppm", j])
        res["jpeg"].append({"q": q, "bytes": os.path.getsize(j), "ssim": ssim(j + ".ppm", ref)})
        wp = f"enc/{name}-q{q}.webp"; run(["cwebp", "-quiet", "-q", str(q), "-m", "6", ppm, "-o", wp]); run(["dwebp", "-quiet", wp, "-ppm", "-o", wp + ".ppm"])
        res["webp"].append({"q": q, "bytes": os.path.getsize(wp), "ssim": ssim(wp + ".ppm", ref)})
    ll = f"enc/{name}-lossless.webp"; run(["cwebp", "-quiet", "-lossless", "-z", "9", ppm, "-o", ll]); run(["dwebp", "-quiet", ll, "-ppm", "-o", ll + ".ppm"])
    png = f"enc/{name}-optimized.png"; Image.open(ref).convert("RGB").save(png, optimize=True)
    res["lossless"] = {"webp_bytes": os.path.getsize(ll), "png_bytes": os.path.getsize(png), "ref_hash": rgbhash(ref),
                       "webp_hash": rgbhash(ll + ".ppm"), "png_hash": rgbhash(png)}
    out["images"][name] = res
json.dump(out, open("results.json", "w"), indent=1)

print(json.dumps(out["versions"]))
for name, r in out["images"].items():
    print(f"\n=== {name} {r['size'][0]}x{r['size'][1]}")
    print("q    jpeg_bytes  jpeg_ssim   webp_bytes  webp_ssim")
    for a, b in zip(r["jpeg"], r["webp"]):
        print(f"{a['q']:<4} {a['bytes']:>10}  {a['ssim']:.6f}  {b['bytes']:>10}  {b['ssim']:.6f}")
    L = r["lossless"]
    print(f"lossless webp {L['webp_bytes']} bytes, pixels identical to reference: {L['webp_hash'] == L['ref_hash']}")
    print(f"optimized png {L['png_bytes']} bytes, pixels identical to reference: {L['png_hash'] == L['ref_hash']}")
