#!/usr/bin/env bash
# create-pulse-resources-android.sh
# Gradle build script for generating Pulse Updates embedded resources for Android
# Based on expo-updates create-updates-resources.gradle

set -eo pipefail

# This script should be called from the app's build.gradle
# Example:
#   tasks.register("createPulseResources") {
#       doLast {
#           exec {
#               commandLine "bash", "${rootProject.projectDir}/../node_modules/pulse-updates/scripts/create-pulse-resources-android.sh"
#               environment "ANDROID_ASSETS_DIR", "${projectDir}/src/main/assets"
#               environment "RUNTIME_VERSION", android.defaultConfig.versionName
#           }
#       }
#   }

echo "[PulseUpdates] Generating embedded manifest for Android..."

PULSE_UPDATES_PACKAGE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"

# Assets directory (passed from Gradle)
ASSETS_DIR="${ANDROID_ASSETS_DIR:-./android/app/src/main/assets}"

# Runtime version (passed from Gradle or env)
RUNTIME_VERSION="${RUNTIME_VERSION:-${PULSE_RUNTIME_VERSION:-unknown}}"

# Find the bundle
BUNDLE_PATH=""
for candidate in "index.android.bundle" "index.bundle" "main.jsbundle"; do
    if [ -f "$ASSETS_DIR/$candidate" ]; then
        BUNDLE_PATH="$ASSETS_DIR/$candidate"
        break
    fi
done

if [ -z "$BUNDLE_PATH" ]; then
    echo "[PulseUpdates] No bundle found in $ASSETS_DIR"
    echo "[PulseUpdates] Skipping embedded manifest generation."
    exit 0
fi

# Find node
NODE_BIN=""
if command -v node &> /dev/null; then
    NODE_BIN="node"
elif [ -x "/usr/local/bin/node" ]; then
    NODE_BIN="/usr/local/bin/node"
elif [ -x "/opt/homebrew/bin/node" ]; then
    NODE_BIN="/opt/homebrew/bin/node"
fi

if [ -z "$NODE_BIN" ]; then
    echo "[PulseUpdates] Node.js not found"
    exit 1
fi

echo "[PulseUpdates] Bundle: $BUNDLE_PATH"
echo "[PulseUpdates] Runtime version: $RUNTIME_VERSION"
echo "[PulseUpdates] Using Node.js: $NODE_BIN"

# Create pulse directory
PULSE_DIR="$ASSETS_DIR/pulse"
mkdir -p "$PULSE_DIR"

# Look for assets in drawable/raw folders or assets folder
ASSETS_PATH=""
if [ -d "$ASSETS_DIR/../res/drawable-mdpi" ]; then
    # Metro bundler puts assets in res/drawable-*
    # We need to collect them differently for Android
    ASSETS_PATH=""  # Skip for now, Android handles assets differently
elif [ -d "$ASSETS_DIR/assets" ]; then
    ASSETS_PATH="$ASSETS_DIR/assets"
fi

# Run the generate-embedded-manifest.mjs script
"$NODE_BIN" "$PULSE_UPDATES_PACKAGE_DIR/scripts/generate-embedded-manifest.mjs" \
    --bundle "$BUNDLE_PATH" \
    --out "$ASSETS_DIR" \
    --platform android \
    --runtime-version "$RUNTIME_VERSION" \
    ${ASSETS_PATH:+--assets "$ASSETS_PATH"} \
    --asset-prefix ""

if [ $? -eq 0 ]; then
    echo "[PulseUpdates] Embedded manifest generated successfully"
    echo "[PulseUpdates] Output: $PULSE_DIR/embedded-manifest.json"
else
    echo "[PulseUpdates] Failed to generate embedded manifest"
    exit 1
fi
