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

# Convert JPG brake-specs diagrams to WebP for GRC product pages.
# Outputs are intentionally written OUTSIDE the repo by default; upload them
# to the server manually (they are gitignored assets).
#
# Usage:
#   scripts/convert_esquemas.sh [src] [dst] [quality]
#
# Defaults:
#   src  = /home/monder/Documents/grc_images/esquemas
#   dst  = /home/monder/Documents/grc_images/esquemas_webp
#   q    = 82

SRC="${1:-/home/monder/Documents/grc_images/esquemas}"
DST="${2:-/home/monder/Documents/grc_images/esquemas_webp}"
QUALITY="${3:-82}"

if ! command -v magick >/dev/null 2>&1; then
  echo "ERROR: ImageMagick 'magick' not found" >&2
  exit 1
fi

mkdir -p "$DST"

converted=0
skipped=0
failed=0

shopt -s nullglob
for f in "$SRC"/*.jpg "$SRC"/*.jpeg "$SRC"/*.JPG; do
  [ -f "$f" ] || continue

  stem=$(basename "${f%.*}")
  out="$DST/$stem.webp"

  if [ -f "$out" ] && [ "$out" -nt "$f" ]; then
    skipped=$((skipped + 1))
    continue
  fi

  if magick "$f" -quality "$QUALITY" -strip "webp:$out"; then
    converted=$((converted + 1))
  else
    failed=$((failed + 1))
    echo "ERROR: failed to convert $f" >&2
  fi
done
shopt -u nullglob

total=$(find "$DST" -maxdepth 1 -type f -name '*.webp' | wc -l)

echo "Done: converted=$converted skipped=$skipped failed=$failed total-in-dst=$total"
echo "Output directory: $DST"
