#!/bin/zsh
set -u
setopt NULL_GLOB

SCRIPT_DIR="${0:A:h}"
CONTENTS_DIR="${SCRIPT_DIR:h}"
RESOURCES_DIR="${CONTENTS_DIR}/Resources"
PAYLOAD="${RESOURCES_DIR}/payload.zip"
APP_SUPPORT="${HOME}/Library/Application Support/Helm/App/0.8.0"
LOG_DIR="${HOME}/Library/Logs/Helm"
LOG_FILE="${LOG_DIR}/helm.log"
mkdir -p "${LOG_DIR}"

show_dialog() {
  /usr/bin/osascript - "$1" <<'APPLESCRIPT' >/dev/null 2>&1
on run argv
  display dialog (item 1 of argv) with title "Helm" buttons {"OK"} default button "OK" with icon caution
end run
APPLESCRIPT
}

export PATH="/opt/homebrew/bin:/usr/local/bin:${HOME}/.volta/bin:${HOME}/.npm-global/bin:${HOME}/.local/bin:${PATH}"
for node_dir in "${HOME}"/.nvm/versions/node/*/bin; do
  export PATH="${node_dir}:${PATH}"
done

NODE_BIN="$(command -v node 2>/dev/null || true)"
if [[ -z "${NODE_BIN}" ]]; then
  show_dialog "Helm needs Node.js 20 or newer. Install Node.js, then open Helm again."
  exit 1
fi
NODE_MAJOR="$("${NODE_BIN}" -p 'Number(process.versions.node.split(".")[0])' 2>/dev/null || echo 0)"
if [[ "${NODE_MAJOR}" -lt 20 ]]; then
  show_dialog "Helm found Node.js $("${NODE_BIN}" --version), but requires Node.js 20 or newer."
  exit 1
fi

CODEX_BIN="$(command -v codex 2>/dev/null || true)"
if [[ -n "${CODEX_BIN}" ]]; then
  export AUTOROUTE_CODEX_BIN="${CODEX_BIN}"
fi

# Reuse only the same Helm version. This avoids reopening a stale local server
# after the desktop app has been updated.
EXISTING="$(/usr/bin/curl -fsS --max-time 1 http://127.0.0.1:4783/api/status 2>/dev/null || true)"
if [[ "${EXISTING}" == *'"version":"0.8.0"'* && "${EXISTING}" == *'"providers"'* ]]; then
  /usr/bin/open http://127.0.0.1:4783
  exit 0
fi

# Extract the bundled runtime once per release rather than exposing the source
# tree directly inside Helm.app.
if [[ ! -f "${APP_SUPPORT}/src/cli.js" || ! -f "${APP_SUPPORT}/package.json" ]]; then
  TMP_DIR="${APP_SUPPORT}.tmp.$$"
  /bin/rm -rf "${TMP_DIR}"
  /bin/mkdir -p "${TMP_DIR}"
  if ! /usr/bin/ditto -x -k "${PAYLOAD}" "${TMP_DIR}"; then
    /bin/rm -rf "${TMP_DIR}"
    show_dialog "Helm could not unpack its local runtime. Please reinstall Helm."
    exit 1
  fi
  /bin/rm -rf "${APP_SUPPORT}"
  /bin/mkdir -p "${APP_SUPPORT:h}"
  /bin/mv "${TMP_DIR}" "${APP_SUPPORT}"
fi

PORT=4783
if /usr/bin/nc -z 127.0.0.1 4783 >/dev/null 2>&1; then
  PORT=0
fi

cd "${HOME}"
exec "${NODE_BIN}" "${APP_SUPPORT}/src/cli.js" ui --port "${PORT}" >>"${LOG_FILE}" 2>&1
