#!/bin/bash
# Deploy APK to connected Android device

set -e

echo "📱 Deploying to Android device..."
echo ""

# Check if device is connected
if ! adb devices | grep -q "device$"; then
    echo "❌ No Android device connected!"
    echo "Please connect a device or start an emulator."
    exit 1
fi

# Build type: debug or release (default: debug). `--debug` alongside `release`
# means the side-by-side release build — same APK path, but it was packaged
# under the .debug applicationId, so the package to launch differs.
BUILD_TYPE="debug"
SIDE_BY_SIDE=0
for arg in "$@"; do
    case "$arg" in
        --debug|--side-by-side) SIDE_BY_SIDE=1 ;;
        debug|release) BUILD_TYPE="$arg" ;;
    esac
done
[ "$BUILD_TYPE" = "debug" ] && SIDE_BY_SIDE=1

# The .debug applicationId (see src-tauri/android/app/build.gradle.kts) is a
# separate package, so it installs alongside a real release build — no
# uninstall dance needed.
if [ "$BUILD_TYPE" = "release" ]; then
    APK_PATH="src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk"
else
    APK_PATH="src-tauri/gen/android/app/build/outputs/apk/universal/debug/app-universal-debug.apk"
fi

if [ "$SIDE_BY_SIDE" = "1" ]; then
    APP_PACKAGE="com.dtourolle.jellytau.debug"
else
    APP_PACKAGE="com.dtourolle.jellytau"
fi

# Check if APK exists
if [ ! -f "$APK_PATH" ]; then
    echo "❌ APK not found at: $APK_PATH"
    if [ "$BUILD_TYPE" = "release" ] && [ "$SIDE_BY_SIDE" = "1" ]; then
        echo "Run './scripts/build-android.sh release --debug' first"
    else
        echo "Run './scripts/build-android.sh $BUILD_TYPE' first"
    fi
    exit 1
fi

echo "📦 Installing APK: $APK_PATH"
echo "📛 Package: $APP_PACKAGE"

if ! adb install -r "$APK_PATH"; then
    echo ""
    echo "❌ Install failed."
    echo "   If it says INSTALL_FAILED_UPDATE_INCOMPATIBLE, an older build of"
    echo "   '$APP_PACKAGE' signed with a different key is still installed."
    echo "   Uninstall just that one and retry:"
    echo "     adb uninstall $APP_PACKAGE"
    exit 1
fi

echo ""
echo "✅ Deployment complete!"
echo "🚀 Launching..."
adb shell monkey -p "$APP_PACKAGE" -c android.intent.category.LAUNCHER 1 > /dev/null 2>&1 \
    || echo "   (auto-launch failed — start it from the launcher)"
