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

// 1. Add fetching of client abstracts to loadData
if (!js.includes("currentClientAbstracts = await window.DB.getAll('client_abstracts')")) {
    js = js.replace(/(currentAbstracts = await window\.DB\.getAll\('subcontract_abstracts'\);)/, "$1\n  currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];");
}

// 2. Ensure currentClientAbstracts is also loaded in renderClientAbstracts just in case
if (!js.includes("currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];", js.indexOf('window.renderClientAbstracts = function'))) {
    js = js.replace(/window\.renderClientAbstracts = (async )?function\(\) \{/, "window.renderClientAbstracts = async function() {\n  currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];");
}

// 3. Make sure to render it after save
if (!js.includes("window.renderClientAbstracts()", js.indexOf('btnSaveClientAbstract.onclick'))) {
    js = js.replace(/await loadData\(\);\s*alert\('تم حفظ المستخلص بنجاح'\);/, "await loadData();\n            if(typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();\n            alert('تم حفظ المستخلص بنجاح');");
}

fs.writeFileSync('app_final.js', js, 'utf8');
console.log('Fixed client abstracts save and render logic!');
