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

# Resolve plugin root (one level up from this script)
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC_NAME="$(basename "$ROOT")"
PLUGIN_DIR_NAME="${PLUGIN_DIR_NAME:-$SRC_NAME}"
PLUGIN_ZIP_NAME="${PLUGIN_ZIP_NAME:-$SRC_NAME}"

if [ -z "$PLUGIN_DIR_NAME" ]; then
  PLUGIN_DIR_NAME="$SRC_NAME"
fi

OUT_ZIP="${ROOT}/../${PLUGIN_ZIP_NAME}.zip"

echo "Packaging '${PLUGIN_DIR_NAME}' → '${OUT_ZIP}'"

SRC_DIR="$ROOT"
STAGING=""
if [ "$PLUGIN_DIR_NAME" != "$SRC_NAME" ]; then
  STAGING="$(mktemp -d)"
  DEST="${STAGING}/${PLUGIN_DIR_NAME}"
  if command -v rsync >/dev/null 2>&1; then
    mkdir -p "$DEST"
    rsync -a \
      --exclude=".venv/" \
      --exclude="venv/" \
      --exclude="__pycache__/" \
      --exclude="**/__pycache__/" \
      --exclude=".git/" \
      --exclude=".idea/" \
      --exclude=".vscode/" \
      --exclude="dev/" \
      --exclude="test/" \
      --exclude="tests/" \
      --exclude="node_modules/" \
      --exclude="build-static-jsoneditor.sh" \
      --exclude="Makefile" \
      --exclude="pylintrc" \
      --exclude="qgis_with_venv.sh" \
      --exclude="plugin_upload.py" \
      --exclude="user-history.db" \
      "$ROOT"/ "$DEST"/
  else
    cp -a "$ROOT" "$DEST"
    rm -rf \
      "$DEST/.venv" \
      "$DEST/venv" \
      "$DEST/.git" \
      "$DEST/.idea" \
      "$DEST/.vscode" \
      "$DEST/dev" \
      "$DEST/test" \
      "$DEST/tests" \
      "$DEST/node_modules"
    find "$DEST" -type d -name "__pycache__" -prune -exec rm -rf {} +
    rm -f \
      "$DEST/build-static-jsoneditor.sh" \
      "$DEST/Makefile" \
      "$DEST/pylintrc" \
      "$DEST/qgis_with_venv.sh" \
      "$DEST/plugin_upload.py" \
      "$DEST/user-history.db"
  fi
  SRC_DIR="$DEST"
  SRC_NAME="$PLUGIN_DIR_NAME"
fi

cd "$(dirname "$SRC_DIR")"
rm -f "$OUT_ZIP"

zip -r "$OUT_ZIP" "$SRC_NAME" \
  -x "$SRC_NAME/.venv/*" \
     "$SRC_NAME/venv/*" \
     "$SRC_NAME/**/__pycache__/*" \
     "$SRC_NAME/__pycache__/*" \
     "$SRC_NAME/.git/*" \
     "$SRC_NAME/.idea/*" \
     "$SRC_NAME/.vscode/*" \
     "$SRC_NAME/dev/*" \
     "$SRC_NAME/test/*" \
     "$SRC_NAME/tests/*" \
     "$SRC_NAME/node_modules/*" \
     "$SRC_NAME/build-static-jsoneditor.sh" \
     "$SRC_NAME/Makefile" \
     "$SRC_NAME/pylintrc" \
     "$SRC_NAME/qgis_with_venv.sh" \
     "$SRC_NAME/plugin_upload.py" \
     "$SRC_NAME/user-history.db"

if [ -n "$STAGING" ]; then
  rm -rf "$STAGING"
fi

echo "Done. Install via: Plugins → Install from ZIP → ${PLUGIN_ZIP_NAME}.zip"
