const JavaScriptObfuscator = require('javascript-obfuscator');
const fs = require('fs');
const path = require('path');

const PUBLIC_JS_DIR = path.join(__dirname, 'public', 'js');
const OUTPUT_DIR = path.join(__dirname, 'public', 'js', 'dist');

// Obfuscation options - balanced between security and performance
const obfuscationOptions = {
    compact: true,
    controlFlowFlattening: true,
    controlFlowFlatteningThreshold: 0.75,
    deadCodeInjection: true,
    deadCodeInjectionThreshold: 0.4,
    debugProtection: false,
    debugProtectionInterval: 0,
    disableConsoleOutput: true,
    identifierNamesGenerator: 'hexadecimal',
    log: false,
    numbersToExpressions: true,
    renameGlobals: false,
    selfDefending: true,
    simplify: true,
    splitStrings: true,
    splitStringsChunkLength: 10,
    stringArray: true,
    stringArrayCallsTransform: true,
    stringArrayEncoding: ['base64'],
    stringArrayIndexShift: true,
    stringArrayRotate: true,
    stringArrayShuffle: true,
    stringArrayWrappersCount: 2,
    stringArrayWrappersChainedCalls: true,
    stringArrayWrappersParametersMaxCount: 4,
    stringArrayWrappersType: 'function',
    stringArrayThreshold: 0.75,
    transformObjectKeys: true,
    unicodeEscapeSequence: false
};

// Create output directory if it doesn't exist
if (!fs.existsSync(OUTPUT_DIR)) {
    fs.mkdirSync(OUTPUT_DIR, { recursive: true });
}

console.log('[BUILD] Starting JavaScript obfuscation...');

// Get all JS files in the public/js directory
const SKIP_FILES = ['replay-canvas.js'];
const jsFiles = fs.readdirSync(PUBLIC_JS_DIR).filter(file =>
    file.endsWith('.js') && !file.startsWith('.') && !SKIP_FILES.includes(file)
);

let obfuscatedCount = 0;

jsFiles.forEach(file => {
    const inputPath = path.join(PUBLIC_JS_DIR, file);
    const outputPath = path.join(OUTPUT_DIR, file);
    
    try {
        console.log(`[BUILD] Obfuscating ${file}...`);
        
        const sourceCode = fs.readFileSync(inputPath, 'utf8');
        const obfuscationResult = JavaScriptObfuscator.obfuscate(sourceCode, obfuscationOptions);
        
        fs.writeFileSync(outputPath, obfuscationResult.getObfuscatedCode());
        
        const originalSize = (fs.statSync(inputPath).size / 1024).toFixed(2);
        const obfuscatedSize = (fs.statSync(outputPath).size / 1024).toFixed(2);
        
        console.log(`[BUILD] ✓ ${file} (${originalSize}KB → ${obfuscatedSize}KB)`);
        obfuscatedCount++;
        
    } catch (error) {
        console.error(`[BUILD] ✗ Failed to obfuscate ${file}:`, error.message);
    }
});

console.log(`\n[BUILD] Obfuscation complete! ${obfuscatedCount}/${jsFiles.length} files processed.`);
console.log(`[BUILD] Obfuscated files saved to: ${OUTPUT_DIR}`);
console.log('[BUILD] To use obfuscated files in production, set NODE_ENV=production');
