#!/bin/zsh
set -e
d=${0:a:h}
cd $d

source $d/.env

function sediment() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
        sed -i '' "$@"
    else
        sed -i "$@"
    fi
}

#xcrun simctl uninstall booted $BUNDLE_ID

echo "Running iOS preview workflow..."
cd "$REPO_DIR"

# 0. Environment Setup (Fix Node Version)
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
echo "Checking Node version..."
if command -v nvm >/dev/null; then
    nvm use 22 || nvm use 20 || echo "Warning: Could not switch to Node 22/20. Current: $(node -v)"
else
    echo "nvm not found, using system node: $(node -v)"
fi

# 1. Install dependencies
echo "1. Installing dependencies (yarn)..."
yarn install

# 1.5. Copy assets
echo "1.5. Copying assets..."
ASSETS_DIR="${0:a:h}/assets"
if [ -d "$ASSETS_DIR" ]; then
	cp -rf "$ASSETS_DIR/"* "$REPO_DIR/assets/"
	echo "✅ Copied all assets (including logo.png, logo-1024.png)"
else
	echo "⚠️  Warning: $ASSETS_DIR not found"
fi

# 1.8. Update package.json version (prevent App Store version conflict)
echo "1.8. Updating package.json version..."
if [ -n "$APP_VERSION" ]; then
    node -e "
        const fs = require('fs');
        const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
        pkg.version = '$APP_VERSION';
        fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\n');
    "
    echo "   ✅ Set version to $APP_VERSION"
else
    echo "   ⚠️  APP_VERSION not set in .env"
fi

# 1.9. Update buildNumber (CFBundleVersion) with current timestamp
echo "1.9. Updating buildNumber..."
build_number=$(date +%y%m%d%H%M%S)
sediment "s/buildNumber: '[0-9]*'/buildNumber: '${build_number}'/" "./app.config.js"
echo "   ✅ Set buildNumber to $build_number"

# 2. Prebuild (Generate ios directory)
echo "2. Running Expo Prebuild..."
# Clean old ios folder to remove old entitlements/AppClip targets
rm -rf ios
npx expo prebuild --platform ios --clean

# 3. CocoaPods
echo "3. Installing CocoaPods..."
cd ios
pod install
cd ..

# 4. Signing (Automated)
echo "4. Configuring Xcode Signing..."
XCODE_PROJ="ios/${APP_NAME}.xcodeproj"
if [ ! -d "$XCODE_PROJ" ]; then
    XCODE_PROJ=$(find ios -name "*.xcodeproj" | head -n 1)
fi
PBXPROJ="$XCODE_PROJ/project.pbxproj"

# Set DEVELOPMENT_TEAM in pbxproj
if [ -n "$DEVELOPMENT_TEAM" ]; then
    echo "   Setting DEVELOPMENT_TEAM=$DEVELOPMENT_TEAM"
    # Add DEVELOPMENT_TEAM to all build configurations
    sediment "s/PRODUCT_BUNDLE_IDENTIFIER = /DEVELOPMENT_TEAM = $DEVELOPMENT_TEAM; PRODUCT_BUNDLE_IDENTIFIER = /g" "$PBXPROJ"
    # Also set where it might already exist but be empty
    sediment "s/DEVELOPMENT_TEAM = \"\";/DEVELOPMENT_TEAM = $DEVELOPMENT_TEAM;/g" "$PBXPROJ"
    sediment "s/DEVELOPMENT_TEAM = ;/DEVELOPMENT_TEAM = $DEVELOPMENT_TEAM;/g" "$PBXPROJ"
fi

# Create/Update entitlements file with App Group
ENTITLEMENTS_FILE="ios/${APP_NAME}/${APP_NAME}.entitlements"
if [ -n "$APP_GROUP" ]; then
    echo "   Setting APP_GROUP=$APP_GROUP"
    cat > "$ENTITLEMENTS_FILE" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>aps-environment</key>
    <string>development</string>
    <key>com.apple.security.application-groups</key>
    <array>
        <string>${APP_GROUP}</string>
    </array>
</dict>
</plist>
EOF
    # Add CODE_SIGN_ENTITLEMENTS to pbxproj if not present
    if ! grep -q "CODE_SIGN_ENTITLEMENTS" "$PBXPROJ"; then
        sediment "s/DEVELOPMENT_TEAM = $DEVELOPMENT_TEAM;/DEVELOPMENT_TEAM = $DEVELOPMENT_TEAM; CODE_SIGN_ENTITLEMENTS = ${APP_NAME}\\/${APP_NAME}.entitlements;/g" "$PBXPROJ"
    fi
fi

echo "✅ Signing configured automatically"

# (Old manual step - commented out)
# open "$XCODE_PROJ"
# echo "========================================================"
# echo " [ACTION REQUIRED] "
# echo " Xcode opened ($XCODE_PROJ)."
# echo " 1. Go to 'Signing & Capabilities' tab."
# echo " 2. Select your Team."
# echo " 3. Verify 'App Clip' target is gone."
# echo " 4. Ensure no red errors exist."
# echo " Press ENTER here once you are done to continue building."
# echo "========================================================"
# read

# 5. Run
echo "5. Building and Running..."
# If user wants specific device ID, uncomment below, otherwise let Expo ask/pick boot simulator

case $1 in
	d|devicei)
		npx expo run:ios --device "$DEVICE_ID" --configuration Release
		;;
	*)
		npx expo run:ios
		;;
esac
