#!/bin/bash

# Set script directory and plugin root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PLUGIN_ROOT"

# Extract plugin version from the main plugin file
VERSION=$(grep "Version:" sync-plugin.php | head -n 1 | sed 's/.*Version: *//' | sed 's/ *$//')
PLUGIN_NAME="raptive-seo"

# Create build directory
BUILD_DIR="build"
TEMP_DIR="$BUILD_DIR/$PLUGIN_NAME"

echo "Building $PLUGIN_NAME version $VERSION..."

# Clean up any existing build
rm -rf "$BUILD_DIR"
mkdir -p "$TEMP_DIR"

echo "Copying plugin files..."

# Copy plugin files (exclude unwanted files and directories)
rsync -av \
    --exclude=".git*" \
    --exclude="README.md" \
    --exclude="scripts/" \
    --exclude="build/" \
    --exclude=".DS_Store" \
    --exclude="Thumbs.db" \
    --exclude="*.log" \
    --exclude="node_modules/" \
    --exclude=".env*" \
    --exclude="assets/" \
    ./ "$TEMP_DIR/"

# Create the ZIP file
cd "$BUILD_DIR"
ZIP_FILE="../${PLUGIN_NAME}-${VERSION}.zip"

echo "Creating ZIP file: $ZIP_FILE"
zip -r "$ZIP_FILE" "$PLUGIN_NAME"

# Clean up temp directory
cd "$PLUGIN_ROOT"
rm -rf "$BUILD_DIR"

echo "✅ Plugin ZIP created successfully: ${PLUGIN_NAME}-${VERSION}.zip"
echo "Files included in the package:"
echo "  ✓ admin/"
echo "  ✓ includes/"
echo "  ✓ public/"
echo "  ✓ sync-plugin.php"
echo "  ✓ readme.txt"
echo "  ✓ uninstall.php"
echo ""
echo "Files excluded:"
echo "  ✗ README.md"
echo "  ✓ assets/"
echo "  ✗ .git/ (and all git-related files)"
echo "  ✗ scripts/"
echo "  ✗ .DS_Store, Thumbs.db, *.log files"
echo "  ✗ node_modules/, .env* files"