import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as qenv from '@push.rocks/qenv';
import { textToSpeech } from '../ts_audio/index.js';

const testQenv = new qenv.Qenv('./', './.nogit/');

tap.test('textToSpeech should return a readable stream', async () => {
  const apiKey = await testQenv.getEnvVarOnDemand('OPENAI_TOKEN');
  if (!apiKey) {
    console.log('OPENAI_TOKEN not set, skipping test');
    return;
  }

  const stream = await textToSpeech({
    apiKey,
    text: 'Hello, this is a test of the text to speech system.',
    voice: 'alloy',
    model: 'tts-1',
  });

  expect(stream).toBeTruthy();
  expect(stream.readable).toBeTrue();

  // Read some bytes to verify it's actual audio data
  const chunks: Buffer[] = [];
  for await (const chunk of stream) {
    chunks.push(Buffer.from(chunk));
    if (chunks.length > 2) break; // Just read a few chunks to verify
  }

  const totalBytes = chunks.reduce((sum, c) => sum + c.length, 0);
  console.log(`Audio stream produced ${totalBytes} bytes in ${chunks.length} chunks`);
  expect(totalBytes).toBeGreaterThan(0);
});

export default tap.start();
