#!/usr/bin/env bash
# Shared helpers for service entrypoints (local dev mode).
# Source this file in each entrypoint script.

# Checkout a git branch if GIT_BRANCH is set.
# Args: $1 = root directory, $2 = log prefix
entrypoint_checkout_branch() {
  local root_dir="$1"
  local prefix="$2"
  local git_branch="${GIT_BRANCH:-}"

  if [[ -z "$git_branch" ]]; then
    return
  fi

  cd "$root_dir"
  git config --global --add safe.directory "$root_dir" 2>/dev/null || true
  local current
  current=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")

  if [[ "$current" != "$git_branch" ]]; then
    echo "[$prefix] Switching to branch: $git_branch"
    if git rev-parse --verify "$git_branch" >/dev/null 2>&1; then
      git checkout "$git_branch" 2>/dev/null || echo "[$prefix] WARNING: Could not checkout $git_branch"
    else
      git fetch origin "$git_branch" 2>/dev/null || true
      git checkout "$git_branch" 2>/dev/null || echo "[$prefix] WARNING: Could not checkout $git_branch"
    fi
  fi
}

# Validate kraiken-lib dist exists.
# Args: $1 = root directory, $2 = log prefix
entrypoint_require_kraiken_lib() {
  local root_dir="$1"
  local prefix="$2"
  local required_dist="$root_dir/kraiken-lib/dist/index.js"

  if [[ ! -f "$required_dist" ]]; then
    echo "[$prefix] ERROR: Run ./scripts/build-kraiken-lib.sh before starting containers" >&2
    exit 1
  fi
}

# Install node_modules if needed (named volume may be empty).
# Args: $1 = log prefix
entrypoint_install_deps() {
  local prefix="$1"

  if [[ ! -d node_modules/.bin ]]; then
    echo "[$prefix] Installing dependencies..."
    npm ci --loglevel error && npm cache clean --force 2>&1 || {
      echo "[$prefix] npm ci failed, trying npm install"
      npm install --no-save --loglevel error && npm cache clean --force
    }
  else
    echo "[$prefix] Using cached node_modules from volume"
  fi
}
