module DEBUGGER__::UI_DAP

def self.setup debug_port

def self.setup debug_port
  if File.directory? '.vscode'
    dir = Dir.pwd
  else
    dir = Dir.mktmpdir("ruby-debug-vscode-")
    tempdir = true
  end
  at_exit do
    DEBUGGER__.skip_all
    FileUtils.rm_rf dir if tempdir
  end
  key = rand.to_s
  Dir.chdir(dir) do
    Dir.mkdir('.vscode') if tempdir
    # vscode-rdbg 0.0.9 or later is needed
    open('.vscode/rdbg_autoattach.json', 'w') do |f|
      f.puts JSON.pretty_generate({
        type: "rdbg",
        name: "Attach with rdbg",
        request: "attach",
        rdbgPath: File.expand_path('../../exe/rdbg', __dir__),
        debugPort: debug_port,
        localfs: true,
        autoAttach: key,
      })
    end
  end
  cmds = ['code', "#{dir}/"]
  cmdline = cmds.join(' ')
  ssh_cmdline = "code --remote ssh-remote+[SSH hostname] #{dir}/"
  STDERR.puts "Launching: #{cmdline}"
  env = ENV.delete_if{|k, h| /RUBY/ =~ k}.to_h
  env['RUBY_DEBUG_AUTOATTACH'] = key
  unless system(env, *cmds)
    DEBUGGER__.warn <<~MESSAGE
    Can not invoke the command.
    Use the command-line on your terminal (with modification if you need).
      #{cmdline}
    If your application is running on a SSH remote host, please try:
      #{ssh_cmdline}
    MESSAGE
  end
end