#!/usr/bin/env bash
set -euo pipefail
SOURCE="${BASH_SOURCE[0]}"
while [ -L "$SOURCE" ]; do
  SOURCE_DIR="$(cd "$(dirname "$SOURCE")" && pwd -P)"
  TARGET="$(readlink "$SOURCE")"
  if [[ "$TARGET" == /* ]]; then
    SOURCE="$TARGET"
  else
    SOURCE="$SOURCE_DIR/$TARGET"
  fi
done
SCRIPT_DIR="$(cd "$(dirname "$SOURCE")" && pwd -P)"
RUNNER_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

if [ "${1:-}" = "mobile" ]; then
  shift
  exec "$RUNNER_DIR/bin/mm-recipe" "$@"
fi
if [ "${1:-}" = "extension" ]; then
  shift
  exec "$RUNNER_DIR/bin/mme-recipe" "$@"
fi

find_protocol_root() {
  local start="$1"
  local dir
  dir="$(cd "$start" && pwd -P)"
  while [ "$dir" != "/" ]; do
    if [ -f "$dir/packages/recipe-harness/package.json" ] && [ -f "$dir/packages/protocol/package.json" ]; then
      printf '%s\n' "$dir"
      return 0
    fi
    if [ -f "$dir/farmslot/packages/recipe-harness/package.json" ] && [ -f "$dir/farmslot/packages/protocol/package.json" ]; then
      printf '%s\n' "$dir/farmslot"
      return 0
    fi
    dir="$(dirname "$dir")"
  done
  return 1
}

node_can_run_source_typescript() {
  local probe_dir probe_file
  probe_dir="$(mktemp -d "${TMPDIR:-/tmp}/metamask-recipe-node-ts.XXXXXX")"
  probe_file="$probe_dir/probe.ts"
  printf 'const answer: number = 42; if (answer !== 42) process.exit(1);\n' > "$probe_file"
  if ! node --no-warnings "$probe_file" >/dev/null 2>&1; then
    rm -rf "$probe_dir"
    return 1
  fi
  rm -rf "$probe_dir"
}

if [ -f "$RUNNER_DIR/dist/cli.js" ]; then
  exec node "$RUNNER_DIR/dist/cli.js" "$@"
fi

TSX_BIN="${TSX_BIN:-$RUNNER_DIR/node_modules/.bin/tsx}"
if [ ! -x "$TSX_BIN" ] && [ -x "$RUNNER_DIR/../../.bin/tsx" ]; then
  TSX_BIN="$RUNNER_DIR/../../.bin/tsx"
fi
if [ ! -x "$TSX_BIN" ]; then
  if [ -z "${FARMSLOT_ROOT:-}" ] && [ -f "$RUNNER_DIR/.farmslot-root" ]; then
    FARMSLOT_ROOT="$(cat "$RUNNER_DIR/.farmslot-root")"
  fi
  if [ -z "${FARMSLOT_ROOT:-}" ]; then
    FARMSLOT_ROOT="$(find_protocol_root "$RUNNER_DIR" || find_protocol_root "$PWD" || true)"
  fi
  if [ -n "${FARMSLOT_ROOT:-}" ]; then
    FARMSLOT_ROOT="$(cd "$FARMSLOT_ROOT" && pwd -P)"
    TSX_BIN="$FARMSLOT_ROOT/node_modules/.bin/tsx"
  fi
fi

if [ -x "$TSX_BIN" ]; then
  exec "$TSX_BIN" "$RUNNER_DIR/src/cli.ts" "$@"
fi

if node_can_run_source_typescript; then
  exec node --no-warnings "$RUNNER_DIR/src/cli.ts" "$@"
fi

echo "metamask-recipe source checkout requires dist/cli.js, Node.js TypeScript type stripping, or a local tsx binary. Install dependencies normally, or set TSX_BIN/FARMSLOT_ROOT for local protocol co-development." >&2
exit 1
