const fs = require('fs');

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

    // Inject the resolver function at the top
    if (!appFinalJs.includes('window.resolveContactAccount')) {
        appFinalJs = `
window.resolveContactAccount = async function(contactId, type) {
    const contact = currentContacts.find(c => c.id == contactId);
    if (!contact) return null;
    
    // 1. Exact match
    let acc = currentAccounts.find(a => a.name.trim() === contact.name.trim());
    if (acc) return acc;
    
    // 2. Fallback to generic account if the user has it
    let genericAcc;
    if (type === 'sales' || type === 'receipt') {
        genericAcc = currentAccounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل'));
    } else {
        genericAcc = currentAccounts.find(a => a.name.includes('مورد'));
    }
    
    // 3. Auto-create account!
    try {
        const newAcc = {
            code: Date.now().toString().slice(-6),
            name: contact.name,
            type: (type === 'sales' || type === 'receipt') ? 'assets' : 'liabilities',
            parent_id: genericAcc ? genericAcc.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 contact account", e);
        return genericAcc;
    }
};\n` + appFinalJs;
    }

    // Patch generateSalesJournal
    appFinalJs = appFinalJs.replace(
        /const clientAcc = currentAccounts\.find\(a => a\.name\.includes\('عملاء'\) \|\| a\.name\.includes\('عميل'\)\);[^\n]*\n/g,
        `const clientAcc = await window.resolveContactAccount(invoice.contact_id, 'sales');\n  `
    );

    // Patch generatePurchasesJournal
    appFinalJs = appFinalJs.replace(
        /const supplierAcc = currentAccounts\.find\(a => a\.name\.includes\('مورد'\)\);/g,
        `const supplierAcc = await window.resolveContactAccount(invoice.contact_id, 'purchases');`
    );

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

    // Patch vouchers_returns.js
    let vouchersJs = fs.readFileSync('vouchers_returns.js', 'utf8');
    vouchersJs = vouchersJs.replace(
        /let cAcc;\s*if \(voucher\.type === 'receipt'\) \{\s*cAcc = currentAccounts\.find\(a => a\.name\.includes\('عملاء'\) \|\| a\.name\.includes\('عميل'\)\);\s*\} else \{\s*cAcc = currentAccounts\.find\(a => a\.name\.includes\('مورد'\)\);\s*\}/g,
        `let cAcc = await window.resolveContactAccount(voucher.contact_id, voucher.type);`
    );
    fs.writeFileSync('vouchers_returns.js', vouchersJs, '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);
    indexHtml = indexHtml.replace(/vouchers_returns\.js\?v=\d+/g, 'vouchers_returns.js?v=' + timestamp);
    fs.writeFileSync('index.html', indexHtml, 'utf8');

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