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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
runtime_root="$repo_root/tools/gitnexus/runtime"
runtime_gitnexus="$runtime_root/gitnexus"
runtime_shared="$runtime_root/gitnexus-shared"
retained_root="${HYPERTWIST_GITNEXUS_SOURCE_ROOT:-$repo_root/mirrors/GitNexus}"
retained_gitnexus="$retained_root/gitnexus"
retained_shared="$retained_root/gitnexus-shared"

usage() {
  cat <<'EOF'
Usage:
  scripts/bootstrap-hypertwist-gitnexus.sh [--if-missing]

Materializes a HyperTwist-owned GitNexus runtime under tools/gitnexus/runtime/
from the retained GitNexus working reference.

Behavior:
  - copies gitnexus + gitnexus-shared into the local runtime landing zone
  - removes copied node_modules so host-correct native dependencies are rebuilt
  - installs gitnexus-shared first, then gitnexus, while intentionally
    skipping the retained root prepare rebuild because HyperTwist only needs
    the shipped CLI plus host-correct dependency payloads
  - runs npm rebuild afterward so native dependency hooks refresh for the
    current host without forcing a fresh retained-source TypeScript compile
  - verifies that @ladybugdb/core loads successfully before declaring success

Options:
  --if-missing  exits early only when the repo-owned runtime is already usable;
                otherwise repairs/rebuilds it in place
EOF
}

probe_runtime() {
  local runtime_dir="$1"
  local cli_path="$runtime_dir/dist/cli/index.js"

  if [[ ! -f "$cli_path" ]]; 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 "Repo-owned GitNexus runtime is not usable yet (${probe_output})." >&2
  return 1
}

copy_runtime_sources() {
  if [[ ! -d "$retained_gitnexus" || ! -d "$retained_shared" ]]; then
    cat >&2 <<EOF
Unable to find the retained GitNexus sources needed for bootstrap.

Expected:
  - $retained_gitnexus
  - $retained_shared

Provide HYPERTWIST_GITNEXUS_SOURCE_ROOT or restore the retained working
reference before bootstrapping the HyperTwist-owned runtime.
EOF
    exit 1
  fi

  rm -rf "$runtime_gitnexus" "$runtime_shared"
  mkdir -p "$runtime_root"

  (
    cd "$retained_root"
    tar \
      --exclude='gitnexus/node_modules' \
      --exclude='gitnexus-shared/node_modules' \
      --exclude='gitnexus/.git' \
      --exclude='gitnexus-shared/.git' \
      -cf - gitnexus gitnexus-shared
  ) | (
    cd "$runtime_root"
    tar -xf -
  )
}

install_runtime() {
  if ! command -v npm >/dev/null 2>&1; then
    echo "npm is required to bootstrap the repo-owned GitNexus runtime." >&2
    exit 1
  fi

  echo "Bootstrapping repo-owned GitNexus runtime under $runtime_root"
  echo "Installing gitnexus-shared dependencies..."
  (cd "$runtime_shared" && npm install --legacy-peer-deps --no-fund --no-audit --ignore-scripts)
  echo "Installing gitnexus dependencies..."
  (cd "$runtime_gitnexus" && npm install --legacy-peer-deps --no-fund --no-audit --ignore-scripts)
  echo "Rebuilding GitNexus native/runtime dependencies for this host..."
  (cd "$runtime_gitnexus" && npm rebuild --legacy-peer-deps --no-fund --no-audit)
}

if [[ "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

if [[ "${1:-}" == "--if-missing" ]]; then
  if probe_runtime "$runtime_gitnexus" >/dev/null 2>&1; then
    printf 'Repo-owned GitNexus runtime already present under %s\n' "$runtime_root"
    exit 0
  fi
elif [[ $# -gt 0 ]]; then
  usage >&2
  exit 1
fi

copy_runtime_sources
install_runtime

if ! probe_runtime "$runtime_gitnexus"; then
  echo "Repo-owned GitNexus runtime bootstrap finished, but the runtime probe still failed." >&2
  exit 1
fi

printf 'Repo-owned GitNexus runtime is ready under %s\n' "$runtime_root"
