local log = require 'down.log'
local mod = require 'down.mod'

local cmpok, cmp = pcall(require, 'cmp')

---@class down.mod.integration.Cmp: down.Mod
local M = mod.new 'integration.cmp'

M.clean = function(s)
  if not s then
    return s
  end
  s = s:gsub('\n', ' ')
  return s:gsub('%s%s+', ' ')
end

--- Scan directory recursively for files
---@param dir string
---@param pattern? string
---@return string[]
local function scan_dir(dir, pattern)
  local files = {}
  pattern = pattern or "**/*"

  local scan_results = vim.fn.globpath(dir, pattern, true, true)
  for _, file in ipairs(scan_results) do
    if vim.fn.isdirectory(file) == 0 then
      table.insert(files, file)
    end
  end

  return files
end

---@class down.mod.integration.cmp.Data
M.files = function()
  local items = {}
  local root = M.dep['workspace'].get_current_workspace()[2]
  local ext = mod.mod_config 'workspace'.ext or '.md'

  local files = scan_dir(root, '**/*' .. ext)
  for _, path in ipairs(files) do
    local item = {
      path = path,
      label = path:match('([^/^\\]+)' .. ext .. '$'),
      kind = cmp.lsp.CompletionItemKind.File,
    }
    item.insertText = '[' .. item.label .. '](' .. item.path .. ')'
    local binary = assert(io.open(item.path, 'rb'))
    local kb = binary:read(1024)
    item.documentation = {
      kind = cmp.lsp.MarkupKind.Markdown,
      value = kb,
    }
    binary:close()
    local body = {}
    if kb then
      for b in kb:gmatch('[^\r\n1]+') do
        table.insert(body, b)
      end
    end
    table.insert(items, item)
  end
  return items
end

M.tags = function()
  local tags = {}
  local root = M.dep['workspace'].get_current_workspace()[2]
end

---@class down.mod.integration.cmp.Config
M.config = {}

---@return down.mod.Setup
M.setup = function()
  if cmpok then
    return {
      loaded = true,
      dependencies = { 'workspace', 'tag', 'data', 'integration.treesitter' },
    }
  else
    return { loaded = false }
  end
end

M.load = function() end

return M
