#!/bin/bash
# Build Android APK

set -e

# Source Rust environment
source "$HOME/.cargo/env.fish" 2>/dev/null || source "$HOME/.cargo/env" 2>/dev/null || true

# Set Android environment variables
export ANDROID_HOME="$HOME/Android/Sdk"
export NDK_HOME="$ANDROID_HOME/ndk/$(ls "$ANDROID_HOME/ndk" | head -1)"

echo "🤖 Building Android APK..."
echo "Android SDK: $ANDROID_HOME"
echo "NDK: $NDK_HOME"
echo ""

# Parse args: build type (debug/release) and optional --clean flag.
# By default the build is INCREMENTAL — Cargo and Vite reuse their caches.
# Pass --clean (or CLEAN=1) to wipe all caches for a from-scratch build.
BUILD_TYPE="debug"
CLEAN="${CLEAN:-0}"
for arg in "$@"; do
    case "$arg" in
        --clean) CLEAN=1 ;;
        debug|release) BUILD_TYPE="$arg" ;;
    esac
done

# Step 0: Optionally clear build caches for a fully fresh build.
if [ "$CLEAN" = "1" ]; then
    echo "🧹 Clearing build caches (clean build)..."
    rm -rf node_modules/.vite dist .svelte-kit .next build target src-tauri/target 2>/dev/null || true
    npm install > /dev/null 2>&1
fi

# Step 1: Sync Android source files
echo "🔄 Syncing Android sources..."
./scripts/sync-android-sources.sh

# Step 2: Build the frontend first to avoid dev server issues
echo "🎨 Building frontend..."
bun run build

# Step 2: Build Android APK
if [ "$BUILD_TYPE" = "release" ]; then
    # Configure release signing from .env (single source of truth). Must run
    # after sync-android-sources.sh, since gen/android is (re)generated there.
    ./scripts/write-keystore-properties.sh
    echo "📦 Building release APK..."
    bun run tauri android build --apk true
else
    echo "📦 Building debug APK..."
    bun run tauri android build --apk true --debug
fi

echo ""
echo "✅ APK build complete!"
echo "📱 APK location: src-tauri/gen/android/app/build/outputs/apk/"
