#!/usr/bin/env bash
# bin/build-wp-plugin.sh
# Packages the RankWiz WP plugin into a distributable zip for self-hosted distribution.
# Usage: ./bin/build-wp-plugin.sh

set -euo pipefail

PLUGIN_DIR="wp-plugin/rankwiz-ai"
VERSION=$(grep "Version:" "$PLUGIN_DIR/rankwiz-ai.php" | awk '{print $2}')

if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "ERROR: Could not extract a valid semver VERSION from rankwiz-ai.php (got: '${VERSION}')" >&2
  exit 1
fi

OUTPUT="storage/app/downloads/rankwiz-ai-${VERSION}.zip"
TEMP_DIR=$(mktemp -d)
trap 'rm -rf "$TEMP_DIR"' EXIT

echo "Building RankWiz WordPress plugin v${VERSION}…"

# Copy plugin files, excluding dev artifacts
rsync -a \
  --exclude='tests/' \
  --exclude='phpunit.xml' \
  --exclude='.gitignore' \
  --exclude='bin/' \
  --exclude='composer.lock' \
  "$PLUGIN_DIR/" "$TEMP_DIR/rankwiz-ai/"

# Install production dependencies only (if composer.phar exists in plugin dir)
if [ -f "$PLUGIN_DIR/composer.phar" ]; then
  (cd "$TEMP_DIR/rankwiz-ai" && php composer.phar install --no-dev --optimize-autoloader --no-interaction 2>/dev/null)
fi

# Create output directory and zip
mkdir -p "$(dirname "$OUTPUT")"
(cd "$TEMP_DIR" && zip -r "$OLDPWD/$OUTPUT" rankwiz-ai/)

FILE_SIZE=$(du -sh "$OUTPUT" | cut -f1)
echo "Built: $OUTPUT ($VERSION) — $FILE_SIZE"

# Warn if zip exceeds 10MB (WordPress default upload limit)
FILE_BYTES=$(wc -c < "$OUTPUT")
if [ "$FILE_BYTES" -gt 10485760 ]; then
  echo "WARNING: zip exceeds 10MB ($FILE_SIZE). Some WordPress installs may reject the upload." >&2
fi
