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

# Build html-to-image as a self-contained IIFE bundle for embedding via include_str!().
# Output: crates/tauri-plugin-pilot/js/vendor/html-to-image.iife.js
#
# Prerequisites: Node.js + npm
# Run from project root: bash scripts/build-html-to-image.sh

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
VENDOR_DIR="$PROJECT_DIR/crates/tauri-plugin-pilot/js/vendor"
OUTPUT="$VENDOR_DIR/html-to-image.iife.js"

cd "$PROJECT_DIR"

# Install html-to-image + esbuild in a temporary workspace
WORK_DIR=$(mktemp -d)
trap 'rm -rf "$WORK_DIR"' EXIT

cd "$WORK_DIR"
npm init -y --silent > /dev/null 2>&1
npm install --save-dev --save-exact html-to-image@1.11.13 > /dev/null 2>&1
npm install --save-dev --save-exact esbuild@0.25.1 > /dev/null 2>&1

mkdir -p "$VENDOR_DIR"

VERSION=$(node -e "console.log(require('./node_modules/html-to-image/package.json').version)")

npx esbuild node_modules/html-to-image/es/index.js \
  --bundle \
  --format=iife \
  --global-name=htmlToImage \
  --minify \
  --banner:js="/* html-to-image ${VERSION} — generated by scripts/build-html-to-image.sh — DO NOT EDIT */" \
  --outfile="$OUTPUT"

SIZE=$(wc -c < "$OUTPUT")
echo "Built: $OUTPUT (html-to-image@${VERSION}, $SIZE bytes)"
