const fs = require('fs');

try {
    let js = fs.readFileSync('app_final.js', 'utf8');

    // Make UI updates safe in renderSalesLines
    js = js.replace(/document\.getElementById\('sales-subtotal'\)\.innerText =/g, "if(document.getElementById('sales-subtotal')) document.getElementById('sales-subtotal').innerText =");
    js = js.replace(/document\.getElementById\('sales-total-discount'\)\.innerText =/g, "if(document.getElementById('sales-total-discount')) document.getElementById('sales-total-discount').innerText =");
    js = js.replace(/document\.getElementById\('sales-net-total'\)\.innerText =/g, "if(document.getElementById('sales-net-total')) document.getElementById('sales-net-total').innerText =");
    js = js.replace(/document\.getElementById\('sales-paid-total'\)\.innerText =/g, "if(document.getElementById('sales-paid-total')) document.getElementById('sales-paid-total').innerText =");
    js = js.replace(/document\.getElementById\('sales-remaining'\)\.innerText =/g, "if(document.getElementById('sales-remaining')) document.getElementById('sales-remaining').innerText =");

    // Make UI updates safe in renderPurchasesLines
    js = js.replace(/document\.getElementById\('purchases-subtotal'\)\.innerText =/g, "if(document.getElementById('purchases-subtotal')) document.getElementById('purchases-subtotal').innerText =");
    js = js.replace(/document\.getElementById\('purchases-total-discount'\)\.innerText =/g, "if(document.getElementById('purchases-total-discount')) document.getElementById('purchases-total-discount').innerText =");
    js = js.replace(/document\.getElementById\('purchases-net-total'\)\.innerText =/g, "if(document.getElementById('purchases-net-total')) document.getElementById('purchases-net-total').innerText =");
    js = js.replace(/document\.getElementById\('purchases-paid-total'\)\.innerText =/g, "if(document.getElementById('purchases-paid-total')) document.getElementById('purchases-paid-total').innerText =");
    js = js.replace(/document\.getElementById\('purchases-remaining'\)\.innerText =/g, "if(document.getElementById('purchases-remaining')) document.getElementById('purchases-remaining').innerText =");

    fs.writeFileSync('app_final.js', js, 'utf8');
    
    // Also bust cache in index.html
    let html = fs.readFileSync('index.html', 'utf8');
    html = html.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + Date.now());
    fs.writeFileSync('index.html', html, 'utf8');
    
    console.log("Patched render functions safely in app_final.js!");
} catch (e) {
    console.error("Error:", e);
}
