const { exec } = require('child_process');

let inputBuffer = '';

process.stdin.on('data', (chunk) => {
  inputBuffer += chunk.toString();
  while (true) {
    if (inputBuffer.length < 4) break;
    const length = Buffer.from(inputBuffer.substring(0, 4), 'binary').readUInt32LE(0);
    if (inputBuffer.length < 4 + length) break;
    const messageStr = inputBuffer.substring(4, 4 + length);
    inputBuffer = inputBuffer.substring(4 + length);
    handleMessage(messageStr);
  }
});

process.stdin.on('end', () => {
  process.exit(0);
});

function handleMessage(messageStr) {
  let msg;
  try {
    msg = JSON.parse(messageStr);
  } catch (e) {
    sendResponse({ error: 'Invalid JSON' });
    return;
  }

  const command = msg.command;
  const timeout = msg.timeout || 30000;

  if (!command) {
    sendResponse({ error: 'No command provided' });
    return;
  }

  exec(command, { timeout, maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {
    const result = {
      stdout: stdout || '',
      stderr: stderr || '',
      exitCode: error ? error.code || 1 : 0,
      success: !error
    };
    if (error && error.killed) {
      result.stderr = `Command timed out after ${timeout}ms`;
      result.exitCode = -1;
    }
    sendResponse(result);
  });
}

function sendResponse(obj) {
  const json = JSON.stringify(obj);
  const length = Buffer.byteLength(json, 'utf8');
  const header = Buffer.alloc(4);
  header.writeUInt32LE(length, 0);
  process.stdout.write(header);
  process.stdout.write(json);
}
