#!/bin/bash

# Define where our temporary node shim lives
SHIM_DIR="/tmp/antigravity_bin"
NODE_SHIM="$SHIM_DIR/node"

# Check if 'node' is already in PATH
if ! command -v node &> /dev/null; then
    echo "⚠️  Node.js not found in PATH."
    
    # Check if 'bun' is available to fill in
    if command -v bun &> /dev/null; then
        echo "✅ Found Bun! Creating a compatibility shim for Node..."
        
        # Create shim directory
        mkdir -p "$SHIM_DIR"
        
        # Create the shim script
        echo '#!/bin/sh' > "$NODE_SHIM"
        echo 'exec bun "$@"' >> "$NODE_SHIM"
        chmod +x "$NODE_SHIM"
        
        # Add to PATH
        export PATH="$SHIM_DIR:$PATH"
        
        echo "🔧 Shim created at $NODE_SHIM"
    else
        echo "❌ Error: Neither 'node' nor 'bun' was found."
        echo "Please install Node.js or Bun to run this application."
        exit 1
    fi
fi

# Ensure dependencies are installed (specifically checking for vite)
if [ ! -f "node_modules/.bin/vite" ]; then
    echo "📦 Dependencies incomplete (vite binary missing)."
    echo "⏳ Running pnpm install to fix... (This may take a while on network drives)"
    
    # Run install and show output
    pnpm install
    
    if [ $? -ne 0 ]; then
       echo "❌ Installation failed. Please check the network connection or drive permissions."
       exit 1
    fi
fi

echo "🚀 Starting Antigravity..."
# Check for vite again to be sure
if [ ! -f "node_modules/.bin/vite" ]; then
   echo "❌ Error: 'vite' binary still not found after install."
   echo "This might be due to the 'noexec' mount option on your drive preventing symlink creation in node_modules/.bin."
   echo "Trying to run via node directly..."
   
   # Fallback: finding the vite script manually if bin is missing
   VITE_PATH=$(find node_modules -name vite.js | head -n 1)
   if [ -z "$VITE_PATH" ]; then
       # try package.json
       VITE_PKG="node_modules/vite/bin/vite.js"
       if [ -f "$VITE_PKG" ]; then
           node "$VITE_PKG"
       else
           echo "❌ Could not find vite.js source."
           exit 1
       fi
   else 
       node "$VITE_PATH"
   fi
else
   # Run the electron dev environment
   pnpm dev:electron
fi
