#!/bin/bash

# Exit immediately if any command fails
set -e

# 1. Require a target directory argument
TARGET_DIR=$1
if [ -z "$TARGET_DIR" ]; then
  echo "❌ Error: Please provide the target project directory."
  echo "Usage: ./npm-update.sh ../my-existing-project"
  exit 1
fi

# Convert to absolute path so we don't lose it when changing directories
TARGET_DIR=$(cd "$TARGET_DIR" && pwd)

echo "🧹 1. Clearing npm cache..."
npm cache clean --force

echo "🔥 2. Building & packing KAMA package locally..."
npm run build --loglevel error
npm pack --loglevel error

# Find the newly created tarball
TARBALL=$(ls -1t *.tgz | head -n 1)

if [ -z "$TARBALL" ]; then
  echo "❌ Error: Failed to find the packed .tgz file."
  exit 1
fi

# Get the absolute path to the tarball
TARBALL_PATH="$(pwd)/$TARBALL"

echo "🚀 3. Navigating to target project: $TARGET_DIR"
cd "$TARGET_DIR"

echo "🗑️ 4. Nailing old Kama modules to force fresh extraction..."
# If we don't delete these, npm will aggressively cache the old version!
rm -rf node_modules/@brightsideoy/kama
if [ -d "kama-worker" ]; then rm -rf kama-worker/node_modules/@brightsideoy/kama; fi
if [ -d "sites" ]; then rm -rf sites/*/node_modules/@brightsideoy/kama; fi

echo "📦 5. Injecting fresh tarball into workspace..."
npm install "$TARBALL_PATH" --save --loglevel error

if [ -d "kama-worker" ]; then
  echo "   -> Updating kama-worker..."
  npm install "$TARBALL_PATH" -w kama-worker --save --loglevel error
fi

# Automatically loop through ALL frontend sites and update them
if [ -d "sites" ]; then
  for site in sites/*; do
    if [ -d "$site" ]; then
      echo "   -> Updating $site..."
      npm install "$TARBALL_PATH" -w "$site" --save --loglevel error
    fi
  done
fi

echo ""
echo "======================================================"
echo "✨ KAMA PACKAGE UPDATED SUCCESSFULLY!"
echo "Target: $TARGET_DIR"
echo "======================================================"
echo ""