local M = {}

M.fish_completer = function(query, ctx, fields)
    -- Ensure any quotes in input are properly escaped
    ctx = ctx:gsub('"', '\\"')
    ctx = ctx:gsub("'", "\\'")

    -- Run fish
    local cmd = "fish --command 'complete \"--do-complete=" .. ctx .. "\"'"
    local res = io.popen(cmd)
    local raw_str = res:read('*all')

    -- Extract completion items
    -- local values = table.map(string.split(raw_str, "\n"), function(v)
    --     return string.split(v, "\t")
    -- end)
    local values = string.split(raw_str, "\n")
    local comp_items = {}
    for _, v in pairs(values) do
        local _, count = string.gsub(v, " ", "")
        if count > 0 then
            local split = string.split(v, "\t")
            comp_items[split[1]] = { split[2] }
        else
            comp_items[#comp_items+1] = v
        end
    end
    -- for _, v in pairs(string.split(raw_str, "\n")) do
    --     local comp_val = string.split(v, "\t")
    --     values[comp_val[1]] = comp_val[2]
    -- end

    -- Only extract completions that start with given prefix
    -- (fish doesn't consistently do this it seems)
    -- if query ~= "" then
    --     for i = #values,1,-1 do
    --         if values[i]:find(query, 1, True) ~= 1 then
    --             table.remove(values, i)
    --         end
    --     end
    -- end

    -- Construct completion items table
    local comp = {
        {
            items = comp_items,
            type = 'list'
        }
    }

    return comp, query
end

return M
