import log from "./log.ts"

export const LineSplitter = () => {
  let buffer = ""
  return new TransformStream({
    transform(chunk, controller) {
      buffer += chunk
      const parts = buffer.split(/\n/)
      const lines = parts.slice(0, -1)
      buffer = parts.at(-1) || ""

      for (const line of lines) {
        controller.enqueue(line)
      }
    },
    flush(controller) {
      if (buffer.length > 0) {
        controller.enqueue(buffer)
      }
    },
  })
}

export async function processStdout(
  process: Bun.ReadableSubprocess,
  onLine: (line: string) => void
) {
  for await (const line of process.stdout
    .pipeThrough(new TextDecoderStream())
    .pipeThrough(LineSplitter())) {
    onLine(line)
  }
}

export async function processStderr(process: Bun.ReadableSubprocess, prefix: string = "") {
  for await (const line of process.stderr
    .pipeThrough(new TextDecoderStream())
    .pipeThrough(LineSplitter())) {
    log.error(`❌ ${prefix}${line}`)
  }
}
