#!/usr/bin/env bash

set -euo pipefail

cd "$(dirname "$0")/.."
REPO_ROOT="$(pwd)"

NDK_ROOT="${ANDROID_NDK_HOME:-}"
if [[ -z "$NDK_ROOT" && -n "${ANDROID_HOME:-}" ]]; then
    NDK_ROOT="$(find "$ANDROID_HOME/ndk" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | sort | tail -1 || true)"
fi
if [[ -z "$NDK_ROOT" && -n "${ANDROID_SDK_ROOT:-}" ]]; then
    NDK_ROOT="$(find "$ANDROID_SDK_ROOT/ndk" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | sort | tail -1 || true)"
fi

ANDROID_PLATFORM=28
JNI_LIBS_DIR="$REPO_ROOT/apps/chanora_flutter/android/app/src/main/jniLibs"

declare -a BUILDS=(
    "arm64-v8a;aarch64-linux-android;/tmp/opus-android-arm64-v8a"
    "armeabi-v7a;armv7-linux-androideabi;/tmp/opus-android-armeabi-v7a"
    "x86_64;x86_64-linux-android;/tmp/opus-android-x86_64"
)

bar() { printf '%s\n' '========================================================================'; }

require_cmd() {
    local cmd=$1
    if ! command -v "$cmd" >/dev/null 2>&1; then
        echo "ERROR: '$cmd' is required but not on PATH." >&2
        exit 1
    fi
}

main() {
    bar
    echo "Chanora Android Rust build"
    echo "Repo root       : $REPO_ROOT"
    echo "NDK             : $NDK_ROOT"
    echo "Android platform: $ANDROID_PLATFORM"
    bar

    require_cmd cargo
    require_cmd cargo-ndk

    if [[ ! -d "$NDK_ROOT" ]]; then
        echo "ERROR: Android NDK not found. Set ANDROID_NDK_HOME or ANDROID_HOME." >&2
        exit 1
    fi

    export ANDROID_NDK_HOME="$NDK_ROOT"
    export LIBOPUS_STATIC=1
    export LIBOPUS_NO_PKG=1

    for build in "${BUILDS[@]}"; do
        IFS=';' read -r abi triple opus_dir <<< "$build"
        if [[ ! -f "$opus_dir/lib/libopus.a" ]]; then
            echo "ERROR: missing $opus_dir/lib/libopus.a" >&2
            echo "Run tools/build-opus-android.sh first." >&2
            exit 1
        fi

        echo "Building Rust bridge for $abi ($triple)"
        export LIBOPUS_LIB_DIR="$opus_dir"
        cargo ndk --platform "$ANDROID_PLATFORM" -t "$abi" build --release -p chanora_bridge

        mkdir -p "$JNI_LIBS_DIR/$abi"
        cp "$REPO_ROOT/target/$triple/release/libchanora_bridge.so" "$JNI_LIBS_DIR/$abi/"
    done

    bar
    echo "Android Rust libraries copied to $JNI_LIBS_DIR"
}

main "$@"
