class SvelteOnRails::Configuration

def node_bin_path

def node_bin_path
  @node_bin_path ||= begin
                       n = ENV['SVELTE_ON_RAILS_NODE_BIN'] || 'node'
                       if n == 'node'
                         nvm_installed = false
                         nvm_dir = ENV['NVM_DIR'] || File.expand_path('~/.nvm')
                         nvm_installed ||= File.exist?("#{nvm_dir}/nvm.sh")
                         if nvm_installed
                           # Check for .nvmrc in the project root
                           project_root = rails_root || Dir.pwd
                           nvmrc_path = File.join(project_root, '.nvmrc')
                           use_nvmrc = File.exist?(nvmrc_path)
                           if use_nvmrc
                             # Read the version from .nvmrc
                             node_version = File.read(nvmrc_path).strip
                             # Ensure NVM is sourced and use the version from .nvmrc
                             command = "[ -s \"#{nvm_dir}/nvm.sh\" ] && . \"#{nvm_dir}/nvm.sh\" && nvm use #{node_version} > /dev/null 2>&1 && nvm which #{node_version}"
                           else
                             # Fallback to current NVM version
                             command = "[ -s \"#{nvm_dir}/nvm.sh\" ] && . \"#{nvm_dir}/nvm.sh\" && nvm which current"
                           end
                           node_path, status = Open3.capture2("bash -lc '#{command}'")
                           # Only update n if the command succeeded and output is non-empty
                           n = node_path.strip if status.success? && !node_path.strip.empty?
                         end
                       end
                       # Validate node_bin
                       unless n && !n.empty? && system("#{n} --version > /dev/null 2>&1")
                         raise "Node.js not found at '#{n || 'unknown'}'. Please configure SVELTE_ON_RAILS_NODE_BIN (e.g., to ~/.nvm/versions/node/vX.Y.Z/bin/node) or ensure 'node' is in the PATH. If using NVM, run `nvm alias default <version>` to set a default version or ensure a valid .nvmrc file is present."
                       end
                       n
                     rescue StandardError => e
                       raise "Failed to detect Node.js binary: «#{e.message}». Ensure Node.js is installed and accessible, or set SVELTE_ON_RAILS_NODE_BIN. If using .nvmrc, ensure the specified version is installed via NVM."
                     end
end