const WebSocket = require('ws');

const ws = new WebSocket('wss://ai.jerxie.com/api/v1/nodes/test-prod-node/stream');

ws.on('open', function open() {
  console.log('connected, waiting for events...');
});

ws.on('message', function incoming(data) {
  const msg = JSON.parse(data);
  if (msg.event !== 'heartbeat') {
    console.log('[EVENT]', msg.event, JSON.stringify(msg.data));
  }
  if (msg.event === 'task_complete' || msg.event === 'task_error') {
    process.exit(0);
  }
});

// Also dispatch a command
setTimeout(async () => {
  const http = require('https');
  const body = JSON.stringify({ command: 'uname -a; id; pwd', timeout_ms: 15000 });
  const req = http.request({
    hostname: 'ai.jerxie.com', path: '/api/v1/nodes/test-prod-node/dispatch',
    method: 'POST', headers: {'Content-Type': 'application/json', 'X-User-ID': '9a333ccd-9c3f-432f-a030-7b1e1284a436', 'Content-Length': body.length}
  }, res => { let data = ''; res.on('data', d => data += d); res.on('end', () => console.log('[DISPATCH]', data)); });
  req.write(body);
  req.end();
}, 1000);

setTimeout(() => { console.log('timeout'); process.exit(1); }, 20000);
