local cmp = require("cmp")
local http = require("socket.http")
local ltn12 = require("ltn12")
local json = require("dkjson")  -- Asegúrate de que tienes soporte para JSON en Lua

local function fetch_ollama_completion(prompt)
    local response_body = {}
    local req_body = json.encode({
        model = "deepseek-r1:14b",  -- Cambia esto si usas otro modelo
        prompt = prompt,
        stream = false
    })

    local result, code = http.request({
        url = "http://localhost:11434/api/generate",  -- Ollama API local
        method = "POST",
        headers = {
            ["Content-Type"] = "application/json",
            ["Content-Length"] = tostring(#req_body),
        },
        source = ltn12.source.string(req_body),
        sink = ltn12.sink.table(response_body),
    })

    if code == 200 and response_body[1] then
        local decoded = json.decode(table.concat(response_body))
        if decoded and decoded.response then
            return decoded.response
        end
    end

    return ""
end

cmp.register_source("ollama", {
    complete = function(self, request, callback)
        local input = table.concat(request.context.cursor_before_line or "", " ")
        local response = fetch_ollama_completion(input)

        if response and response ~= "" then
            callback({ { label = response, insertText = response, kind = cmp.lsp.CompletionItemKind.Text } })
        else
            callback({})
        end
    end,
})

