const fs = require('fs');

try {
    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');

    // The bad block looks like this:
    /*
      if (it.item_id === parseInt(itemId)) {
        if (inv.type === 'sales_return' && inv.status === 'posted') {
           records.push({ date: inv.date, inv: inv, type: '...', loc: inv.from_warehouse_name || '', whId: inv.from_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price });
           return;
        }
        if (inv.type === 'purchases_return' && inv.status === 'posted') {
           records.push({ date: inv.date, inv: inv, type: '...', loc: inv.to_warehouse_name || '', whId: inv.to_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price });
           return;
        }
      }
    */
    
    // We will use a regex that matches this exact structure, ignoring the Arabic characters.
    const badRegex = /[ \t]*if\s*\(\s*it\.item_id\s*===\s*parseInt\(itemId\)\s*\)\s*\{\s*if\s*\(\s*inv\.type\s*===\s*'sales_return'\s*&&\s*inv\.status\s*===\s*'posted'\s*\)\s*\{\s*records\.push\(\{[\s\S]*?qtyIn:\s*it\.qty,\s*qtyOut:\s*0,\s*price:\s*it\.price\s*\}\);\s*return;\s*\}\s*if\s*\(\s*inv\.type\s*===\s*'purchases_return'\s*&&\s*inv\.status\s*===\s*'posted'\s*\)\s*\{\s*records\.push\(\{[\s\S]*?qtyIn:\s*0,\s*qtyOut:\s*it\.qty,\s*price:\s*it\.price\s*\}\);\s*return;\s*\}\s*\}/g;

    const matches = appFinalJs.match(badRegex);
    console.log("Found matches to remove:", matches ? matches.length : 0);
    
    if (matches && matches.length > 0) {
        appFinalJs = appFinalJs.replace(badRegex, '');
        console.log("Removed bad blocks.");
        
        // Now, we need to inject the logic into generateInventoryReport.
        // We look for:
        // if (it.item_id === parseInt(itemId)) {
        //   if (inv.type === 'in' || inv.type === 'opening_balance') {
        
        const targetRegex = /(if\s*\(\s*it\.item_id\s*===\s*parseInt\(itemId\)\s*\)\s*\{\s*)(if\s*\(\s*inv\.type\s*===\s*'in'\s*\|\|\s*inv\.type\s*===\s*'opening_balance'\s*\)\s*\{)/;
        
        if (targetRegex.test(appFinalJs)) {
            const inject = `$1
        if (inv.type === 'sales_return' && inv.status === 'posted') {
           records.push({ date: inv.date, inv: inv, type: 'مرتجع مبيعات', loc: inv.from_warehouse_name || '', whId: inv.from_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price });
        } else if (inv.type === 'purchases_return' && inv.status === 'posted') {
           records.push({ date: inv.date, inv: inv, type: 'مرتجع مشتريات', loc: inv.to_warehouse_name || '', whId: inv.to_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price });
        } else $2`;
            
            appFinalJs = appFinalJs.replace(targetRegex, inject);
            console.log("Injected logic correctly into generateInventoryReport.");
        } else {
            console.log("Could not find generateInventoryReport target to inject.");
        }
        
        fs.writeFileSync('app_final.js', appFinalJs, 'utf8');
        
        let indexHtml = fs.readFileSync('index.html', 'utf8');
        indexHtml = indexHtml.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + Date.now());
        fs.writeFileSync('index.html', indexHtml, 'utf8');
        console.log("Updated app_final.js and busted cache.");
    }

} catch (e) {
    console.error(e);
}
