#!/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 to start fresh..."
rm -rf "$TEST_DIR"
mkdir -p "$TEST_DIR"

# Make sure the CLI file is actually executable before packing!
chmod +x bin/cli.js

echo "🔥 2. Packing KAMA locally (this will trigger build scripts)..."
npm pack

# 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

echo "✅ Packaged successfully: $TARBALL"

echo "🚚 3. Moving tarball to test environment..."
mv "$TARBALL" "$TEST_DIR/"

echo "📂 4. Entering test environment..."
cd "$TEST_DIR"

echo "🚀 5. Simulating 'npx kama init' using the local tarball..."
echo "------------------------------------------------------"

# Explicitly define the package source and the binary to run
npx --yes --package "$TEST_DIR/$TARBALL" kama init

echo "------------------------------------------------------"
echo "🔍 6. Detecting generated workspace..."

# Figure out if user initialized in current folder (.) or a subfolder
if [ -f "package.json" ]; then
  WORKSPACE_DIR="."
else
  # Find the first created directory that contains a package.json
  WORKSPACE_DIR=$(find . -mindepth 2 -maxdepth 2 -name "package.json" | head -n 1 | xargs dirname)
fi

# Sanity check
if [ ! -f "$WORKSPACE_DIR/package.json" ]; then
  echo "❌ Could not find a package.json. Did the setup abort?"
  exit 1
fi

echo "✅ Found workspace at: $WORKSPACE_DIR"
cd "$WORKSPACE_DIR"

echo "📦 7. Installing NPM dependencies..."
npm install

echo "🔥 8. Booting up KAMA (CMS & Astro Site)..."
echo "👉 You should see localhost URLs below to click and test."
echo "   (Press Ctrl+C to stop the servers. Running this script again will wipe everything and restart.)"
echo "------------------------------------------------------"
npm run dev