-- Highlight lines with treesitter if using the item.detail with the item.label
-- field. Would need to be languag and language server specific

-- if item.detail == nil thn return item.label end
-- if vim.startswith(item.detail, 'fn') then
--   return item.label:sub(0, require('blink.cmp.util').find_last_alphanum_or_dash_underscore(item.label))
--     .. item.detail:sub(3):gsub('…', '..')
-- end
-- return item.label

local function get_highlights_for_string(bufnr, line, start_col, end_col, item)
  local parser = vim.treesitter.get_parser(bufnr, 'rust')
  local tree = parser:parse({ line, start_col, line, end_col })[1]
  local root = tree:root()

  local start_row, _, end_row, _ = root:range()
  if line < start_row or line > end_row then
    return {} -- Line is out of range
  end

  local highlights = {}
  local query = vim.treesitter.query.get(parser:lang(), 'highlights')
  if not query then return highlights end

  for id, node, _ in query:iter_captures(root, bufnr, line, line + 1) do
    local name = query.captures[id]
    local capture_start_row, capture_start_col, capture_end_row, capture_end_col = node:range()

    if capture_start_row == line and (capture_start_col < end_col or capture_end_col > start_col) then
      table.insert(highlights, {
        math.max(start_col, capture_start_col),
        math.min((capture_end_row == line) and capture_end_col or end_col, end_col),
        group = name,
      })
    end
  end
  -- if item.kind == vim.lsp.protocol.CompletionItemKind.Function then
  --   local start_alpha_numeric = 1
  --   for i = 1, #text do
  --     if text:sub(i, i):match('[%w_]') or text:sub(i, i) == '-' then
  --       start_alpha_numeric = i
  --       break
  --     end
  --   end
  --   local end_alpha_numeric = start_alpha_numeric
  --   for i = start_alpha_numeric, #text do
  --     if text:sub(i, i):match('[%w_]') or text:sub(i, i) == '-' then
  --       end_alpha_numeric = i
  --     else
  --       break
  --     end
  --   end
  --
  --   if start_alpha_numeric ~= end_alpha_numeric then
  --     table.insert(highlights, {
  --       start_alpha_numeric - 1,
  --       end_alpha_numeric - 1,
  --       group = 'Function',
  --     })
  --   end
  -- end

  return vim.tbl_map(function(hl) return { hl[1], hl[2], group = hl.group } end, highlights)
end

function utils.find_last_alphanum_or_dash_underscore(str)
  -- Reverse the string
  local reversed = string.reverse(str)

  -- Find the first (which is actually the last in the original string)
  -- alphanumeric or dash or underscore character
  local _, pos = string.find(reversed, '[%w_-]')

  if pos then
    -- Return the position in the original string
    return #str - pos + 1
  else
    -- Return nil if no such character is found
    return nil
  end
end

return get_highlights_for_string