const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    
    // The buggy line:
    // let parent = currentAccounts.find(a => a.name === 'العهد' || a.name === 'عهد الموظفين') || currentAccounts.find(a => a.name.includes('عهد') && a.type === 'رئيسي');
    // if (!parent) parent = currentAccounts.find(a => a.name.includes('صول') && a.type === 'رئيسي');
    
    const searchString = "if (!parent) parent = currentAccounts.find(a => a.name.includes('صول') && a.type === 'رئيسي');";
    const replaceString = "if (!parent) parent = currentAccounts.find(a => a.name.includes('صول') && !a.parent_id);";

    js = js.replace(searchString, replaceString);
    
    const searchString2 = "currentAccounts.find(a => a.name.includes('عهد') && a.type === 'رئيسي')";
    const replaceString2 = "currentAccounts.find(a => a.name.includes('عهد') && (!a.parent_id || a.type === 'رئيسي'))";
    
    js = js.replace(searchString2, replaceString2);

    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Patched custody parent assignment in app_final.js');
}

// Cache buster
let html = fs.readFileSync('index.html', 'utf8');
html = html.replace(/v=\d+/g, 'v=' + Date.now());
fs.writeFileSync('index.html', html, 'utf8');
