const fs = require('fs');
const path = require('path');

const soundsDir = path.join(__dirname, '..', 'public_build', 'sounds');
const appJsPath = path.join(__dirname, '..', 'public_build', 'app.js');
const placeholder = '// __SOUND_DATA_PLACEHOLDER__';

console.log('--- Inlining audio files into app.js ---');

try {
    const soundFiles = fs.readdirSync(soundsDir).filter(file => file.endsWith('.mp3'));
    const soundData = {};

    soundFiles.forEach(file => {
        const filePath = path.join(soundsDir, file);
        const fileBuffer = fs.readFileSync(filePath);
        const base64String = fileBuffer.toString('base64');
        const key = path.basename(file, '.mp3');
        soundData[key] = `data:audio/mpeg;base64,${base64String}`;
        console.log(`  - Inlined ${file}`);
    });

    const soundDataJSON = JSON.stringify(soundData, null, 2);
    const replacementString = `const soundData = ${soundDataJSON};`;

    let appJsContent = fs.readFileSync(appJsPath, 'utf8');
    if (appJsContent.includes(placeholder)) {
        appJsContent = appJsContent.replace(placeholder, replacementString);
        fs.writeFileSync(appJsPath, appJsContent, 'utf8');
        console.log('--- Successfully injected sound data into app.js ---');
    } else {
        throw new Error(`Placeholder "${placeholder}" not found in app.js!`);
    }

} catch (error) {
    console.error('!!! Error inlining audio:', error.message);
    process.exit(1);
}
