#!/bin/bash
set -euo pipefail

# Nom du plugin (doit correspondre au slug WordPress.org)
PLUGIN_SLUG="ai-builder"

# Dossiers source et destination
SOURCE_DIR="./${PLUGIN_SLUG}"
DEST_DIR="./${PLUGIN_SLUG}/svn-ready"
FOLDER_NAME="trunk"
ASSETS_FOLDER_NAME="assets"

cd ..

# Fail only if an *active* (non-commented) window.config block sets apiUrl to localhost.
# Lines that are entirely // comments are ignored, so commented DEV blocks do not trigger.
CONFIG_FILE="${PLUGIN_SLUG}/config.js"
# Regex in a variable: a literal ";" inside [[ =~ ... ]] would otherwise end the test.
wc_close_re='\}[[:space:]]*;'
if [[ -f "$CONFIG_FILE" ]]; then
  in_wc_block=0
  while IFS= read -r line || [[ -n "$line" ]]; do
    [[ "$line" =~ ^[[:space:]]*// ]] && continue
    if [[ "$line" =~ window\.config[[:space:]]*=[[:space:]]*\{ ]]; then
      in_wc_block=1
    fi
    if (( in_wc_block )) && [[ "$line" == *apiUrl* ]]; then
      line_lc=$(echo "$line" | tr '[:upper:]' '[:lower:]')
      if [[ "$line" =~ 127\.0\.0\.1 ]] || [[ "$line_lc" == *localhost* ]]; then
        echo "API URL NOT SET TO PROD" >&2
        exit 1
      fi
    fi
    if (( in_wc_block )) && [[ "$line" =~ $wc_close_re ]]; then
      in_wc_block=0
    fi
  done < "$CONFIG_FILE"
fi

# Créer les dossiers de destination (structure SVN : trunk + assets)
mkdir -p "$DEST_DIR/$FOLDER_NAME"
mkdir -p "$DEST_DIR/$ASSETS_FOLDER_NAME"

# Copier le code vers trunk/ en excluant ce qui ne doit pas partir
rsync -av \
  --exclude 'assets/js/node_modules/*' \
  --exclude '.git/*' \
  --exclude '.gitignore' \
  --exclude 'zips/*' \
  --exclude 'prepare-project-for-zip.sh' \
  --exclude '.DS_Store' \
  --exclude 'assets/.DS_Store' \
  --exclude 'assets/js/.DS_Store' \
  --exclude 'assets/banner-*.png' \
  --exclude 'assets/banner-*.jpg' \
  --exclude 'assets/icon-*.jpeg' \
  --exclude 'assets/icon-*.png' \
  --exclude 'assets/screenshot-*.jpg' \
  --exclude 'assets/screenshot-*.png' \
  --exclude 'svn-ready/*' \
  "$SOURCE_DIR/" "$DEST_DIR/$FOLDER_NAME/"

# Copier uniquement les assets images vers assets/
shopt -s nullglob
if [ -d "$SOURCE_DIR/$ASSETS_FOLDER_NAME" ]; then
  cp "$SOURCE_DIR/$ASSETS_FOLDER_NAME"/*.{png,jpg,jpeg} "$DEST_DIR/$ASSETS_FOLDER_NAME/" 2>/dev/null || true
fi
shopt -u nullglob

echo "✅ Structure SVN prête dans : $DEST_DIR"
echo "Contenu :"
tree "$DEST_DIR" || ls -R "$DEST_DIR"
