local ai = {}

local function write_output(lines, cursor)
    local new_lines = {}
    local count = 1
    new_lines[1] = ''
    for _, line in ipairs(lines) do
        for _, l in ipairs(vim.split(line, '\n')) do
            count = count + 1
            new_lines[count] = '% ' .. l
        end
    end
    new_lines[count+1] = ''
    new_lines[count+2] = ''

    vim.schedule(function()
        local buf = vim.api.nvim_get_current_buf()
        vim.api.nvim_buf_set_text(buf, cursor, 0, cursor, 0, new_lines)
    end)
end

local function run_external_command(command, input_text, cursor)
    local stdout = vim.loop.new_pipe(false)
    local stderr = vim.loop.new_pipe(false)
    local stdin = vim.loop.new_pipe(true)
    local handle

    handle = vim.loop.spawn(command, {
        stdio = {stdin, stdout, stderr},
    }, function(code)
        stdout:close()
        stderr:close()
        stdin:close()
        handle:close()
        print("Process exited with code: " .. code)
    end)

    local output = {}
    stdout:read_start(function(err, data)
        if err then
            print("Error reading stdout: " .. err)
            return
        end
        if data then
            table.insert(output, data)
        else
            stdout:read_stop()
            write_output(output, cursor)
        end
    end)

    -- Write input text to stdin
    vim.loop.write(stdin, input_text .. "\n", function(err)
        if err then
            print("Error writing to stdin: " .. err)
        end
        vim.loop.shutdown(stdin)
    end)
end

function ai.run()
    local s_start = vim.fn.getpos("'<")
    local s_end = vim.fn.getpos("'>")
    local n_lines = math.abs(s_end[2] - s_start[2]) + 1
    local lines = vim.api.nvim_buf_get_lines(0, s_start[2] - 1, s_end[2], false)
    lines[1] = string.sub(lines[1], s_start[3], -1)
    if n_lines == 1 then
        lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3] - s_start[3] + 1)
    else
        lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3])
    end
    run_external_command('/home/user/Workspace/Projects/Gemini/run.sh', table.concat(lines, '\n'), s_end[2])
end

vim.keymap.set('v', '<Leader>a', ':<C-u>call v:lua.require("ai").run()<CR>', { silent = true })

return ai
