#!/bin/bash
set -e

echo "🚀 Starting Automated APK Build in WSL..."

# --- SETUP JAVA 21 (Portable) ---
JAVA_DIR="$HOME/java-21"
if [ ! -d "$JAVA_DIR" ]; then
    echo "⬇️ Downloading OpenJDK 21 (Temurin)..."
    mkdir -p "$JAVA_DIR"
    cd "$JAVA_DIR"
    # Adoptium Temurin JDK 21
    wget -q -L https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2%2B13/OpenJDK21U-jdk_x64_linux_hotspot_21.0.2_13.tar.gz -O jdk21.tar.gz
    tar -xzf jdk21.tar.gz --strip-components=1
    rm jdk21.tar.gz
    echo "✅ Java 21 Installed."
else
    echo "✅ Java 21 already present."
fi

export JAVA_HOME="$JAVA_DIR"
export PATH="$JAVA_HOME/bin:$PATH"

# --- SETUP ANDROID SDK ---
SDK_DIR="$HOME/android-sdk"
mkdir -p "$SDK_DIR/cmdline-tools"

if [ ! -d "$SDK_DIR/cmdline-tools/latest" ]; then
    echo "⬇️ Downloading Android Command Line Tools..."
    cd "$SDK_DIR/cmdline-tools"
    wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O tools.zip
    unzip -q tools.zip
    mv cmdline-tools latest
    rm tools.zip
    echo "✅ Tools downloaded."
else
    echo "✅ Android Tools already present."
fi

export ANDROID_HOME="$SDK_DIR"
export PATH="$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools"

# --- INSTALL SDK PACKAGES ---
echo "📦 Checking SDK Packages..."
yes | sdkmanager --licenses > /dev/null
# Only install if missing to save time
if [ ! -d "$SDK_DIR/platforms/android-35" ]; then
    echo "⬇️ Installing Platform 35..."
    sdkmanager "platform-tools" "platforms;android-35" "build-tools;35.0.0" > /dev/null
fi

# --- BUILD APK ---
PROJECT_DIR="/mnt/e/TRAE Playground/MindShift-Windows/android"
cd "$PROJECT_DIR"

echo "🔨 Building APK with Java 21..."
chmod +x gradlew
./gradlew assembleDebug

# --- SUCCESS ---
echo "🎉 Build Complete!"
echo "APK Location: $PROJECT_DIR/app/build/outputs/apk/debug/app-debug.apk"
