#!/bin/sh
set -eu

BASE_URL='https://api-dev.mlx.fast'
BIN_DIR="${MLXFAST_BIN_DIR:-$HOME/.local/bin}"
LIB_DIR="${MLXFAST_LIB_DIR:-$HOME/.local/share/mlxfast}"
CLI_PATH="$LIB_DIR/mlxfast.js"
CLI_BIN="$BIN_DIR/mlxfast"

say() { printf '%s\n' "$1"; }
fail() { printf 'error: %s\n' "$1" >&2; exit 1; }
shell_quote() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\''/g")"; }
curl_file() {
  url=$1
  output=$2
  if curl --retry 8 --retry-all-errors --connect-timeout 20 --tls-max 1.2 -fsSL "$url" -o "$output"; then return 0; fi
  if curl --retry 8 --connect-timeout 20 --tls-max 1.2 -fsSL "$url" -o "$output"; then return 0; fi
  curl --retry 8 --connect-timeout 20 -fsSL "$url" -o "$output"
}

command -v curl >/dev/null 2>&1 || fail 'curl is required to install MLX Fast CLI'
command -v sed >/dev/null 2>&1 || fail 'sed is required to install MLX Fast CLI'

if command -v bun >/dev/null 2>&1; then
  BUN_PATH=$(command -v bun)
else
  command -v bash >/dev/null 2>&1 || fail 'bash is required to install Bun'
  say 'Bun is required for the MLX Fast CLI. Installing Bun...'
  curl -fsSL https://bun.sh/install | bash
  if [ -x "$HOME/.bun/bin/bun" ]; then
    BUN_PATH="$HOME/.bun/bin/bun"
  elif command -v bun >/dev/null 2>&1; then
    BUN_PATH=$(command -v bun)
  else
    fail 'Bun install finished, but bun was not found. Add ~/.bun/bin to PATH and rerun this installer.'
  fi
fi

mkdir -p "$BIN_DIR" "$LIB_DIR"
TMP_FILE="$CLI_PATH.tmp.$$"
trap 'rm -f "$TMP_FILE"' EXIT HUP INT TERM
say "Downloading MLX Fast CLI from $BASE_URL..."
curl_file "$BASE_URL/cli/mlxfast.js" "$TMP_FILE"
[ -s "$TMP_FILE" ] || fail "downloaded CLI payload is empty"
mv "$TMP_FILE" "$CLI_PATH"

{
  printf '%s\n' '#!/bin/sh'
  printf 'if [ -z "${MLXFAST_API_URL:-}" ]; then export MLXFAST_API_URL=%s; fi\n' "$(shell_quote "$BASE_URL")"
  printf 'if [ -z "${MLXFAST_BENCHMARK_REF:-}" ]; then export MLXFAST_BENCHMARK_REF=%s; fi\n' "$(shell_quote 'gpsanant/mlxfast-challenge-dev-serial-v2-3')"
  printf 'exec %s %s "$@"\n' "$(shell_quote "$BUN_PATH")" "$(shell_quote "$CLI_PATH")"
} > "$CLI_BIN"
chmod +x "$CLI_BIN"

say "Installed mlxfast to $CLI_BIN"
if [ "${MLXFAST_INSTALL_SKILL:-1}" != "0" ]; then
  "$CLI_BIN" install-skill
fi

say 'CLI telemetry is enabled after login. Disable it with: mlxfast config --telemetry disabled'
say 'Trace capture is enabled and strongly recommended. mlxfast clone sets up coding-agent hooks in the repo; launch your coding agent from inside the cloned repo so its reasoning traces are recorded.'
if ! command -v mlxfast >/dev/null 2>&1; then
  say "Add $BIN_DIR to your PATH to run mlxfast from any shell."
fi
say 'Done. Try: mlxfast --help'
