const fs = require('fs');

const path = 'd:/برنامج مخازن/app_final.js';
const newModulePath = 'd:/برنامج مخازن/store_contractors_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\.openReceiveModal\s*=/,
    /window\.openDecisionModal\s*=/,
    /window\.viewDetails\s*=/,
    /window\.printInvoice\s*=/,
    /window\.markNotifAsRead\s*=/,
    /window\.openStorekeeperReviewModal\s*=/,
    /window\.renderItemCard\s*=/,
    /window\.populateDropdowns\s*=/,
    /window\.updateAvailableBalance\s*=/,
    /window\.renderComments\s*=/,
    /window\.addComment\s*=/,
    /window\.handleMentionInput\s*=/,
    /window\.insertMention\s*=/,
    /window\.sendInvoiceToStore\s*=/,
    /window\.renderAbstractComments\s*=/,
    /window\.addAbstractComment\s*=/,
    /window\.renderClientAbstracts\s*=/,
    /window\.openClientAbstractModal\s*=/,
    /window\.deleteClientAbstract\s*=/,
    /window\.approveClientAbstract\s*=/,
    /window\.payClientAbstract\s*=/,
    /window\.renderStorekeepersDashboard\s*=/
];

const eventListeners = [
    /document\.getElementById\('btn-confirm-receipt'\)\.addEventListener/,
    /document\.getElementById\('btn-execute-decision'\)\.addEventListener/,
    /document\.getElementById\('btn-approve-storekeeper'\)\?\.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-confirm-receipt', 'btn-execute-decision', 'btn-approve-storekeeper'].forEach(id => {
    let oldElem = document.getElementById(id);
    if (oldElem) {
        let newElem = oldElem.cloneNode(true);
        oldElem.parentNode.replaceChild(newElem, oldElem);
    }
});\n\n`;

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