import openai from '../external-services/openai.js';

const interpretAudioGenPrompt = async (prompt: string) => {
  try {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      temperature: 0.8,
      tool_choice: {
        type: 'function',
        function: {
          name: 'generateAudio',
        },
      },
      tools: [
        {
          type: 'function',
          function: {
            name: 'generateAudio',
            parameters: {
              type: 'object',
              properties: {
                bpm: {
                  type: 'number',
                  description: 'The beats per minute of the audio to generate. Omit if none was specified by the user.',
                },
                key: {
                  type: 'string',
                  description: 'The musical key of the audio to generate. Omit if none was specified by the user.',
                },
                // soundEffect: {
                //   type: 'boolean',
                //   description: 'Whether the audio is a sound effect or not.',
                // },
                movieScene: {
                  type: 'string',
                  description:
                    '2-3 word description of the kind of movie scene, location, or setting where the described audio would be well-used as a soundtrack. Avoid using terms which could easily be associated with a genre that has not been mentioned.',
                },
                textPrompt: {
                  type: 'string',
                  description:
                    'Detailed text prompt describing style and other details not captured by other parameters. The system will prefer to generate full multi-instrumental clips by default. To encourage it to generate fewer simultaneous instruments, be clever and include words like "solo" or "atonal" throughout your prompt to produce results that are in line with the user\'s prompt. Mentioning an instrument by name is not sufficient - you must add additional terms to rule out other instruments.',
                },
              },
              required: ['textPrompt', 'movieScene'],
            },
          },
        },
      ],
      messages: [
        {
          role: 'system',
          content:
            'You are choosing the correct parameters to pass to an audio generation API. The user will describe what they want, and you will invoke the "generateAudio" function with the correct parameters.',
        },
        {
          role: 'user',
          content: `${prompt}`,
        },
      ],
    });
    return JSON.parse(response.choices[0].message.tool_calls[0].function.arguments);
  } catch (e) {
    return { textPrompt: prompt };
  }
};

export default interpretAudioGenPrompt;
