// Host audio plumbing for local playback: a PulseAudio daemon and a null sink named `virtual_out`.
// cliamp plays *into* that sink (PULSE_SINK) and the capture side reads `virtual_out.monitor`, so the
// sink has to exist before either of them starts — which is why this runs at sidecar startup rather
// than on first play. Both steps are idempotent and both failures are non-fatal: a host without
// pulseaudio simply has no browser playback, and everything else the music sidecar does still works.

export const VIRTUAL_SINK = 'virtual_out';

export function ensurePulseAudio(): void {
  const pulseaudio = Bun.which('pulseaudio');
  const pactl = Bun.which('pactl');
  if (!pulseaudio || !pactl) {
    console.log('[music] pulseaudio not installed, skipping audio setup');
    return;
  }

  const check = Bun.spawnSync({ cmd: [pulseaudio, '--check'], stdout: 'ignore', stderr: 'ignore' });
  if (check.exitCode !== 0) {
    const start = Bun.spawnSync({ cmd: [pulseaudio, '--start', '-D'], stdout: 'ignore', stderr: 'ignore' });
    if (start.exitCode !== 0) {
      console.error('[music] failed to start pulseaudio');
      return;
    }
    console.log('[music] pulseaudio started');
  } else {
    console.log('[music] pulseaudio already running');
  }

  const sinks = Bun.spawnSync({ cmd: [pactl, 'list', 'short', 'sinks'], stdout: 'pipe', stderr: 'ignore' });
  if (sinks.stdout.toString().includes(VIRTUAL_SINK)) {
    console.log(`[music] ${VIRTUAL_SINK} sink already exists`);
    return;
  }

  const load = Bun.spawnSync({
    cmd: [
      pactl,
      'load-module',
      'module-null-sink',
      `sink_name=${VIRTUAL_SINK}`,
      'sink_properties=device.description=Virtual_Output',
    ],
    stdout: 'pipe',
    stderr: 'pipe',
  });
  if (load.exitCode !== 0) console.error('[music] failed to load null sink:', load.stderr.toString().trim());
  else console.log(`[music] ${VIRTUAL_SINK} null sink loaded`);
}
