const fs = require('fs');

const appFinalPath = 'd:/برنامج مخازن/app_final.js';
const storePath = 'd:/برنامج مخازن/store_module.js';
const contractorsPath = 'd:/برنامج مخازن/contractors_module.js';

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

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;
}

// 1. Store Module
const storePatterns = [
    /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\.renderStorekeepersDashboard\s*=/
];

const storeEventListeners = [
    /document\.getElementById\('btn-confirm-receipt'\)\.addEventListener/,
    /document\.getElementById\('btn-execute-decision'\)\.addEventListener/,
    /document\.getElementById\('btn-approve-storekeeper'\)\?\.addEventListener/
];

let storeLines = [];
for (let p of storePatterns) storeLines.push(...extractBlock(p));
for (let p of storeEventListeners) storeLines.push(...extractBlock(p));

let storePrepend = `
// 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 (storeLines.length > 0) {
    fs.writeFileSync(storePath, storePrepend + storeLines.join('\n'), 'utf8');
    console.log('Created store_module.js (' + storeLines.length + ' lines)');
}

// 2. Contractors Module
const contractorsPatterns = [
    /window\.renderAbstractComments\s*=/,
    /window\.addAbstractComment\s*=/,
    /window\.renderClientAbstracts\s*=/,
    /window\.openClientAbstractModal\s*=/,
    /window\.deleteClientAbstract\s*=/,
    /window\.approveClientAbstract\s*=/,
    /window\.payClientAbstract\s*=/
];

let contractorsLines = [];
for (let p of contractorsPatterns) contractorsLines.push(...extractBlock(p));

if (contractorsLines.length > 0) {
    fs.writeFileSync(contractorsPath, contractorsLines.join('\n'), 'utf8');
    console.log('Created contractors_module.js (' + contractorsLines.length + ' lines)');
}
