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

// Helper function to delete a folder recursively
function deleteDirectory(directory) {
    if (fs.existsSync(directory)) {
        fs.readdirSync(directory).forEach(file => {
            const fullPath = path.join(directory, file);
            if (fs.statSync(fullPath).isDirectory()) {
                // Recursively delete subdirectories
                deleteDirectory(fullPath);
            } else {
                // Delete file
                fs.unlinkSync(fullPath);
            }
        });
        fs.rmdirSync(directory); // Remove the now empty directory
        console.log(`Deleted existing directory: ${directory}`);
    }
}

// Helper function to copy a directory recursively, while excluding certain directories
function copyDirectory(source, destination) {
    if (!fs.existsSync(destination)) {
        fs.mkdirSync(destination, { recursive: true });
    }

    const files = fs.readdirSync(source);

    files.forEach(file => {
        const sourceFile = path.join(source, file);
        const destinationFile = path.join(destination, file);

        // Skip .git and other system-like folders (you can add more if needed)
        if (file === '.git' || file === '.vscode' || file === 'node_modules') {
            console.log(`Skipping directory: ${file}`);
            return;
        }

        if (fs.statSync(sourceFile).isDirectory()) {
            // Recursively copy subdirectories
            copyDirectory(sourceFile, destinationFile);
        } else {
            // Copy file
            fs.copyFileSync(sourceFile, destinationFile);
        }
    });
}

// Function to minimize Lua file using luamin module
function minimizeLuaFile(filePath) {
    try {
        // Normalize the file path (important for Windows)
        const normalizedFilePath = path.normalize(filePath);

        // Read the original content of the Lua file
        const originalContent = fs.readFileSync(normalizedFilePath, 'utf8');

        // Minimize the Lua content using the luamin module
        const minimizedContent = luamin.minify(originalContent);

        // Overwrite the original file with minimized content
        fs.writeFileSync(normalizedFilePath, minimizedContent);
        console.log(`Minimized: ${normalizedFilePath}`);
    } catch (error) {
        console.error(`Error minimizing ${filePath}:`, error.message);
    }
}

// Function to recursively search for Lua files in a directory
function findLuaFiles(dir) {
    const files = fs.readdirSync(dir);

    files.forEach(file => {
        const fullPath = path.join(dir, file);

        if (fs.statSync(fullPath).isDirectory()) {
            // Recursively search for Lua files in subdirectories
            findLuaFiles(fullPath);
        } else if (path.extname(fullPath) === '.lua') {
            // Minimize the Lua file
            minimizeLuaFile(fullPath);
        }
    });
}

// 1. Get the current folder name and create the destination directory name
const currentFolder = path.basename(path.resolve(__dirname, '../')); // Get the current folder's name (one folder up)
const destinationFolder = `${currentFolder}_minimized`; // Append "_minimized" to the current folder name

// 2. Set up the source and destination directories
const sourceDir = path.resolve(__dirname, '../'); // One folder up from the script's current location
const destinationDir = path.resolve(__dirname, `../../${destinationFolder}`); // Two folders up for the minimized output

// 3. Delete the destination directory if it exists
console.log(`Checking if ${destinationDir} exists...`);
deleteDirectory(destinationDir);

// 4. Copy the entire folder structure to the new location, excluding unwanted directories
console.log(`Copying folder from ${sourceDir} to ${destinationDir}...`);
copyDirectory(sourceDir, destinationDir);

// 5. Start minimizing Lua files in the copied directory (destinationDir)
console.log(`Minimizing Lua files in ${destinationDir}...`);
findLuaFiles(destinationDir);
