/**
 * Suno API integration for uploading audio and generating covers
 */

const SUNO_API_URL = 'https://suno-ai--flappy-dodo-audio-upload-api.modal.run';

/**
 * Upload audio to Suno and generate covers
 * @param {Blob} audioBlob - The audio blob to upload
 * @param {string} styles - Comma-separated style tags (e.g., "marimba,jazz,rock")
 * @param {boolean} isMumbleMode - Whether to enable mumble mode for creative vocal interpretation
 * @param {string} taskMode - Generation task mode: "cover" or "sample_condition"
 * @returns {Promise<Object>} The response from Suno API
 */
export async function uploadToSunoAndGenerateCovers(audioBlob: Blob, styles = 'marimba,jazz,electronic', isMumbleMode = false, taskMode = 'cover') {
  try {
    // Create FormData
    const formData = new FormData();

    // Convert blob to file with .wav extension
    const audioFile = new File([audioBlob], 'performance.wav', { type: 'audio/wav' });
    formData.append('file', audioFile);
    formData.append('styles', styles);
    formData.append('is_mumble', isMumbleMode.toString());
    formData.append('task', taskMode);

    console.log('🚀 Uploading to Suno API with styles:', styles);
    console.log('📋 FormData styles value:', formData.get('styles'));
    console.log('🎤 FormData is_mumble value:', formData.get('is_mumble'));
    console.log('🎯 FormData task value:', formData.get('task'));

    // Upload and generate covers
    const response = await fetch(`${SUNO_API_URL}/upload-and-cover`, {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log('✅ Suno API response:', data);

    return {
      success: true,
      data
    };
  } catch (error) {
    console.error('❌ Error uploading to Suno:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    };
  }
}

/**
 * Style presets for different musical genres
 */
export const STYLE_PRESETS = {
  relaxing: 'marimba,ambient,peaceful',
  energetic: 'rock,electronic,upbeat',
  jazzy: 'jazz,smooth,piano',
  classical: 'classical,orchestral,strings',
  tropical: 'reggae,tropical,beach',
  retro: '8bit,chiptune,retro',
  lofi: 'lofi,chill,study',
  epic: 'cinematic,epic,orchestral'
};

/**
 * Get a random style preset
 * @returns {string} Random style string
 */
export function getRandomStyle() {
  const keys = Object.keys(STYLE_PRESETS) as Array<keyof typeof STYLE_PRESETS>;
  const randomKey = keys[Math.floor(Math.random() * keys.length)];
  return STYLE_PRESETS[randomKey];
}
