const fs = require('fs');

const path = 'd:/برنامج مخازن/app_final.js';
const newModulePath = 'd:/برنامج مخازن/manufacture_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\.openManufactureModal\s*=/,
    /function renderManufactureTable\s*\(/
];

const eventListeners = [
    /document\.getElementById\('manufacture-items-tbody'\)\.addEventListener/,
    /document\.getElementById\('manufacture-product'\)\.addEventListener/,
    /document\.getElementById\('manufacture-qty'\)\.addEventListener/,
    /document\.getElementById\('manufacture-warehouse'\)\.addEventListener/,
    /document\.getElementById\('btn-save-manufacture'\)\.addEventListener/
];

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

let prependLogic = `
// Strip old listeners from app_final.js
['btn-save-manufacture', 'manufacture-items-tbody', 'manufacture-product', 'manufacture-qty', 'manufacture-warehouse'].forEach(id => {
    let oldElem = document.getElementById(id);
    if (oldElem) {
        let newElem = oldElem.cloneNode(true);
        oldElem.parentNode.replaceChild(newElem, oldElem);
    }
});\n\n`;

// Since we cloned 'manufacture-product' etc., `renderManufactureTable` relies on getting those elements.
// And since they are global ID queries, it's fine.

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