#!/usr/bin/env bash
#
# Set up the cross-compilation environment for building Python native
# extensions targeting Android ARM64.
#
# This script:
#   1. Verifies Android NDK is installed
#   2. Installs the Rust aarch64-linux-android target
#   3. Installs maturin (Python wheel builder for Rust extensions)
#   4. Runs a quick test compile to verify the toolchain works
#
set -euo pipefail

echo "=== LedGrab Android NDK Setup ==="

# ── Check prerequisites ─────────────────────────────────────────────

if ! command -v rustc &>/dev/null; then
    echo "ERROR: Rust is not installed."
    echo "Install from: https://rustup.rs/"
    exit 1
fi
echo "Rust: $(rustc --version)"

if ! command -v cargo &>/dev/null; then
    echo "ERROR: Cargo is not installed."
    exit 1
fi
echo "Cargo: $(cargo --version)"

if ! command -v python3.11 &>/dev/null && ! command -v python3 &>/dev/null; then
    echo "WARNING: Python 3.11 not found. Needed for maturin builds."
fi

# ── Install Rust target ─────────────────────────────────────────────

echo ""
echo "Installing Rust Android target..."
rustup target add aarch64-linux-android
echo "Installed targets:"
rustup target list --installed | grep android

# ── Install maturin ─────────────────────────────────────────────────

echo ""
echo "Installing maturin..."
pip install maturin 2>/dev/null || pip3 install maturin 2>/dev/null || {
    echo "WARNING: Could not install maturin. Install manually: pip install maturin"
}

if command -v maturin &>/dev/null; then
    echo "maturin: $(maturin --version)"
fi

# ── Verify NDK ──────────────────────────────────────────────────────

echo ""
if [ -n "${ANDROID_NDK_HOME:-}" ]; then
    echo "ANDROID_NDK_HOME: $ANDROID_NDK_HOME"
else
    echo "ANDROID_NDK_HOME is not set."
    echo "Set it to your NDK installation path, e.g.:"
    echo "  export ANDROID_NDK_HOME=\$HOME/Android/Sdk/ndk/26.1.10909125"
    echo ""
    echo "Or install NDK via Android Studio:"
    echo "  SDK Manager → SDK Tools → NDK (Side by side)"
fi

echo ""
echo "=== Setup complete ==="
echo ""
echo "Next steps:"
echo "  1. Ensure ANDROID_NDK_HOME is set"
echo "  2. Run: ./build-pydantic-core.sh"
