const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    
    // Patch saveSettlement
    js = js.replace(/closeModal\('settlement-modal'\);\s*await loadData\(\);/g, 
        "closeModal('settlement-modal'); await loadData(); if (typeof renderSettlements === 'function') renderSettlements();");
    
    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Patched saveSettlement explicitly.');
}

if (fs.existsSync('subcontracts.js')) {
    let js = fs.readFileSync('subcontracts.js', 'utf8');
    
    // Patch saveSubcontract
    js = js.replace(/closeModal\('subcontract-modal'\);\s*await loadData\(\);/g, 
        "closeModal('subcontract-modal'); await loadData(); if (typeof renderSubcontracts === 'function') renderSubcontracts();");

    // Patch saveAbstract
    js = js.replace(/closeModal\('abstract-modal'\);\s*await loadData\(\);/g, 
        "closeModal('abstract-modal'); await loadData(); if (typeof renderAbstracts === 'function') renderAbstracts();");

    fs.writeFileSync('subcontracts.js', js, 'utf8');
    console.log('Patched subcontracts explicitly.');
}

if (fs.existsSync('vouchers_returns.js')) {
    let js = fs.readFileSync('vouchers_returns.js', 'utf8');
    
    // Patch saveVoucher
    js = js.replace(/closeModal\('voucher-modal'\);\s*if\s*\(window\.loadData\)\s*await window\.loadData\(\);/g, 
        "closeModal('voucher-modal'); if (window.loadData) await window.loadData(); if (typeof renderVouchers === 'function') renderVouchers();");

    fs.writeFileSync('vouchers_returns.js', js, 'utf8');
    console.log('Patched vouchers explicitly.');
}

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