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

function mockToggleExtension(iniContent, extName, enabled) {
    const lines = iniContent.split(/\r?\n/);
    let found = false;
    const newLines = lines.map(line => {
        const trimmedLine = line.trim();
        const pattern = new RegExp(`^\\s*;?\\s*extension\\s*=\\s*(?:php_)?${extName}(?:\\.dll)?\\s*$`, 'i');

        if (pattern.test(trimmedLine)) {
            found = true;
            return enabled ? `extension=php_${extName}.dll` : `;extension=php_${extName}.dll`;
        }
        return line;
    });

    if (!found && enabled) {
        const extSectionIndex = newLines.findIndex(l => l.trim().toLowerCase() === '; dynamic extensions');
        if (extSectionIndex !== -1) {
            newLines.splice(extSectionIndex + 1, 0, `extension=php_${extName}.dll`);
        } else {
            newLines.push(`extension=php_${extName}.dll`);
        }
    }

    let extDirSet = false;
    const finalLines = newLines.map(line => {
        if (line.trim().startsWith('extension_dir') || line.trim().startsWith(';extension_dir')) {
            extDirSet = true;
            return 'extension_dir = "ext"';
        }
        return line;
    });

    if (!extDirSet) {
        finalLines.unshift('extension_dir = "ext"');
    }

    return finalLines.join('\n');
}

// Test cases
const testIni = `
[PHP]
; extension_dir = "./"
; Dynamic Extensions
;extension=php_bz2.dll
extension=php_curl.dll
;extension=php_mysql.dll
`;

console.log("--- Initial ---");
console.log(testIni);

console.log("\n--- Enable mysql ---");
let updated = mockToggleExtension(testIni, 'mysql', true);
console.log(updated);
if (updated.includes('extension=php_mysql.dll') && !updated.includes(';extension=php_mysql.dll')) {
    console.log("SUCCESS: mysql enabled");
} else {
    console.log("FAIL: mysql not enabled properly");
}

console.log("\n--- Disable curl ---");
updated = mockToggleExtension(updated, 'curl', false);
console.log(updated);
if (updated.includes(';extension=php_curl.dll')) {
    console.log("SUCCESS: curl disabled");
} else {
    console.log("FAIL: curl not disabled properly");
}

console.log("\n--- Check extension_dir ---");
if (updated.includes('extension_dir = "ext"')) {
    console.log("SUCCESS: extension_dir set correctly");
} else {
    console.log("FAIL: extension_dir not set properly");
}

console.log("\n--- Add new extension (mbstring) ---");
updated = mockToggleExtension(updated, 'mbstring', true);
console.log(updated);
if (updated.includes('extension=php_mbstring.dll')) {
    console.log("SUCCESS: mbstring added");
} else {
    console.log("FAIL: mbstring not added");
}
