#!/usr/bin/env bash
#
# optimize_goldens.sh — recursively optimize PNG goldens in-place.
#
# Runs after each `record` pass for both iOS and Android parity galleries.
# Removes unnecessary PNG chunks (textual metadata, ancillary palette
# entries) and re-encodes the image with a better DEFLATE strategy so the
# image bytes on disk drop by 15–40% without touching a single pixel.
#
# Dependencies
# ------------
#   zopflipng   (preferred — brute-force DEFLATE, best compression)
#   pngcrush    (fallback — faster, smaller savings)
#
# Install on macOS:
#   brew install zopfli pngcrush
#
# The script never fails if the tools are missing: it warns and exits 0,
# leaving the goldens untouched. CI's size-gate will still fail loudly if
# the PNGs would bust the 150 KB budget.
#
# Usage
# -----
#   ./scripts/optimize_goldens.sh                 # default dirs (iOS + Android)
#   ./scripts/optimize_goldens.sh path1 path2     # specific dirs only
#
# Idempotent — re-running on already-optimized PNGs is a no-op.
#
set -euo pipefail

DIRS=("$@")
if [ ${#DIRS[@]} -eq 0 ]; then
    DIRS=(
        "iosApp/HoneyDueTests/__Snapshots__"
        "composeApp/src/androidUnitTest/roborazzi"
    )
fi

tool=""
if command -v zopflipng >/dev/null 2>&1; then
    tool="zopflipng"
elif command -v pngcrush >/dev/null 2>&1; then
    tool="pngcrush"
else
    echo "WARNING: neither zopflipng nor pngcrush is installed — skipping PNG optimization."
    echo "  Install with: brew install zopfli pngcrush"
    exit 0
fi

echo "optimize_goldens: using ${tool}"

count=0
saved=0
for dir in "${DIRS[@]}"; do
    if [ ! -d "$dir" ]; then
        continue
    fi
    while IFS= read -r -d '' png; do
        before=$(stat -f%z "$png" 2>/dev/null || stat -c%s "$png")
        if [ "$tool" = "zopflipng" ]; then
            # -y  : overwrite without prompt
            # --lossy_transparent : allow color rewrite under alpha=0 for extra savings
            zopflipng -y --lossy_transparent "$png" "$png" >/dev/null 2>&1 || true
        else
            # -ow : overwrite-in-place; -q : quiet
            pngcrush -q -ow "$png" >/dev/null 2>&1 || true
        fi
        after=$(stat -f%z "$png" 2>/dev/null || stat -c%s "$png")
        saved=$((saved + before - after))
        count=$((count + 1))
    done < <(find "$dir" -name '*.png' -print0)
done

if [ "$count" -eq 0 ]; then
    echo "optimize_goldens: no PNGs found in: ${DIRS[*]}"
    exit 0
fi

# Print a human-readable summary. `bc` is standard on macOS / most linuxes.
mb=$(echo "scale=2; $saved/1048576" | bc)
printf "optimize_goldens: %d PNGs processed, saved %.2f MB (%s)\n" "$count" "$mb" "$tool"
