#!/usr/bin/env bash

# Determine the directory where this script lives, following symlinks
# This is important for npm link to work correctly
SCRIPT_PATH="${BASH_SOURCE[0]}"
while [ -L "$SCRIPT_PATH" ]; do
  SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
  SCRIPT_PATH="$(readlink "$SCRIPT_PATH")"
  [[ $SCRIPT_PATH != /* ]] && SCRIPT_PATH="$SCRIPT_DIR/$SCRIPT_PATH"
done
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Prefer compiled version if it exists, otherwise try ts-node
if [ -f "$PROJECT_ROOT/dist/index.js" ]; then
  # Production mode or built dev: use compiled JavaScript
  exec node "$PROJECT_ROOT/dist/index.js" "$@"
elif [ -f "$PROJECT_ROOT/index.ts" ] && [ -f "$PROJECT_ROOT/node_modules/ts-node/register/index.js" ]; then
  # Development mode with ts-node available: use ts-node
  exec node --require ts-node/register --require tsconfig-paths/register "$PROJECT_ROOT/index.ts" "$@"
else
  echo "Error: Neither dist/index.js nor TypeScript source with ts-node found"
  echo "Run 'npm run build' to compile TypeScript"
  exit 1
fi
