const fs = require('fs');

const path = 'd:/برنامج مخازن/app_final.js';
const newModulePath = 'd:/برنامج مخازن/projects_module.js';

let content = fs.readFileSync(path, 'utf8');
const lines = content.split(/\r?\n/);

let extractedLines = [];

function extractBlock(startRegex) {
    let block = [];
    let isInside = false;
    let bCount = 0;
    for (let i = 0; i < lines.length; i++) {
        if (!isInside && startRegex.test(lines[i])) {
            isInside = true;
            bCount = 0;
        }
        if (isInside) {
            block.push(lines[i]);
            if (lines[i].includes('{')) bCount += (lines[i].match(/{/g) || []).length;
            if (lines[i].includes('}')) bCount -= (lines[i].match(/}/g) || []).length;
            
            if (bCount === 0) {
                isInside = false;
                block.push('');
            }
        }
    }
    return block;
}

const patterns = [
    /window\.addProjectBoqRow\s*=/,
    /window\.removeProjectBoqRow\s*=/,
    /window\.updateProjectBoqRow\s*=/,
    /window\.removeProjectAttachment\s*=/,
    /window\.openProjectModal\s*=/,
    /window\.deleteProject\s*=/,
    /window\.openProjectDetails\s*=/
];

const savePatterns = [
    /document\.getElementById\('btn-save-project'\)\.addEventListener/
];

for (let p of patterns) extractedLines.push(...extractBlock(p));
for (let p of savePatterns) extractedLines.push(...extractBlock(p));

let prependLogic = `
// Strip old listeners from app_final.js
['btn-save-project'].forEach(id => {
    let oldBtn = document.getElementById(id);
    if (oldBtn) {
        let newBtn = oldBtn.cloneNode(true);
        oldBtn.parentNode.replaceChild(newBtn, oldBtn);
    }
});\n\n`;

if (extractedLines.length > 0) {
    fs.writeFileSync(newModulePath, prependLogic + extractedLines.join('\n'), 'utf8');
    console.log('Projects module extracted to ' + newModulePath);
    console.log('Total extracted lines: ' + extractedLines.length);
} else {
    console.log('Nothing extracted.');
}
