#!/bin/zsh
set -e  # Exit immediately if any command fails

# --- Configuration ---
SCHEME="FlipTalk"
BUNDLE_ID="com.jaredlog.Flip-Talk"
DEVICE_NAME="iPhone 17 Pro"
BUILD_PATH="./build"  # This ensures Predictable Paths

echo "🚀 Starting Build for $DEVICE_NAME..."

# 1. Boot the simulator if it isn't already running
# We use 'grep' to check status so we don't try to boot an active device
if ! xcrun simctl list devices | grep "$DEVICE_NAME" | grep -q "(Booted)"; then
    echo "⚙️  Booting Simulator..."
    xcrun simctl boot "$DEVICE_NAME"
fi
open -a Simulator

# 2. Build the App
# We use 'env -u' to hide your Homebrew variables (CC, CXX) from Xcode
# We use '-derivedDataPath' to force the build into the local ./build folder
echo "🔨 Compiling..."
env -u CC -u CXX -u LIBCLANG_PATH xcodebuild \
  -scheme "$SCHEME" \
  -destination "platform=iOS Simulator,name=$DEVICE_NAME" \
  -configuration Debug \
  -derivedDataPath "$BUILD_PATH" \
  clean build | xcbeautify

# 3. Locate the .app bundle
# Since we used -derivedDataPath, we know EXACTLY where this is.
APP_PATH="$BUILD_PATH/Build/Products/Debug-iphonesimulator/$SCHEME.app"

if [ ! -d "$APP_PATH" ]; then
    echo "❌ Error: App bundle not found at $APP_PATH"
    exit 1
fi

# 4. Install and Launch
echo "📲 Installing..."
xcrun simctl install "$DEVICE_NAME" "$APP_PATH"

echo "▶️  Launching $BUNDLE_ID..."
xcrun simctl launch "$DEVICE_NAME" "$BUNDLE_ID"

echo "✅ Done!"
