#!/bin/bash

BASE="ratelimitsucks"
TOTAL=10
PARALLEL=4

# Cache the original package.json contents in memory
PKG_CONTENT=$(cat package.json)

draw_progress() {
  local current=$1
  local total=$2
  local percent=$(( current * 100 / total ))
  local bar_size=30
  local filled=$(( current * bar_size / total ))
  local empty=$(( bar_size - filled ))

  local bar=$(printf "%${filled}s" | tr ' ' '#')
  local spaces=$(printf "%${empty}s" | tr ' ' '-')

  printf "\rProgress: [%s%s] %d%% (%d/%d)" "$bar" "$spaces" "$percent" "$current" "$total"
}

publish_one() {
  local NAME=$1
  local TMP_DIR
  
  # Create isolated temp folder
  TMP_DIR=$(mktemp -d 2>/dev/null || mktemp -d -t 'tmp_npm')

  (
    # FIX: Copy ALL project files (like logo.svg), but leave behind heavy folders
    if command -v rsync >/dev/null 2>&1; then
      rsync -a --exclude='node_modules' --exclude='.git' ./ "$TMP_DIR/" 2>/dev/null
    else
      cp -R . "$TMP_DIR" 2>/dev/null
      rm -rf "$TMP_DIR/node_modules" "$TMP_DIR/.git" 2>/dev/null
    fi

    cd "$TMP_DIR" || exit 1
    
    # Write and update package.json
    echo "$PKG_CONTENT" > package.json
    node -e "
      const fs = require('fs');
      const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
      pkg.name = process.argv[1];
      fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
    " "$NAME"

    # Publish fully complete package
    npm publish --silent > /dev/null 2>&1
  )

  # Clean up temp folder
  rm -rf "$TMP_DIR"
  echo "$NAME"
}

echo "Starting automated deployment..."
echo "========================================="
draw_progress 0 "$TOTAL"

completed=0
while read -r FINISHED_PKG
do
  completed=$((completed + 1))
  
  # Live UI: Wipes progress line, prints completed pkg, redraws bar below it
  printf "\r\033[K"
  echo " ✓ Uploaded: $FINISHED_PKG"
  draw_progress "$completed" "$TOTAL"

done < <(
  count=1
  while [ "$count" -le "$TOTAL" ]
  do
    while [ "$(jobs -p | wc -l)" -ge "$PARALLEL" ]
    do
      sleep 0.05
    done

    # Iteration formatting (e.g., ratelimitsucks, ratelimitsucks1, ratelimitsucks2...)
    if [ "$count" -eq 1 ]; then
      publish_one "${BASE}" &
    else
      publish_one "${BASE}$((count - 1))" &
    fi
    count=$((count + 1))
  done
  
  wait
)

# Clear progress bar one last time for the final complete block
printf "\r\033[K"
echo -e "\n=========================================\nALL PACKAGES DEPLOYED CLEANLY"