#!/usr/bin/env bash
# Point a product repo's @norskvideo/ctl-* dependencies at a local checkout of
# the ctl monorepo (or restore the registry versions). See local-dev/README.md.
#
#   dev-link.sh <path-to-ctl-monorepo>   # link ctl-* packages to that checkout
#   dev-link.sh --unlink                 # drop the overrides, reinstall pinned
#
# Nothing is committed — the links live only in this repo's node_modules.
set -euo pipefail

PACKAGES=(sdk foundation product-template-schema test-harness commands dev-kit)
product_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && git -C . rev-parse --show-toplevel 2>/dev/null || pwd)"

if [ "${1:-}" = "--unlink" ]; then
  for pkg in "${PACKAGES[@]}"; do
    bun unlink "@norskvideo/ctl-${pkg}" 2>/dev/null || true
  done
  echo "==> reinstalling pinned versions"
  bun install --cwd "${product_root}"
  echo "==> unlinked; registry versions restored"
  exit 0
fi

mono="${1:?usage: dev-link.sh <path-to-ctl-monorepo> | --unlink}"
mono="$(cd "${mono}" && pwd)"
[ -d "${mono}/packages" ] || { echo "not a ctl monorepo checkout: ${mono}" >&2; exit 1; }

for pkg in "${PACKAGES[@]}"; do
  dir="${mono}/packages/${pkg}"
  [ -d "${dir}" ] || { echo "  skip @norskvideo/ctl-${pkg} (not in checkout)"; continue; }
  ( cd "${dir}" && bun link )
  bun link "@norskvideo/ctl-${pkg}" --cwd "${product_root}"
  echo "  linked @norskvideo/ctl-${pkg} -> ${dir}"
done
echo "==> linked against ${mono}; run dev-link.sh --unlink to restore"
