const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    
    const searchString = `              let parent = currentAccounts.find(a => a.name === 'العهد' || a.name === 'عهد الموظفين') || currentAccounts.find(a => a.name.includes('عهد') && (!a.parent_id || a.type === 'رئيسي'));
              if (!parent) parent = currentAccounts.find(a => a.name.includes('صول') && !a.parent_id);`;
              
    const replaceString = `              let parent = currentAccounts.find(a => a.name === 'العهد' || a.name === 'عهد الموظفين' || (a.name.includes('عهد') && (!a.parent_id || a.type === 'رئيسي')));
              
              if (!parent) {
                  // Try to find Assets account to put the main custody account under
                  let assetsAcc = currentAccounts.find(a => a.name.includes('صول') && !a.parent_id);
                  parent = {
                      id: Date.now() - 1000,
                      name: 'عهد الموظفين',
                      code: assetsAcc ? assetsAcc.code + '99' : '199',
                      type: 'رئيسي',
                      parent_id: assetsAcc ? assetsAcc.id : null
                  };
                  await window.DB.add('accounts', parent);
                  currentAccounts.push(parent);
              }`;
              
    js = js.replace(searchString, replaceString);
    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Patched user custody parent creation');
}

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