local CONSOLE_ENTRY_HEIGHT = 22 -- Just the white section for pixel scanning
local CONSOLE_ENTRY_WIDTH = 256 -- Just a reasonable amount, the real value is small and slow to iterate

local function GetConsoleTextEntryPos()
    render.CapturePixels()

    local w, h = ScrW(), ScrH()

    for x = 0, w - 1, CONSOLE_ENTRY_WIDTH do
        x = x + 3 -- Hack to jump past caret

        for y = 0, h - 1, CONSOLE_ENTRY_HEIGHT do
            local r, g, b = render.ReadPixel(x, y)
            
            if r == 255 and g == 255 and b == 255 then
                -- We have a white match, now to ensure that the text-entry's border is around here somewhere

                for border_y = y, y - CONSOLE_ENTRY_HEIGHT - 1, -1 do
                    local r, g, b = render.ReadPixel(x, border_y)

                    if r == 79 and g == 79 and b == 79 then
                        return x, y
                    elseif r ~= 255 and g ~= 255 and b ~= 255 then
                        break
                    end
                end
            end
        end
    end
end

local function DoCmd(cmd)
    RunConsoleCommand("showconsole")
    SetClipboardText(cmd)

    timer.Simple(2, function() -- Wait for console to be open

        gui.InternalKeyCodePressed(KEY_ENTER) -- Clear out current console input
        gui.InternalKeyCodeReleased(KEY_ENTER)

        local console_x, console_y = GetConsoleTextEntryPos()

        gui.SetMousePos(console_x, console_y) -- Can't get the InternalMouseMoved to work

        timer.Simple(0.2, function()
            gui.InternalMousePressed(MOUSE_RIGHT)
            gui.InternalMouseReleased(MOUSE_RIGHT)

            gui.SetMousePos(console_x + 46, console_y + 46) -- Move to paste button

            timer.Simple(0.2, function()
                gui.InternalMousePressed(MOUSE_LEFT)
                gui.InternalMouseReleased(MOUSE_LEFT)

                timer.Simple(0.2, function()
                    gui.InternalKeyCodePressed(KEY_ENTER) -- Execute our input
                    gui.InternalKeyCodeReleased(KEY_ENTER)
                end)
            end)
        end)
    end)
end

DoCmd("echo hello!")