#!/usr/bin/env bash

hypertwist_gitnexus_repo_root() {
  cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd
}

hypertwist_gitnexus_repo_runtime_dir() {
  local repo_root="${1:-$(hypertwist_gitnexus_repo_root)}"
  printf '%s\n' "${HYPERTWIST_GITNEXUS_RUNTIME_DIR:-$repo_root/tools/gitnexus/runtime/gitnexus}"
}

hypertwist_gitnexus_retained_runtime_dir() {
  local repo_root="${1:-$(hypertwist_gitnexus_repo_root)}"
  printf '%s\n' "$repo_root/mirrors/GitNexus/gitnexus"
}

hypertwist_gitnexus_probe_runtime_dir() {
  local runtime_dir="$1"
  local runtime_label="$2"
  local local_gitnexus_cli="$runtime_dir/dist/cli/index.js"

  if [[ ! -f "$local_gitnexus_cli" ]]; then
    return 1
  fi

  local probe_output=""
  local probe_exit=0

  set +e
  probe_output="$(
    cd "$runtime_dir" &&
    node --input-type=module -e 'try { await import("@ladybugdb/core"); } catch (error) { const code = error?.code ? `${error.code}: ` : ""; const message = error?.message || String(error); console.error(`${code}${message}`); process.exit(1); }' 2>&1
  )"
  probe_exit=$?
  set -e

  if [[ "$probe_exit" -eq 0 ]]; then
    return 0
  fi

  probe_output="${probe_output//$'\n'/ }"
  echo "${runtime_label} is not usable on this host (${probe_output})." >&2
  return 1
}

hypertwist_gitnexus_resolve_local_cli() {
  local repo_root="${1:-$(hypertwist_gitnexus_repo_root)}"
  local bootstrap_script="$repo_root/scripts/bootstrap-hypertwist-gitnexus.sh"
  local repo_runtime_dir
  repo_runtime_dir="$(hypertwist_gitnexus_repo_runtime_dir "$repo_root")"
  local retained_runtime_dir
  retained_runtime_dir="$(hypertwist_gitnexus_retained_runtime_dir "$repo_root")"
  local repo_runtime_cli="$repo_runtime_dir/dist/cli/index.js"
  local retained_runtime_cli="$retained_runtime_dir/dist/cli/index.js"

  if [[ "${HYPERTWIST_GITNEXUS_SKIP_LOCAL_CLI:-0}" == "1" ]]; then
    echo "Skipping local GitNexus CLIs because HYPERTWIST_GITNEXUS_SKIP_LOCAL_CLI=1." >&2
    return 1
  fi

  if hypertwist_gitnexus_probe_runtime_dir "$repo_runtime_dir" "Repo-owned GitNexus runtime"; then
    printf '%s\n' "$repo_runtime_cli"
    return 0
  fi

  if [[ -x "$bootstrap_script" ]]; then
    "$bootstrap_script" --if-missing >/dev/null 2>&1 || true
    if hypertwist_gitnexus_probe_runtime_dir "$repo_runtime_dir" "Repo-owned GitNexus runtime"; then
      printf '%s\n' "$repo_runtime_cli"
      return 0
    fi
  fi

  if hypertwist_gitnexus_probe_runtime_dir "$retained_runtime_dir" "Retained GitNexus runtime"; then
    printf '%s\n' "$retained_runtime_cli"
    return 0
  fi

  echo "No usable local GitNexus runtime is available. Falling back to npx gitnexus@latest." >&2
  return 1
}
