#!/usr/bin/env bash
set -euo pipefail

candidate_paths=()

add_candidate() {
  local value="${1:-}"
  if [ -n "$value" ]; then
    candidate_paths+=("$value")
  fi
}

if [ -n "${DEVICE_POD_CLI:-}" ]; then
  add_candidate "$DEVICE_POD_CLI"
fi

for base in \
  "${UNIDESK_SKILLS_PATH:-}" \
  /app/skills \
  /root/.agents/skills \
  /home/ubuntu/.agents/skills; do
  if [ -n "$base" ]; then
    add_candidate "$base/device-pod-cli/scripts/device-pod-cli.mjs"
  fi
done

for base in \
  "$PWD" \
  /workspace/hwlab \
  /root/hwlab \
  /app \
  /root/unidesk; do
  if [ -n "$base" ]; then
    add_candidate "$base/skills/device-pod-cli/scripts/device-pod-cli.mjs"
    add_candidate "$base/tools/device-pod-cli.mjs"
  fi
done

dir="$PWD"
while [ "$dir" != "/" ]; do
  add_candidate "$dir/skills/device-pod-cli/scripts/device-pod-cli.mjs"
  add_candidate "$dir/tools/device-pod-cli.mjs"
  dir="$(dirname "$dir")"
done

for cli in "${candidate_paths[@]}"; do
  if [ -f "$cli" ]; then
    exec node "$cli" "$@"
  fi
done

{
  echo "hwpod: device-pod-cli.mjs not found."
  echo "hwpod searches DEVICE_POD_CLI, UNIDESK_SKILLS_PATH/device-pod-cli, ./skills/device-pod-cli, and ./tools/device-pod-cli.mjs."
  echo "Set DEVICE_POD_CLI=/path/to/device-pod-cli.mjs or run from a HWLAB workspace that contains skills/device-pod-cli."
} >&2
exit 127
