#!/bin/bash
set -euo pipefail

PROJECT_DIR="${PROJECT_DIR:-/workspace/frontend}"
LOCKFILE="${PROJECT_DIR}/package-lock.json"
NODE_MODULES_DIR="${PROJECT_DIR}/node_modules"
HASH_FILE="${NODE_MODULES_DIR}/.package-lock.hash"
DEV_COMMAND="${DEV_COMMAND:-npm run dev -- --host 0.0.0.0 --port 3001}"

cd "${PROJECT_DIR}"

calculate_lock_hash() {
  sha256sum "${LOCKFILE}" | awk '{print $1}'
}

write_hash() {
  calculate_lock_hash > "${HASH_FILE}"
}

install_dependencies() {
  echo "[frontend] 安装/更新依赖..."
  npm ci
  write_hash
}

if [ ! -d "${NODE_MODULES_DIR}" ]; then
  install_dependencies
elif [ ! -f "${HASH_FILE}" ]; then
  install_dependencies
else
  current_hash="$(calculate_lock_hash)"
  installed_hash="$(cat "${HASH_FILE}" 2>/dev/null || true)"

  if [ "${current_hash}" != "${installed_hash}" ]; then
    echo "[frontend] package-lock.json 发生变化，重新安装依赖..."
    install_dependencies
  else
    echo "[frontend] 依赖哈希一致，跳过 npm ci。"
  fi
fi

# Check if node_modules/.bin exists in PATH, if not add it
if [[ ":$PATH:" != *":${NODE_MODULES_DIR}/.bin:"* ]]; then
    export PATH="${NODE_MODULES_DIR}/.bin:$PATH"
fi

echo "Starting development server..."
exec ${DEV_COMMAND}

