#!/usr/bin/env bash
#
# migrate-config.sh — convert a legacy (v1) config.yaml to the v2 layout.
#
# Usage:
#   scripts/migrate-config.sh                       # in-place rewrite of ./config.yaml
#   scripts/migrate-config.sh --dry-run             # print result to stdout + diff to stderr
#   scripts/migrate-config.sh --config /path.yaml   # operate on a different file
#
# The script delegates to the TypeScript CLI compiled at
# dist/scripts/migrate-config.js. If that file doesn't exist yet, we try
# the tsx runtime as a fallback (matches `npm run dev`'s approach), so
# the script works even before `npm run build` has run once.
#
# Exit codes mirror the Node CLI (see src/scripts/migrate-config.ts).

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
DIST_ENTRY="$PROJECT_DIR/dist/scripts/migrate-config.js"
TS_ENTRY="$PROJECT_DIR/src/scripts/migrate-config.ts"

if [[ -f "$DIST_ENTRY" ]]; then
  exec node "$DIST_ENTRY" "$@"
fi

# Fallback path for pre-build environments. Prefer tsx > ts-node because
# the rest of the repo's npm scripts use tsx (see package.json:bench).
if command -v npx >/dev/null 2>&1; then
  if [[ -f "$PROJECT_DIR/node_modules/tsx/dist/cli.mjs" ]] || npx --no-install tsx --version >/dev/null 2>&1; then
    exec npx --no-install tsx "$TS_ENTRY" "$@"
  fi
  if [[ -f "$PROJECT_DIR/node_modules/ts-node/dist/bin.js" ]]; then
    exec node --loader ts-node/esm "$TS_ENTRY" "$@"
  fi
fi

echo "error: neither dist/scripts/migrate-config.js nor a TS runtime (tsx/ts-node) is available." >&2
echo "       Run 'npm run build' first, or install tsx (npm i -D tsx)." >&2
exit 1
