const fs = require('fs');
let app = fs.readFileSync('app_final.js', 'utf8');

const injection = `
  // --- AUTO-CREATE ESSENTIAL ACCOUNTS ---
  const essentialAccounts = [
    { name: 'حسابات العملاء', keywords: ['عميل', 'عملاء'], parentKeywords: ['صول'], type: 'فرعي' },
    { name: 'حسابات الموردين', keywords: ['مورد'], parentKeywords: ['خصوم', 'التزام'], type: 'فرعي' },
    { name: 'المخزون', keywords: ['مخزون'], parentKeywords: ['صول'], type: 'رئيسي' },
    { name: 'تكلفة المبيعات', keywords: ['تكلفة المبيعات'], parentKeywords: ['مصروف'], type: 'رئيسي' },
    { name: 'المبيعات', keywords: ['مبيعات', 'إيرادات مبيعات'], parentKeywords: ['إيراد'], type: 'رئيسي' },
    { name: 'ضريبة القيمة المضافة', keywords: ['ضريب', 'قيمة مضافة'], parentKeywords: ['خصوم', 'التزام'], type: 'فرعي' },
    { name: 'الخصم المسموح به', keywords: ['مسموح به'], parentKeywords: ['مصروف'], type: 'فرعي' },
    { name: 'الخصم المكتسب', keywords: ['مكتسب'], parentKeywords: ['إيراد'], type: 'فرعي' }
  ];

  for (let ess of essentialAccounts) {
    if (!currentAccounts.some(a => ess.keywords.some(k => a.name.includes(k)))) {
      const parent = currentAccounts.find(a => ess.parentKeywords.some(k => a.name.includes(k)));
      const newAcc = {
        id: Date.now() + Math.floor(Math.random() * 10000),
        code: '',
        name: ess.name,
        type: ess.type,
        parent_id: parent ? parent.id : null,
        op_debit: 0,
        op_credit: 0
      };
      await window.DB.add('accounts', newAcc);
      currentAccounts.push(newAcc);
      // Wait a tiny bit to avoid ID collision
      await new Promise(r => setTimeout(r, 2));
    }
  }
  // -------------------------------------
`;

// Insert after: currentAccounts = await window.DB.getAll('accounts'); (around line 1678)
// Be careful to replace only once
if (!app.includes('AUTO-CREATE ESSENTIAL ACCOUNTS')) {
  app = app.replace(
    /currentAccounts = await window\.DB\.getAll\('accounts'\);\s*\}/,
    `currentAccounts = await window.DB.getAll('accounts');\n  }\n${injection}`
  );
  
  // Actually the match might fail if formatting is different. 
  // Another hook: right before currentJournals = await window.DB.getAll('journal_entries') || [];
  app = app.replace(
    /currentJournals = await window\.DB\.getAll\('journal_entries'\)/,
    `${injection}\n  currentJournals = await window.DB.getAll('journal_entries')`
  );
  
  fs.writeFileSync('app_final.js', app, 'utf8');
}

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

console.log('Auto-create logic injected!');
