local dap = require("dap")
local dapui = require("dapui")

-- Setup dap-ui
dapui.setup()

-- Auto-open UI on DAP start
dap.listeners.after.event_initialized["dapui_config"] = function()
  dapui.open()
end
dap.listeners.before.event_terminated["dapui_config"] = function()
  dapui.close()
end
dap.listeners.before.event_exited["dapui_config"] = function()
  dapui.close()
end

-- Paths for Mason v2 codelldb adapter
local mason_path = vim.fn.stdpath("data") .. "/mason/packages/codelldb/extension"
local adapter_path = mason_path .. "/adapter/codelldb"
local liblldb_path = mason_path .. "/lldb/lib/liblldb.so"

-- Register the DAP adapter
dap.adapters.codelldb = {
  type = "server",
  host = "127.0.0.1",
  port = "${port}",
  executable = {
    command = adapter_path,
    args = { "--port", "${port}" },
  },
}

-- Debug configuration for Rust
dap.configurations.rust = {
  {
    name = "Launch Rust",
    type = "codelldb",
    request = "launch",
    program = function()
      return vim.fn.input(
        "Path to executable: ",
        vim.fn.getcwd() .. "/target/debug/",
        "file"
      )
    end,
    cwd = "${workspaceFolder}",
    stopOnEntry = false,
    args = {},
    runInTerminal = false,
  },
}
