/**
 * Script to download notification sound from YouTube
 * Uses @distube/ytdl-core to download audio
 */

const ytdl = require('@distube/ytdl-core');
const fs = require('fs');
const path = require('path');

const YOUTUBE_URL = 'https://www.youtube.com/watch?v=utmKQWAuYH4';
const OUTPUT_PATH = path.join(__dirname, '..', 'public', 'notification.mp3');

console.log('Downloading notification sound from YouTube...');
console.log(`URL: ${YOUTUBE_URL}`);
console.log(`Output: ${OUTPUT_PATH}`);

async function downloadAudio() {
  try {
    // Validate URL
    if (!ytdl.validateURL(YOUTUBE_URL)) {
      throw new Error('Invalid YouTube URL');
    }

    // Get video info
    console.log('\nFetching video information...');
    const info = await ytdl.getInfo(YOUTUBE_URL);
    console.log(`Title: ${info.videoDetails.title}`);

    // Get audio format
    const audioFormats = ytdl.filterFormats(info.formats, 'audioonly');
    if (audioFormats.length === 0) {
      throw new Error('No audio formats available');
    }

    // Select best quality audio
    const format = audioFormats[0];
    console.log(`\nDownloading audio format: ${format.audioCodec || 'unknown'}`);

    // Create write stream
    const outputStream = fs.createWriteStream(OUTPUT_PATH);
    
    // Download audio
    const audioStream = ytdl.downloadFromInfo(info, { format });
    
    audioStream.pipe(outputStream);
    
    audioStream.on('progress', (chunkLength, downloaded, total) => {
      const percent = (downloaded / total * 100).toFixed(2);
      process.stdout.write(`\rDownloaded: ${percent}%`);
    });

    await new Promise((resolve, reject) => {
      outputStream.on('finish', () => {
        console.log('\n\n✅ Successfully downloaded notification sound!');
        resolve();
      });
      outputStream.on('error', reject);
      audioStream.on('error', reject);
    });

  } catch (error) {
    console.error('\n❌ Error downloading audio:', error.message);
    console.error('\nAlternative options:');
    console.log('1. Install yt-dlp: pip install yt-dlp');
    console.log('2. Download executable: https://github.com/yt-dlp/yt-dlp/releases');
    console.log('3. Use online converter');
    console.log('\nThen run:');
    console.log(`yt-dlp -x --audio-format mp3 --audio-quality 0 -o "public/notification.mp3" "${YOUTUBE_URL}"`);
    process.exit(1);
  }
}

downloadAudio();

