#!/bin/bash

# Exit immediately if any command fails
set -e

# Define absolute test directory path
TEST_DIR="$(cd .. && pwd)/npm-test"

echo "🧹 1. Nuking old test environment & caches..."
rm -rf "$TEST_DIR"
mkdir -p "$TEST_DIR"
rm -rf ~/.npm/_npx/

# 🎯 FIX 1: Nuke the global npm cache so npx doesn't silently use an old cached version of the tarball!
npm cache clean --force

# Ensure CLI binary permissions are intact
chmod +x bin/cli.js

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

mv "$TARBALL" "$TEST_DIR/"
cd "$TEST_DIR"

echo "🚀 3. Initializing test workspace..."
echo "------------------------------------------------------"
npx --yes --package "$TEST_DIR/$TARBALL" kama init
echo "------------------------------------------------------"

# Detect workspace root
WORKSPACE_DIR="."
if [ ! -f "package.json" ]; then
  WORKSPACE_DIR=$(find . -mindepth 2 -maxdepth 2 -name "package.json" | head -n 1 | xargs dirname)
fi

if [ ! -f "$WORKSPACE_DIR/package.json" ]; then
  echo "❌ Could not find package.json. Aborting test."
  exit 1
fi

cd "$WORKSPACE_DIR"

echo "📦 4. Installing workspace dependencies quietly..."
npm install --loglevel error
npm install "$TEST_DIR/$TARBALL" --save --loglevel error

if [ -d "kama-worker" ]; then
  npm install "$TEST_DIR/$TARBALL" -w kama-worker --save --loglevel error
fi

# 🎯 FIX 2: You MUST inject the local tarball into the site too!
# Otherwise, Astro will download an old Kama package from the internet.
if [ -d "sites/kama-starter" ]; then
  npm install "$TEST_DIR/$TARBALL" -w sites/kama-starter --save --loglevel error
fi

echo ""
echo "======================================================"
echo "✨ KAMA ENVIRONMENT BOOTSTRAPPED SUCCESSFULLY!"
echo "   - Backend Worker: http://localhost:8787"
echo "   - Astro Site:     http://localhost:4321"
echo "======================================================"
echo ""

npm run dev --loglevel error