#!/usr/bin/env bash
#
# Link or unlink a local @flowdrop/flowdrop for development.
#
# Usage:
#   ./link-local.sh          # link local library + set dev version in libraries.yml
#   ./link-local.sh unlink   # restore npm registry version + original version
#

set -euo pipefail

LIBRARY_PATH="/Users/shibindas/work/06.FlowDrop/fdnpm/libs/flowdrop"
PACKAGE_NAME="@flowdrop/flowdrop"
CONSUMER_DIR="$(cd "$(dirname "$0")" && pwd)"
LIBRARIES_YML="$CONSUMER_DIR/../../flowdrop_ui_components.libraries.yml"

# Get the released version from the library's package.json
get_release_version() {
  node -e "console.log(require('$LIBRARY_PATH/package.json').version)"
}

# Get short commit hash from the library repo
get_commit_hash() {
  git -C "$LIBRARY_PATH" rev-parse --short HEAD
}

# Read the current version string from libraries.yml
get_current_libraries_version() {
  grep -A1 '^flowdrop:' "$LIBRARIES_YML" | grep 'version:' | sed -E 's/.*version: //'
}

# Compute next build counter for the given base (version-dev-hash).
# If libraries.yml already has base-N, returns N+1. Otherwise returns 1.
get_next_build_counter() {
  local base="$1"
  local current
  current="$(get_current_libraries_version)"
  if [[ "$current" == "${base}-"* ]]; then
    local n="${current#${base}-}"
    echo $(( n + 1 ))
  else
    echo 1
  fi
}

# Update the flowdrop library version in libraries.yml
set_libraries_version() {
  local version="$1"
  sed -i '' -E '/^flowdrop:/{n;s/^(  version: ).*/\1'"$version"'/;}' "$LIBRARIES_YML"
  echo "Updated libraries.yml flowdrop version to: $version"
}

if [[ "${1:-}" == "unlink" ]]; then
  echo "Unlinking $PACKAGE_NAME..."

  RELEASE_VERSION="$(get_release_version)"
  set_libraries_version "$RELEASE_VERSION"

  cd "$CONSUMER_DIR"
  npm unlink "$PACKAGE_NAME"
  npm install

  echo "Done — restored $PACKAGE_NAME from npm registry."
else
  echo "Linking $PACKAGE_NAME from $LIBRARY_PATH..."

  if [[ ! -d "$LIBRARY_PATH" ]]; then
    echo "Error: Library not found at $LIBRARY_PATH" >&2
    exit 1
  fi

  RELEASE_VERSION="$(get_release_version)"
  COMMIT_HASH="$(get_commit_hash)"
  BASE_VERSION="$RELEASE_VERSION-dev-$COMMIT_HASH"
  BUILD_COUNTER="$(get_next_build_counter "$BASE_VERSION")"
  set_libraries_version "$BASE_VERSION-$BUILD_COUNTER"

  # Build the library dist so the linked version is up-to-date
  echo "Building $PACKAGE_NAME..."
  cd "$LIBRARY_PATH"
  npm run build
  npm link

  cd "$CONSUMER_DIR"
  npm link "$PACKAGE_NAME"
  npm run build
  ddev drush cr

  echo "Done — $PACKAGE_NAME now points to local source."
  ls -la "$CONSUMER_DIR/node_modules/@flowdrop/flowdrop"
fi
