const axios = require('axios');
const AWS = require('aws-sdk');
const FormData = require('form-data');

const aiTextToSpeech = async (req, res) => {
  AWS.config.update({
    region: 'ap-south-1',
    accessKeyId: process.env.AWS_polly2_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_polly2_SECRET_ACCESS_KEY,
  });

  const polly = new AWS.Polly();
  const voiceIdMap = {
    "Ava": "Ivy",
    "Monstero": "Justin",
    "Dax": "Kevin",
    "Kai": "Danielle",
    "Arlo": "Ruth",
    "Yara": "Salli"
  };

  const { text, voiceId: frontendVoiceId } = req.body;

  if (!text || !frontendVoiceId) {
    return res.status(400).json({ error: 'Text and voiceId are required' });
  }

  const pollyVoiceId = voiceIdMap[frontendVoiceId];
  if (!pollyVoiceId) {
    return res.status(400).json({ error: 'Invalid voiceId provided' });
  }

  const params = {
    Text: text,
    OutputFormat: 'mp3',
    Engine: 'neural',
    VoiceId: pollyVoiceId,
  };

  try {
    function generateTimestampWithRandomDigits() {
      const now = new Date();
      const formattedDate = now.toISOString().replace('T', '_').replace(/\..+/, '').replace(/:/g, '-');
      const randomDigits = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      return `${formattedDate}_${randomDigits}`;
    }

    const folder = generateTimestampWithRandomDigits();
    const folderName = `audio_files/${folder}`;

    const data = await polly.synthesizeSpeech(params).promise();
    const audioBuffer = data.AudioStream;

    const textBuffer = Buffer.from(text, 'utf-8');

    const formData = new FormData();
    formData.append('file1', audioBuffer, 'speech.mp3');
    formData.append('file2', textBuffer, 'text.txt');
    // formData.append('folder', folderName); // Send folder name
    formData.append('bucket', 'polly-bs'); // Adjust bucket

    const response = await axios.post(
      'https://preschool-curriculum.in/api/one/v1/file/upload',
      formData,
      {
        headers: {
          // 'Authorization': `Bearer ${process.env.BEARER_TOKEN}`,
          ...formData.getHeaders() // Ensure FormData headers are included
        }
      }
    );

    res.json({
      message: 'Speech generated and saved successfully',
      fileUrls: response.data.urls,
      fileKeys: response.data.data
    });

  } catch (error) {
    console.error('Error generating speech or uploading files:', error);
    res.status(500).json({ error: 'Error generating speech or uploading files' });
  }
};

module.exports = aiTextToSpeech;
