#!/usr/bin/env bash
set -euo pipefail

orig="src/img/device.png"
backup="src/img/device@orig.png"

if [[ ! -f "$orig" ]]; then
  echo "Error: $orig not found" >&2
  exit 1
fi

# Backup original once
if [[ ! -f "$backup" ]]; then
  cp "$orig" "$backup"
  echo "Backup created at $backup"
else
  echo "Backup already exists at $backup"
fi

before_size=$(stat -c%s "$orig" 2>/dev/null || wc -c < "$orig")

opt_tool=""
if command -v pngquant >/dev/null 2>&1; then
  opt_tool="pngquant"
  # Use pngquant lossy compression with reasonable quality range
  pngquant --skip-if-larger --force --quality=65-80 --output "$orig" "$backup"
elif command -v oxipng >/dev/null 2>&1; then
  opt_tool="oxipng"
  # Lossless optimization
  oxipng -o 4 --strip safe -i 0 -Z "$orig"
elif command -v convert >/dev/null 2>&1; then
  opt_tool="imagemagick"
  # Resize to max width 1200px (keeps aspect), strip metadata; re-encode PNG
  convert "$orig" -strip -resize 1200x -define png:compression-level=9 -define png:compression-filter=5 -define png:compression-strategy=1 "$orig.tmp"
  mv -f "$orig.tmp" "$orig"
else
  echo "No optimizer found (pngquant/oxipng/ImageMagick). Install one and re-run." >&2
  exit 2
fi

after_size=$(stat -c%s "$orig" 2>/dev/null || wc -c < "$orig")

fmt() { num=$1; awk -v n=$num 'BEGIN{ split("B KB MB GB TB",u); s=1; while (n>=1024 && s<5){n/=1024; s++} printf "%.2f %s", n, u[s] }'; }

echo "Optimizer used: $opt_tool"
echo "Before: $(fmt $before_size)"
echo "After:  $(fmt $after_size)"

if (( after_size < before_size )); then
  echo "✅ device.png optimized successfully."
else
  echo "ℹ️  No size improvement (tool limitations or already optimized)."
fi
