#!/usr/bin/env bash
set -e

echo "🚀 JellyTau Android Development Helper"
echo "======================================"

# Setup environment
echo "Setting up environment..."
source "$HOME/.cargo/env.fish" 2>/dev/null || source "$HOME/.cargo/env" || true
export ANDROID_HOME="$HOME/Android/Sdk"
export NDK_HOME="$ANDROID_HOME/ndk/$(ls $ANDROID_HOME/ndk 2>/dev/null | head -1)"

# Check prerequisites
echo -e "\n✓ Checking prerequisites..."

if ! command -v rustc &> /dev/null; then
    echo "❌ Rust not found. Please install from https://rustup.rs"
    exit 1
fi

if ! command -v adb &> /dev/null; then
    echo "❌ ADB not found. Please install Android SDK"
    exit 1
fi

if [ ! -d "$ANDROID_HOME" ]; then
    echo "⚠️  ANDROID_HOME not found at $ANDROID_HOME"
    echo "   Please install Android SDK or update the path"
fi

# Check for connected devices
echo -e "\n📱 Connected devices:"
adb devices

# Menu
echo -e "\n📋 What would you like to do?"
echo "1) Run in development mode (hot reload)"
echo "2) Build debug APK"
echo "3) Build release APK"
echo "4) Install debug APK to device"
echo "5) Check environment"
read -p "Select option (1-5): " choice

case $choice in
    1)
        echo -e "\n🔨 Starting development mode..."
        bun run tauri android dev
        ;;
    2)
        echo -e "\n🔨 Building debug APK..."
        bun run tauri android build --debug
        echo -e "\n✅ Debug APK built at:"
        echo "   src-tauri/gen/android/app/build/outputs/apk/debug/app-debug.apk"
        ;;
    3)
        echo -e "\n🔨 Building release APK..."
        bun run tauri android build
        echo -e "\n✅ Release APK built at:"
        echo "   src-tauri/gen/android/app/build/outputs/apk/release/"
        ;;
    4)
        APK="src-tauri/gen/android/app/build/outputs/apk/debug/app-debug.apk"
        if [ -f "$APK" ]; then
            echo -e "\n📲 Installing to device..."
            adb install -r "$APK"
            echo "✅ Installed!"
        else
            echo "❌ APK not found. Build it first (option 2)"
        fi
        ;;
    5)
        echo -e "\n🔍 Environment Check:"
        echo "  Rust: $(rustc --version 2>/dev/null || echo 'Not found')"
        echo "  Cargo: $(cargo --version 2>/dev/null || echo 'Not found')"
        echo "  Bun: $(bun --version 2>/dev/null || echo 'Not found')"
        echo "  ADB: $(adb --version 2>/dev/null | head -1 || echo 'Not found')"
        echo "  ANDROID_HOME: $ANDROID_HOME"
        echo "  NDK_HOME: $NDK_HOME"
        echo ""
        echo "  Rust Android targets:"
        rustup target list 2>/dev/null | grep android | grep installed || echo "    None installed"
        ;;
    *)
        echo "Invalid option"
        exit 1
        ;;
esac
