const fs = require('fs');
let code = fs.readFileSync('contractors_module.js', 'utf8');

const lastIdx = code.lastIndexOf('window.onClientAbstractProjectChange = function');

// Find the insertion point inside the LAST onClientAbstractProjectChange
const searchStr = "document.getElementById('client-abstract-client-name').value = proj.client || '';";
const insertionIdx = code.indexOf(searchStr, lastIdx);

if (insertionIdx !== -1) {
    const numberingLogic = `
    const projectAbstracts = (currentClientAbstracts || []).filter(a => String(a.project_id) === String(pId));
    let maxNum = 0;
    projectAbstracts.forEach(a => {
        let num = parseInt(String(a.abstract_number).replace(/[^\\d]/g, '')) || 0;
        if(num > maxNum) maxNum = num;
    });
    const nextId = maxNum + 1;
    if(document.getElementById('client-abstract-number')) document.getElementById('client-abstract-number').value = 'جاري ' + nextId;
`;
    code = code.substring(0, insertionIdx) + numberingLogic + '\n    ' + code.substring(insertionIdx);
    fs.writeFileSync('contractors_module.js', code, 'utf8');
    
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    indexHtml = indexHtml.replace(/v=20260610o/g, 'v=20260610p');
    fs.writeFileSync('index.html', indexHtml, 'utf8');
    console.log('Fixed duplicate function insertion');
} else {
    console.log('Insertion point not found');
}
