-- Integration-test driver: the REAL reactive MCP computer server. Connects the real
-- libcloud daemon to the gateway and serves exec-lua / run-file / write-file via cloud.serve
-- (same wiring as daemons/mcp-computer-server.lua), then stays registered so the TS
-- side can drive the MCP tools over the gateway.
--
-- Args (via shell.run): url, secret.
--   url     gateway origin, e.g. ws://127.0.0.1:PORT (daemon appends /gateway)
--   secret  shared secret ('' / '-' => none)
local args = { ... };
local url = args[1];
local secret = args[2];
if secret == '' or secret == '-' then secret = nil; end

local createCloud = require('/apis/libcloud');
local createMcpComputer = require('/apis/libmcpcomputer');
local createEventLoop = require('/apis/eventloop');

_G.bootEventLoop = createEventLoop();
local el = _G.bootEventLoop;
local cloud = createCloud();
local mcp = createMcpComputer();

cloud.startSession({
  eventloop = el,
  url = url,
  secret = secret,
  os = os,
});

cloud.serve('exec-lua', function(payload)
  local result = mcp.executeLua(payload and payload.code);
  return true, {
    ok = result.ok,
    returns = result.returns or {},
    output = result.output or '',
    error = result.error,
  };
end, { eventloop = el });

cloud.serve('run-file', function(payload)
  local result = mcp.executeFile(payload and payload.path, nil, payload and payload.args);
  return true, {
    ok = result.ok,
    returns = result.returns or {},
    output = result.output or '',
    error = result.error,
  };
end, { eventloop = el });

cloud.serve('write-file', function(payload)
  local result = mcp.writeFile(payload and payload.path, payload and payload.content);
  return true, {
    ok = result.ok,
    path = result.path,
    bytes = result.bytes,
    error = result.error,
  };
end, { eventloop = el });

local function runReady()
  os.pullEvent('trapos_cloud_connected');
  print('__CLOUD_READY__ ' .. cloud.traposId(os));
  os.sleep(12);
end

parallel.waitForAny(
  function() el.runLoop(true); end,
  runReady
);

os.shutdown();
