#!/usr/bin/env bash
# Assemble the installer payload: the app + CPython's embeddable distro.
# Runs on Linux or Windows (git-bash); the .iss compile itself needs Windows.
#
#   installer/build_payload.sh [version] [python-version]
set -euo pipefail
cd "$(dirname "$0")/.."

VER="${1:-$(grep -oP '__version__ = "\K[^"]+' src/clipshelf/__init__.py)}"
PYVER="${2:-3.12.7}"
OUT="installer/payload"
EMBED_URL="https://www.python.org/ftp/python/${PYVER}/python-${PYVER}-embed-amd64.zip"

rm -rf "$OUT"
mkdir -p "$OUT"

# the same tracked files the zip ships, minus dev-only trees
git archive HEAD | tar -x -C "$OUT"
rm -rf "$OUT/tests" "$OUT/scripts" "$OUT/packs" "$OUT/.github" "$OUT/site"
rm -f "$OUT/WINDOWS-TEST.md" "$OUT/docs/TESTING.md" "$OUT/.gitignore" "$OUT/.gitattributes"

# the cs2 pack ships pre-installed, as it does in the zip
mkdir -p "$OUT/plugins"
cp -r packs/cs2-pack "$OUT/plugins/cs2-pack"

# CPython embeddable: no system Python needed, and no PyInstaller — the
# ctranslate2 wheels faster-whisper depends on do not survive freezing
echo "fetching python ${PYVER} embeddable..."
curl -fsSL "$EMBED_URL" -o /tmp/pyembed.zip
mkdir -p "$OUT/python"
unzip -qo /tmp/pyembed.zip -d "$OUT/python"
rm -f /tmp/pyembed.zip

# The ._pth file REPLACES sys.path entirely, so uncommenting `import site`
# is necessary but NOT sufficient — Lib\site-packages has to be named. Get
# this wrong and pip installs succeed while every import fails, which is
# exactly what the first CI run looked like.
for pth in "$OUT"/python/python*._pth; do
    sed -i 's/^#import site/import site/' "$pth" 2>/dev/null || true
    grep -q '^import site' "$pth" || printf '\nimport site\n' >> "$pth"
    grep -q 'site-packages' "$pth" || printf 'Lib\\site-packages\n' >> "$pth"
done
mkdir -p "$OUT/python/Lib/site-packages"

echo "payload: $(du -sh "$OUT" | cut -f1) ($(find "$OUT" -type f | wc -l) files)"
echo "version: $VER"
