#!/usr/bin/env bash
# Rebuild js/vendor/imgly-background-removal-<version>/ from npm, the way the committed copy was built.
# The bundle is IMG.LY's @imgly/background-removal (AGPL-3.0) with onnxruntime-web, zod, ndarray, and
# lodash-es (MIT). Source maps carry the original source of every bundled file, and the .LEGAL.txt
# files keep each bundled package's license notice.
#
# Usage: scripts/vendor_background_removal.sh [version]   (default 1.7.0)
# The model and WASM files are not vendored: the library fetches them from IMG.LY's servers for its
# own version. After changing the version, update the "library" path in scripts/tool_content.py.
set -euo pipefail

VERSION="${1:-1.7.0}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/js/vendor/imgly-background-removal-$VERSION"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

cd "$WORK"
npm init -y > /dev/null
npm install --no-audit --no-fund "@imgly/background-removal@$VERSION" esbuild@0.25 > /dev/null
printf "export { removeBackground, preload } from '@imgly/background-removal';\n" > entry.mjs
npx esbuild entry.mjs --bundle --format=esm --splitting --minify --sourcemap --sources-content=true \
  --legal-comments=linked --platform=browser --target=es2020 --outdir=out \
  --entry-names=background-removal '--chunk-names=chunk-[hash]'

rm -rf "$OUT"
mkdir -p "$OUT"
cp out/* "$OUT/"
cp node_modules/@imgly/background-removal/LICENSE.md "$OUT/LICENSE.md"
cp node_modules/@imgly/background-removal/ThirdPartyLicenses.json "$OUT/ThirdPartyLicenses.json"
echo "Wrote $OUT"
