#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# H5-in-App-Integration SDK · HarmonyOS 单元测试入口
#
# 用法：
#   bash scripts/test-harmony.sh              # 运行 tencentqianwebview 模块本地单元测试
#   bash scripts/test-harmony.sh --help       # 查看本帮助
#
# 测试框架：@ohos/hypium（本地单元测试，不需要设备）
# 测试目录：harmonyos-arkts/tencentqianwebview/src/test/
# 结果输出：harmonyos-arkts/tencentqianwebview/.test/default/intermediates/test/coverage_data/test_result.txt
#
# 设计要点：
# - 复用 build-harmony.sh 的工具链定位逻辑（DevEco Studio 自动发现）
# - 不引入 npm / package.json，工程保持纯 ohpm 体系
# - 自动从 DevEco Studio 安装目录定位 hvigorw / node / ohpm
# ------------------------------------------------------------------------------
set -euo pipefail

# ---- 路径与常量 --------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
HARMONY_DIR="${REPO_ROOT}/harmonyos-arkts"
TEST_RESULT_FILE="${HARMONY_DIR}/tencentqianwebview/.test/default/intermediates/test/coverage_data/test_result.txt"

# DevEco Studio 内嵌工具链候选位置（按优先级）
DEVECO_CANDIDATES=(
  "/Applications/DevEco-Studio.app/Contents"
  "${HOME}/Applications/DevEco-Studio.app/Contents"
)

# ---- 提前处理 --help ---------------------------------------------------------
case "${1:-}" in
  -h|--help)
    sed -n '2,17p' "${BASH_SOURCE[0]}"
    exit 0
    ;;
esac

# ---- 定位 DevEco Studio 安装根目录 ------------------------------------------
locate_deveco_root() {
  if [[ -n "${DEVECO_HOME:-}" ]] && [[ -d "${DEVECO_HOME}" ]]; then
    echo "${DEVECO_HOME}"
    return 0
  fi
  for candidate in "${DEVECO_CANDIDATES[@]}"; do
    if [[ -d "${candidate}/tools/hvigor" ]]; then
      echo "${candidate}"
      return 0
    fi
  done
  return 1
}

DEVECO_ROOT="$(locate_deveco_root || true)"

# ---- 定位 hvigorw / node / ohpm ---------------------------------------------
HVIGOR_BIN=""
NODE_HOME_DIR=""
OHPM_BIN=""
SDK_HOME_DIR=""

# hvigorw
if [[ -n "${HVIGOR:-}" ]] && [[ -x "${HVIGOR}" ]]; then
  HVIGOR_BIN="${HVIGOR}"
elif [[ -n "${DEVECO_ROOT}" ]] && [[ -x "${DEVECO_ROOT}/tools/hvigor/bin/hvigorw" ]]; then
  HVIGOR_BIN="${DEVECO_ROOT}/tools/hvigor/bin/hvigorw"
elif command -v hvigorw >/dev/null 2>&1; then
  HVIGOR_BIN="$(command -v hvigorw)"
fi

# DEVECO_SDK_HOME
if [[ -n "${DEVECO_SDK_HOME:-}" ]] && [[ -d "${DEVECO_SDK_HOME}" ]]; then
  SDK_HOME_DIR="${DEVECO_SDK_HOME}"
elif [[ -n "${DEVECO_ROOT}" ]] && [[ -d "${DEVECO_ROOT}/sdk" ]]; then
  SDK_HOME_DIR="${DEVECO_ROOT}/sdk"
elif [[ -d "${HOME}/Library/Huawei/Sdk" ]]; then
  SDK_HOME_DIR="${HOME}/Library/Huawei/Sdk"
fi

# node
if [[ -n "${NODE_HOME:-}" ]] && [[ -x "${NODE_HOME}/bin/node" ]]; then
  NODE_HOME_DIR="${NODE_HOME}"
elif [[ -n "${DEVECO_ROOT}" ]] && [[ -x "${DEVECO_ROOT}/tools/node/bin/node" ]]; then
  NODE_HOME_DIR="${DEVECO_ROOT}/tools/node"
