#!/bin/sh
# Resolve symlinks so global installs (npm link / npm install -g) can find the
# actual package directory instead of the global bin directory.
SOURCE="$0"
while [ -L "$SOURCE" ]; do
  SOURCE_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  TARGET="$(readlink "$SOURCE")"
  case "$TARGET" in
    /*) SOURCE="$TARGET" ;;
    *) SOURCE="$SOURCE_DIR/$TARGET" ;;
  esac
done

# Detect the runtime used to install this package and use the matching one
# to avoid native module ABI mismatches (e.g., better-sqlite3 compiled for bun vs node)
DIR="$(cd -P "$(dirname "$SOURCE")/.." && pwd)"

# MCP stdio reserves stdout exclusively for JSON-RPC frames. node-llama-cpp
# / llama.cpp / ggml can write native logs directly to stdout before JS-level
# log handlers are attached, so seed the native quiet env before Node/Bun imports
# the CLI and its LLM modules. Preserve explicit user values when provided.
if [ "$1" = "mcp" ]; then
  export LLAMA_LOG_LEVEL="${LLAMA_LOG_LEVEL:-error}"
  export GGML_LOG_LEVEL="${GGML_LOG_LEVEL:-error}"
  export GGML_BACKEND_SILENT="${GGML_BACKEND_SILENT:-1}"
fi

JS="$DIR/dist/cli/qmd.js"
TS="$DIR/src/cli/qmd.ts"

# In published packages, bin/qmd must run dist/. In a git checkout, however,
# dist/ is often ignored and can be stale after git reset or branch switches.
# Prefer source mode only for checkouts so ./bin/qmd reflects the checked-out
# source without changing packaged/runtime behavior.
if [ -e "$DIR/.git" ] && [ -f "$TS" ]; then
  if [ -f "$DIR/bun.lock" ] || [ -f "$DIR/bun.lockb" ]; then
    if command -v bun >/dev/null 2>&1; then
      exec bun "$TS" "$@"
    fi
  fi
  if [ -f "$DIR/node_modules/tsx/dist/cli.mjs" ]; then
    exec node "$DIR/node_modules/tsx/dist/cli.mjs" "$TS" "$@"
  fi
fi

if [ ! -f "$JS" ]; then
  echo "qmd is not built: missing $JS" >&2
  echo "Run: bun install && bun run build" >&2
  echo "Or:  npm install && npm run build" >&2
  echo "After building, run: qmd doctor" >&2
  exit 1
fi

# Detect the package manager that installed dependencies by checking lockfiles.
# $BUN_INSTALL is intentionally NOT checked — it only indicates that bun exists
# on the system, not that it was used to install this package (see #361).
#
# package-lock.json takes priority: if it exists, npm installed the native
# modules for Node.  The repo ships bun.lock, so without this check, source
# builds that use npm would be incorrectly routed to bun, causing ABI
# mismatches with better-sqlite3 / sqlite-vec (see #381).
if [ -f "$DIR/package-lock.json" ]; then
  exec node "$JS" "$@"
elif [ -f "$DIR/bun.lock" ] || [ -f "$DIR/bun.lockb" ]; then
  exec bun "$JS" "$@"
else
  exec node "$JS" "$@"
fi
