#!/usr/bin/env bash
# Toolchain availability check for FlexUI OHOS/Android development.
# Usage: ./build.sh check-env
# Prints which required tools are found and exits non-zero if any are missing.
#
# Why this exists: the build scripts are bash and rely on DevEco Studio's
# bundled tools. On Windows the system `bash` may resolve to WSL (with no distro
# installed), so this script also reports which bash is actually running.
source "$(cd "$(dirname "$0")/.." && pwd)/scripts/_config.sh"

missing=0

report() {
  local name="$1" ok="$2" detail="$3"
  if [ "$ok" = "1" ]; then
    log "OK   $name${detail:+ — $detail}"
  else
    warn "MISS $name${detail:+ — $detail}"
    missing=1
  fi
}

# The shell we are running in (matters on Windows: WSL bash vs Git Bash)
if command -v cygpath >/dev/null 2>&1; then
  report "bash (Git Bash/MSYS)" 1 "$(command -v bash)"
else
  report "bash (WSL or native)" 0 "use Git Bash for build.sh: e.g. 'D:/Program Files/Git/bin/bash.exe'"
fi

# DevEco SDK
if [ -n "${DEVECO_SDK_HOME:-}" ] && [ -d "$DEVECO_SDK_HOME" ]; then
  report "DevEco SDK" 1 "$DEVECO_SDK_HOME"
else
  report "DevEco SDK" 0 "set DEVECO_SDK_HOME or install to one of the probed paths (_config.sh)"
fi

# hvigorw (HAR/HAP builds)
if [ -n "${HVIGORW:-}" ] && command -v "$HVIGORW" >/dev/null 2>&1; then
  report "hvigorw" 1 "$HVIGORW"
elif [ -n "${HVIGORW:-}" ] && [ -f "$HVIGORW" ]; then
  report "hvigorw" 1 "$HVIGORW"
else
  report "hvigorw" 0 "expected at DevEco Studio tools/hvigor/bin/hvigorw"
fi

# ohpm (dependency install)
if command -v ohpm >/dev/null 2>&1; then
  report "ohpm" 1 "$(command -v ohpm)"
else
  report "ohpm" 0 "add DevEco Studio tools/ohpm/bin to PATH"
fi

# hdc (device install/logs)
if command -v hdc >/dev/null 2>&1; then
  report "hdc" 1 "$(command -v hdc)"
else
  report "hdc" 0 "add DevEco Studio sdk/default/openharmony/toolchains to PATH"
fi

# node (jsfwk/ASCF tooling)
if command -v node >/dev/null 2>&1; then
  report "node" 1 "$(command -v node) $(node --version 2>/dev/null)"
else
  report "node" 0 "install Node.js LTS"
fi

# C++ native build smoke path (what to run after editing driver/js/src, dom/, framework cpp)
if [ "$missing" = "0" ]; then
  log ""
  log "Toolchain OK — after editing C++ (driver/js/src/**, dom/**, framework/ohos/src/main/cpp/**), verify with:"
  log "    ./build.sh build-engine     # compiles native .so into flexui_engine HAR (~10 min)"
fi

exit "$missing"