#!/usr/bin/env bash
# Android NDK discovery for AndroidCast build scripts.
# Source this file:  source "$(dirname "$0")/android-ndk.sh"
#
# Optional env:
#   ANDROIDCAST_NDK_VERSION  — pin a version under $HOME/Android/Sdk/ndk (e.g. 29.0.14206865)
#   ANDROID_NDK_HOME / ANDROID_NDK_ROOT — used when valid
#
set -euo pipefail

_androidcast_sdk_base() {
  printf '%s\n' "${ANDROIDCAST_SDK_BASE:-${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}}}"
}

# Print absolute NDK root (directory containing ndk-build). Errors on stderr.
androidcast_find_ndk_root() {
  local project_root="${1:-}"
  local ndk="" ndk_root ndk_ver parent pinned

  if [[ -n "$project_root" && -f "$project_root/local.properties" ]]; then
    ndk="$(sed -n 's/^[[:space:]]*ndk\.dir=//p' "$project_root/local.properties" | tr -d '\r' | head -1)"
    ndk="${ndk%/}"
    while [[ -n "$ndk" ]]; do
      if [[ -x "$ndk/ndk-build" ]]; then
        realpath "$ndk"
        return 0
      fi
      parent="$(dirname "$ndk")"
      [[ "$parent" == "$ndk" ]] && break
      ndk="$parent"
    done
  fi

  for ndk in "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_ROOT:-}"; do
    ndk="${ndk%/}"
    if [[ -n "$ndk" && -x "$ndk/ndk-build" ]]; then
      realpath "$ndk"
      return 0
    fi
  done

  ndk_root="$(_androidcast_sdk_base)/ndk"
  if [[ ! -d "$ndk_root" ]]; then
    echo "ERROR: No Android NDK found. Install via SDK Manager ($ndk_root) or set ANDROID_NDK_HOME." >&2
    return 1
  fi

  pinned="${ANDROIDCAST_NDK_VERSION:-}"
  if [[ -n "$pinned" ]]; then
    if [[ -d "$ndk_root/$pinned" ]]; then
      ndk_ver="$pinned"
    else
      echo "ERROR: ANDROIDCAST_NDK_VERSION=$pinned not found under $ndk_root" >&2
      return 1
    fi
  else
    ndk_ver="$(ls -1 "$ndk_root" 2>/dev/null | sort -V | tail -n 1 || true)"
    if [[ -z "$ndk_ver" ]]; then
      echo "ERROR: No NDK versions under $ndk_root" >&2
      return 1
    fi
  fi

  ndk="$ndk_root/$ndk_ver"
  if [[ ! -x "$ndk/ndk-build" ]]; then
    echo "ERROR: ndk-build missing under $ndk" >&2
    return 1
  fi
  realpath "$ndk"
}

# Print llvm prebuilt bin directory for the current host.
androidcast_ndk_host_bin() {
  local ndk_root="${1:?NDK root required}"
  local os arch host_tag
  case "$(uname -s)" in
    Linux) os=linux ;;
    Darwin) os=darwin ;;
    *) os="$(uname -s | tr '[:upper:]' '[:lower:]')" ;;
  esac
  arch="$(uname -m)"
  case "$arch" in
    x86_64 | amd64) arch=x86_64 ;;
    aarch64 | arm64) arch=aarch64 ;;
  esac
  host_tag="${os}-${arch}"
  if [[ ! -d "$ndk_root/toolchains/llvm/prebuilt/${host_tag}/bin" ]]; then
    host_tag="linux-x86_64"
  fi
  realpath "$ndk_root/toolchains/llvm/prebuilt/${host_tag}/bin"
}
