const fs = require('fs');

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

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

let startIndex = -1;
let endIndex = -1;

for (let i = 0; i < lines.length; i++) {
    if (lines[i].includes('window.resolveSystemAccount = async function')) {
        if (startIndex === -1) startIndex = i;
    }
    if (lines[i].includes('window.deleteJournal = async function')) {
        endIndex = i;
    }
}

if (startIndex !== -1 && endIndex !== -1) {
    // Find the end of deleteJournal function
    let bracesCount = 0;
    let foundStart = false;
    let finalIndex = endIndex;
    
    for (let i = endIndex; i < lines.length; i++) {
        if (lines[i].includes('{')) {
            bracesCount += (lines[i].match(/{/g) || []).length;
            foundStart = true;
        }
        if (lines[i].includes('}')) {
            bracesCount -= (lines[i].match(/}/g) || []).length;
        }
        
        if (foundStart && bracesCount === 0) {
            finalIndex = i;
            break;
        }
    }
    
    // Extract the module
    const moduleLines = lines.slice(startIndex, finalIndex + 1);
    fs.writeFileSync(newModulePath, moduleLines.join('\n'), 'utf8');
    
    console.log('Accounting module extracted to ' + newModulePath);
    console.log('Extracted lines: ' + (finalIndex - startIndex + 1));
} else {
    console.log('Could not find start or end index.');
}
