const axios = require('axios');
const fs = require('fs');
const crypto = require('crypto');
const player = require('play-sound')(opts = {});
const { ipcMain } = require('electron');

// Directory where audio files will be cached
const cacheDirectory = './speech_cache/';

// Create cache directory if it does not exist
if (!fs.existsSync(cacheDirectory)) {
  fs.mkdirSync(cacheDirectory);
}

ipcMain.handle('getSpeech', async (event, text) => {
  // Create a hash of the text to use as a unique filename
  const filename = crypto.createHash('md5').update(text).digest('hex') + '.mp3';

  // Full path of the audio file in the cache directory
  const filepath = cacheDirectory + filename;

  // Check if audio file already exists in the cache
  if (!fs.existsSync(filepath)) {
    // If audio file does not exist, make API request
    try {
      const response = await axios({
        method: 'post',
        url: 'https://api.elevenlabs.io/v1/text-to-speech/8JNqTOY3RaSYcHTVJZ0G',
        headers: {
          'Content-Type': 'application/json',
          'xi-api-key': 'd191e27c2e5b07573b39fe70f0783f48'
        },
        data: {
          text: text,
          model_id: 'eleven_multilingual_v1',
          voice_settings: {
            stability: 0,
            similarity_boost: 0,
            style: 0.5,
            use_speaker_boost: true
          }
        },
        responseType: 'arraybuffer'
      });

      // Write the audio data to a file in the cache directory
      fs.writeFileSync(filepath, response.data);

    } catch (error) {
      console.error(`Error making API request: ${error}`);
    }
  }
  return filepath
});