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

// remove global numbering from openClientAbstractModal
const regex = /let maxNum = 0;\s*currentClientAbstracts\.forEach[\s\S]*?value = 'جاري ' \+ nextId;/s;
code = code.replace(regex, "if(document.getElementById('client-abstract-number')) document.getElementById('client-abstract-number').value = '';");

// add project-specific numbering in onClientAbstractProjectChange
const idx = code.indexOf("document.getElementById('client-abstract-client-name').value = proj.client || '';");
if (idx !== -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, idx) + numberingLogic + '\n    ' + code.substring(idx);
}

fs.writeFileSync('contractors_module.js', code, 'utf8');

let indexHtml = fs.readFileSync('index.html', 'utf8');
indexHtml = indexHtml.replace(/v=20260610n/g, 'v=20260610o');
fs.writeFileSync('index.html', indexHtml, 'utf8');

console.log('Fixed project-specific numbering');
