#!/usr/bin/env bash
# Idempotent harness bootstrap: node deps + factory PATH symlink (never copies).
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT"

install_factory_path() {
  local artifact_root factory_bin link_target="${HOME:?}/.local/bin/factory"

  artifact_root="${HOME}/.local/opt/overdeck/harness/current"
  if [[ -x "$artifact_root/factory/bin/factory" ]]; then
    factory_bin="$(readlink -f "$artifact_root/factory/bin/factory")"
  elif [[ -x "$ROOT/factory/bin/factory" ]]; then
    factory_bin="$(readlink -f "$ROOT/factory/bin/factory")"
  else
    echo "bootstrap: factory entrypoint missing; skipping PATH symlink" >&2
    return 0
  fi

  mkdir -p "${HOME}/.local/bin"
  if [[ -e "$link_target" && ! -L "$link_target" ]]; then
    echo "bootstrap: refusing to replace non-symlink $link_target" >&2
    return 1
  fi
  if [[ -L "$link_target" && "$(readlink -f "$link_target")" == "$factory_bin" ]]; then
    return 0
  fi
  ln -sfn "$factory_bin" "$link_target"
  echo "bootstrap: linked $link_target -> $factory_bin"
}

if [[ -f package.json ]]; then
  bash "$ROOT/lib/provision-deps.sh" provision "$ROOT"
else
  echo "bootstrap: no package.json — harness engine uses Node stdlib; skipping node install"
fi

install_factory_path
