const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    
    // Find the end of loadData exactly
    const searchString = `  if (typeof renderPurchases === 'function') renderPurchases();
    if (typeof renderVouchers === 'function') renderVouchers();
    if (typeof renderSalesReturns === 'function') renderSalesReturns();
    if (typeof renderPurchasesReturns === 'function') renderPurchasesReturns();`;
    
    const replaceString = `  if (typeof renderPurchases === 'function') renderPurchases();
    if (typeof renderVouchers === 'function') renderVouchers();
    if (typeof renderSalesReturns === 'function') renderSalesReturns();
    if (typeof renderPurchasesReturns === 'function') renderPurchasesReturns();
    if (typeof window.renderSettlements === 'function') window.renderSettlements();
    if (typeof window.renderSubcontracts === 'function') window.renderSubcontracts();
    if (typeof window.renderAbstracts === 'function') window.renderAbstracts();
    if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();`;

    if (js.includes(searchString) && !js.includes('window.renderSettlements()')) {
        js = js.replace(searchString, replaceString);
        fs.writeFileSync('app_final.js', js, 'utf8');
        console.log('Added missing render functions to loadData.');
    } else {
        console.log('Already patched or search string not found.');
    }
}

// Cache buster
if (fs.existsSync('index.html')) {
    let html = fs.readFileSync('index.html', 'utf8');
    html = html.replace(/v=\d+/g, 'v=' + Date.now());
    fs.writeFileSync('index.html', html, 'utf8');
}
