-- REPL Server: Lua REPL over TCP
-- Enabled when RELENCIA_ENV=local

-- Load helper functions
dofile('/modules/repl/dbg.lua')

-- Find an available port, starting from default and incrementing
local basePort = tonumber(os.getenv("RELENCIA_REPL_PORT")) or 17777
local maxAttempts = 20
local server = nil
local actualPort = nil

for i = 0, maxAttempts - 1 do
    local tryPort = basePort + i
    server = Server.create(tryPort)
    if server then
        actualPort = tryPort
        break
    end
end

if not server then
    g_logger.error("REPL: Failed to find available port in range " .. basePort .. "-" .. (basePort + maxAttempts - 1))
    return
end

-- Store port globally so it can be queried
_G.REPL_PORT = actualPort

function server:onAccept(connection, errMsg, errCode)
    if errCode and errCode ~= 0 then
        g_logger.warning("REPL: Accept error: " .. errMsg)
        server:acceptNext()
        return
    end

    function connection:onRecv(data)
        local code = data:gsub("\n$", "")
        local fn, compileErr = loadstring(code)

        if not fn then
            self:write("ERROR: " .. tostring(compileErr) .. "\n")
            self:close()
            return
        end

        local ok, result = pcall(fn)
        if ok then
            if result == nil then
                self:write("(nil)\n")
            else
                self:write(dump(result) .. "\n")
            end
        else
            self:write("ERROR: " .. tostring(result) .. "\n")
        end
        self:close()
    end

    connection:read_until("\n")
    server:acceptNext()
end

server:acceptNext()

-- Print in a parseable format for scripts
print("REPL_PORT=" .. actualPort)
g_logger.info("REPL server listening on port " .. actualPort)
