const fs = require('fs');

try {
    let indexHtml = fs.readFileSync('index.html', 'utf8');

    function removeRow(html, idToFind, functionName) {
        let index = html.indexOf(idToFind);
        if (index === -1) return html;

        let startStr = '<div class="flex-row">';
        let startIndex = html.lastIndexOf(startStr, index);
        
        let endStr = functionName + '()';
        let functionIndex = html.indexOf(endStr, index);
        if (functionIndex === -1) return html;

        let endDivIndex = html.indexOf('</div>', functionIndex);
        let endDivIndex2 = html.indexOf('</div>', endDivIndex + 6); // Need to close the inner div and the outer flex-row

        if (startIndex !== -1 && endDivIndex2 !== -1) {
            let chunk = html.substring(startIndex, endDivIndex2 + 6);
            return html.replace(chunk, '');
        }
        return html;
    }

    indexHtml = removeRow(indexHtml, 'sales-returns-item', 'addSalesReturnsLine');
    indexHtml = removeRow(indexHtml, 'purchases-returns-item', 'addPurchasesReturnsLine');

    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + timestamp);
    indexHtml = indexHtml.replace(/vouchers_returns\.js\?v=\d+/g, 'vouchers_returns.js?v=' + timestamp);

    fs.writeFileSync('index.html', indexHtml, 'utf8');

    console.log('Safe patch applied successfully!');
} catch (e) {
    console.error('Error applying safe patch:', e);
}
