#!/usr/bin/env bash
# Generates Android launcher icons from assets/adaptive-icon-android.png.
# - Trims white border, re-centers chain on 1024×1024 transparent canvas
#   (logo size unchanged, only position).
# - Writes ic_launcher_foreground.webp (transparent bg) for adaptive icon.
# - Writes ic_launcher{,_round}.webp on #0a0a0a square as legacy fallback.
# - Background color matches values/colors.xml (iconBackground = #0a0a0a).
set -euo pipefail

cd "$(dirname "$0")/.."

SOURCE="assets/adaptive-icon-android.png"
RES="android/app/src/main/res"
BG="#0a0a0a"

if [[ ! -f "$SOURCE" ]]; then
  echo "Missing $SOURCE" >&2
  exit 1
fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

# 1. Trim near-white borders, re-embed centered on 1024×1024 transparent canvas.
#    -fuzz 5% absorbs JPEG-style artifacts around the white background.
magick "$SOURCE" \
  -fuzz 5% -trim +repage \
  -background "rgba(0,0,0,0)" -gravity center -extent 1024x1024 \
  "$TMP/master.png"

# Overwrite source so app.config.ts stays the single source of truth.
cp "$TMP/master.png" "$SOURCE"
echo "Wrote centered master → $SOURCE"

# bash 3.2 (macOS default) has no assoc arrays — use parallel positional pairs:
# "<bucket>:<foreground-px>:<legacy-px>".
BUCKETS=( "mdpi:108:48" "hdpi:162:72" "xhdpi:216:96" "xxhdpi:324:144" "xxxhdpi:432:192" )

for entry in "${BUCKETS[@]}"; do
  bucket="${entry%%:*}"
  rest="${entry#*:}"
  fg_size="${rest%%:*}"
  lg_size="${rest#*:}"
  dir="$RES/mipmap-$bucket"
  mkdir -p "$dir"

  # Foreground layer (transparent bg) for adaptive icon.
  magick "$TMP/master.png" -resize "${fg_size}x${fg_size}" "$TMP/fg-$bucket.png"
  cwebp -quiet -q 95 "$TMP/fg-$bucket.png" -o "$dir/ic_launcher_foreground.webp"
  echo "  ic_launcher_foreground.webp $bucket ${fg_size}px"

  # Legacy ic_launcher / ic_launcher_round on dark background.
  magick -size "${lg_size}x${lg_size}" "xc:$BG" \
    \( "$TMP/master.png" -resize "${lg_size}x${lg_size}" \) -gravity center -composite \
    "$TMP/lg-$bucket.png"
  cwebp -quiet -q 95 "$TMP/lg-$bucket.png" -o "$dir/ic_launcher.webp"
  cp "$dir/ic_launcher.webp" "$dir/ic_launcher_round.webp"
  echo "  ic_launcher{,_round}.webp $bucket ${lg_size}px"
done

echo "Done."
