export default (options) => {
  let cmd = "sox";

  if (options.binPath) {
    cmd = options.binPath;
  }

  // Build common output/encoding args
  let args = [
    "--no-show-progress",
    "--rate",
    options.sampleRate,
    "--channels",
    options.channels,
    "--encoding",
    "signed-integer",
    "--bits",
    "16",
    "--type",
    options.audioType,
    "-", // write to stdout
  ];

  if (options.bufferSize) {
    args.push("--buffer", options.bufferSize);
  }

  if (options.endOnSilence) {
    args = args.concat([
      "silence",
      "1",
      "0.1",
      options.thresholdStart || options.threshold + "%",
      "1",
      options.silence,
      options.thresholdEnd || options.threshold + "%",
    ]);
  }

  if (options.arguments) {
    args = args.concat(options.arguments);
  }

  const spawnOptions = {};

  // Prepend input spec based on platform
  const platform = process.platform;
  if (platform === "win32") {
    const rawDev = options.device;
    const dev =
      rawDev && `${rawDev}`.trim().length ? `${rawDev}`.trim() : "default";
    args.unshift("-t", "waveaudio", dev);
    // AUDIODEV sometimes respected on Windows; keep for compatibility
    spawnOptions.env = { ...process.env, AUDIODEV: dev };
  } else if (platform === "darwin") {
    // CoreAudio input
    if (options.device) {
      args.unshift("-t", "coreaudio", options.device);
    } else {
      // Explicitly select CoreAudio default device for reliability
      args.unshift("-t", "coreaudio", "default");
    }
  } else {
    // Linux: ALSA default or specified
    if (options.device) {
      args.unshift("-t", "alsa", options.device);
    } else {
      args.unshift("-d");
    }
  }

  return { cmd, args, spawnOptions };
};
