#!/usr/bin/env bash
#
# RankWiz AI WordPress Plugin — Build Script
# Creates a distributable zip file for WordPress deployment.
#
# Usage: ./bin/build.sh [--out /path/to/output]
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
PLUGIN_NAME="rankwiz-ai"

# Read version from main plugin file.
PLUGIN_VERSION=$(grep -m1 "Version:" "${PLUGIN_DIR}/${PLUGIN_NAME}.php" | awk '{print $NF}')
if [ -z "$PLUGIN_VERSION" ]; then
    echo "ERROR: Could not determine plugin version." >&2
    exit 1
fi

BUILD_DIR="${PLUGIN_DIR}/build"
OUTPUT_FILE="${BUILD_DIR}/${PLUGIN_NAME}-${PLUGIN_VERSION}.zip"

# Allow output override via --out flag.
while [[ $# -gt 0 ]]; do
    case $1 in
        --out) OUTPUT_FILE="$2"; shift 2 ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

echo "Building ${PLUGIN_NAME} v${PLUGIN_VERSION}..."

# Clean and recreate build directory.
rm -rf "${BUILD_DIR}/tmp"
mkdir -p "${BUILD_DIR}/tmp/${PLUGIN_NAME}"

# Copy plugin files (exclude dev artifacts).
rsync -a \
    --exclude=".git" \
    --exclude="bin/" \
    --exclude="build/" \
    --exclude="tests/" \
    --exclude="phpunit.xml" \
    --exclude=".phpunit.cache" \
    --exclude=".phpcs.xml.dist" \
    --exclude="composer.json" \
    --exclude="composer.lock" \
    "${PLUGIN_DIR}/" "${BUILD_DIR}/tmp/${PLUGIN_NAME}/"

# Install production Composer dependencies (no dev).
cd "${BUILD_DIR}/tmp/${PLUGIN_NAME}"
if [ -f composer.json ]; then
    composer install --no-dev --optimize-autoloader --no-interaction --quiet
fi

# Create zip.
mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}/tmp"
zip -r "${OUTPUT_FILE}" "${PLUGIN_NAME}/" -x "*.DS_Store" -x "*/.git/*"

# Cleanup temp.
rm -rf "${BUILD_DIR}/tmp"

echo "Build complete: ${OUTPUT_FILE}"
echo "Contents:"
unzip -l "${OUTPUT_FILE}" | head -40
