const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    
    // Find the end of window.loadData function
    const lines = js.split('\n');
    let inLoadData = false;
    let braceCount = 0;
    
    for (let i = 0; i < lines.length; i++) {
        if (lines[i].includes('window.loadData = async function(')) {
            inLoadData = true;
        }
        
        if (inLoadData) {
            if (lines[i].includes('{')) braceCount += (lines[i].match(/\{/g) || []).length;
            if (lines[i].includes('}')) braceCount -= (lines[i].match(/\}/g) || []).length;
            
            if (braceCount === 0 && lines[i].includes('}')) {
                // We found the end of the loadData function! Insert our code right before this line.
                const inject = `
    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();
`;
                lines.splice(i, 0, inject);
                break;
            }
        }
    }
    
    fs.writeFileSync('app_final.js', lines.join('\n'), 'utf8');
    console.log('Successfully injected missing render functions into loadData!');
}

// 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');
}