elif command -v node >/dev/null 2>&1; then
  NODE_HOME_DIR="$(dirname "$(dirname "$(command -v node)")")"
fi

# ohpm
if [[ -n "${OHPM:-}" ]] && [[ -x "${OHPM}" ]]; then
  OHPM_BIN="${OHPM}"
elif [[ -n "${DEVECO_ROOT}" ]] && [[ -x "${DEVECO_ROOT}/tools/ohpm/bin/ohpm" ]]; then
  OHPM_BIN="${DEVECO_ROOT}/tools/ohpm/bin/ohpm"
elif command -v ohpm >/dev/null 2>&1; then
  OHPM_BIN="$(command -v ohpm)"
fi

# ---- 工具链就绪检查 ----------------------------------------------------------
if [[ -z "${HVIGOR_BIN}" ]]; then
  cat >&2 <<EOF
❌ 找不到 hvigorw 可执行文件。请按下列任一方式准备：
   1. 安装 DevEco Studio（macOS 默认安装到 /Applications/DevEco-Studio.app）
   2. 显式指定环境变量：export DEVECO_HOME=/path/to/DevEco-Studio.app/Contents
   3. 或显式指定：export HVIGOR=/path/to/hvigorw
EOF
  exit 1
fi
if [[ -z "${NODE_HOME_DIR}" ]]; then
  echo "❌ 找不到 node。可设置 NODE_HOME=/path/to/node-installation 或安装 DevEco Studio。" >&2
  exit 1
fi
if [[ -z "${OHPM_BIN}" ]]; then
  echo "❌ 找不到 ohpm。可设置 OHPM=/path/to/ohpm 或安装 DevEco Studio。" >&2
  exit 1
fi
if [[ -z "${SDK_HOME_DIR}" ]]; then
  echo "❌ 找不到 HarmonyOS SDK。可设置 DEVECO_SDK_HOME=/path/to/sdk 或安装 DevEco Studio。" >&2
  exit 1
fi

echo "ℹ️  DevEco Studio:   ${DEVECO_ROOT:-(未使用)}"
echo "ℹ️  hvigorw:         ${HVIGOR_BIN}"
echo "ℹ️  node home:       ${NODE_HOME_DIR}"
echo "ℹ️  ohpm:            ${OHPM_BIN}"
echo "ℹ️  DEVECO_SDK_HOME: ${SDK_HOME_DIR}"

# 把工具链信息暴露给 hvigorw
export NODE_HOME="${NODE_HOME_DIR}"
export DEVECO_SDK_HOME="${SDK_HOME_DIR}"
export PATH="${NODE_HOME_DIR}/bin:${PATH}"

# ---- 首次安装依赖 ------------------------------------------------------------
if [[ ! -d "${HARMONY_DIR}/oh_modules" ]]; then
  echo ""
  echo "▶ 首次测试：oh_modules 不存在，执行 ohpm install ..."
  pushd "${HARMONY_DIR}" >/dev/null
  "${OHPM_BIN}" install
  popd >/dev/null
fi

# ---- 执行单元测试 ------------------------------------------------------------
echo ""
echo "▶ 运行 tencentqianwebview 模块本地单元测试 ..."
pushd "${HARMONY_DIR}" >/dev/null
"${HVIGOR_BIN}" --no-daemon test -p module=tencentqianwebview@default
popd >/dev/null

# ---- 输出结果摘要 ------------------------------------------------------------
echo ""
if [[ -f "${TEST_RESULT_FILE}" ]]; then
  echo "📋 测试结果摘要："
  tail -1 "${TEST_RESULT_FILE}"
  echo ""

  # 检查是否有失败
  if grep -q "Failure: 0, Error: 0" "${TEST_RESULT_FILE}"; then
    echo "✅ HarmonyOS 单元测试全部通过！"
  else
    echo "❌ HarmonyOS 单元测试存在失败，详见："
    echo "   ${TEST_RESULT_FILE}"
    exit 1
  fi
else
  echo "⚠️  未找到测试结果文件：${TEST_RESULT_FILE}"
  echo "   请检查 hvigorw test 是否正常执行。"
  exit 1
fi
