const fs = require('fs');

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

    // Replace the old resolveSystemAccount
    const newResolver = `
window.resolveSystemAccount = async function(accountName, parentKeywords, accountType, alternateNames) {
    let acc = currentAccounts.find(a => a.name.trim() === accountName.trim());
    if (acc) return acc;
    
    if (alternateNames && alternateNames.length > 0) {
        acc = currentAccounts.find(a => alternateNames.includes(a.name.trim()));
        if (acc) return acc;
    }

    let parentAcc = null;
    if (parentKeywords && parentKeywords.length > 0) {
        parentAcc = currentAccounts.find(a => parentKeywords.some(k => a.name === k || a.name.includes(k)));
    }

    try {
        const newAcc = {
            code: Date.now().toString().slice(-6),
            name: accountName,
            type: accountType || (parentAcc ? parentAcc.type : 'revenues'),
            parent_id: parentAcc ? parentAcc.id : null,
            balance: 0
        };
        const addedId = await window.DB.add('accounts', newAcc);
        newAcc.id = addedId;
        currentAccounts.push(newAcc);
        if (window.loadData) window.loadData(false);
        return newAcc;
    } catch (e) {
        console.error("Failed to auto-create system account", e);
        return parentAcc;
    }
};`;

    appFinalJs = appFinalJs.replace(/window\.resolveSystemAccount = async function[\s\S]*?catch \(e\) \{\s*console\.error\("Failed to auto-create system account", e\);\s*return null;\s*\}\s*\};/g, newResolver);

    // Update generateSalesJournal
    appFinalJs = appFinalJs.replace(
        /const salesAcc = await window\.resolveSystemAccount\('إيرادات المبيعات', 'revenues', \['إيرادات', 'مبيعات', 'ايراد'\]\);/g,
        `const salesAcc = await window.resolveSystemAccount('إيرادات المبيعات', ['الإيرادات', 'إيرادات', 'ايرادات'], 'revenues', ['المبيعات', 'مبيعات', 'ايرادات مبيعات']);`
    );

    // Update generatePurchasesJournal
    appFinalJs = appFinalJs.replace(
        /const invAcc = await window\.resolveSystemAccount\('مخزون البضاعة', 'assets', \['مخزون', 'بضاعة', 'مخازن'\]\);/g,
        `const invAcc = await window.resolveSystemAccount('مخزون البضاعة', ['الأصول', 'أصول', 'اصول متداولة'], 'assets', ['المخزون', 'مخزون', 'بضاعة']);`
    );

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');

    // Bust cache
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + timestamp);
    fs.writeFileSync('index.html', indexHtml, 'utf8');

    console.log('System Account resolver improved successfully.');
} catch (e) {
    console.error('Error patching:', e);
}
