const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    
    // Find the end of loadData
    const searchString = "  if (typeof renderPurchases === 'function') renderPurchases();";
    const replaceString = `  if (typeof renderPurchases === 'function') renderPurchases();
  if (typeof window.renderSettlements === 'function') window.renderSettlements();
  if (typeof window.renderSubcontracts === 'function') window.renderSubcontracts();
  if (typeof window.renderAbstracts === 'function') window.renderAbstracts();
  if (typeof window.renderVouchers === 'function') window.renderVouchers();
  if (typeof window.renderSalesReturns === 'function') window.renderSalesReturns();
  if (typeof window.renderPurchasesReturns === 'function') window.renderPurchasesReturns();
  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');
}
