import { spawn } from 'node:child_process'

function encodeMessage(payload) {
  const body = Buffer.from(JSON.stringify(payload), 'utf8')
  const len = Buffer.alloc(4)
  len.writeUInt32LE(body.length, 0)
  return Buffer.concat([len, body])
}

function decodeMessages(buffer) {
  const messages = []
  let offset = 0
  while (offset + 4 <= buffer.length) {
    const len = buffer.readUInt32LE(offset)
    if (offset + 4 + len > buffer.length) break
    const body = buffer.subarray(offset + 4, offset + 4 + len)
    messages.push(JSON.parse(body.toString('utf8')))
    offset += 4 + len
  }
  return messages
}

const child = spawn(process.execPath, ['host.mjs'], {
  cwd: process.cwd(),
  stdio: ['pipe', 'pipe', 'inherit'],
})

const chunks = []
child.stdout.on('data', (chunk) => chunks.push(chunk))

child.stdin.write(encodeMessage({ action: 'ping' }))
setTimeout(() => {
  child.stdin.end()
}, 120)

child.on('exit', () => {
  const out = Buffer.concat(chunks)
  const messages = decodeMessages(out)
  // eslint-disable-next-line no-console
  console.log(JSON.stringify(messages, null, 2))
})
