const fs = require('fs');
const { execSync } = require('child_process');

// 1. Copy app.js to app_final.js
let js = fs.readFileSync('app.js', 'utf8');

// 2. Inject currentClientAbstracts
if (!js.includes('let currentClientAbstracts = [];')) {
    js = js.replace('let allNotifications = [];', 'let allNotifications = [];\nlet currentClientAbstracts = [];');
}

// 3. Inject loadData logic
if (!js.includes("currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];")) {
    const loadTarget = "allNotifications = await window.DB.getAll('notifications') || [];";
    js = js.replace(loadTarget, loadTarget + "\n  currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];");
}

// 4. Inject menu logic
if (!js.includes("if(e.target.dataset.view === 'client-abstracts')")) {
    const initTarget = "if(e.target.dataset.view === 'project-reports') renderProjectReports();";
    js = js.replace(initTarget, initTarget + "\n    if(e.target.dataset.view === 'client-abstracts' && typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();");
}

// 5. Append updatedLogic from update_app_final2.js
const update2 = fs.readFileSync('update_app_final2.js', 'utf8');
const startIdx = update2.indexOf('window.renderClientAbstracts = function() {');
const endIdx = update2.indexOf('// Replace everything');
if(startIdx !== -1 && endIdx !== -1) {
    const updatedLogic = update2.substring(startIdx, endIdx);
    js += '\n' + updatedLogic;
} else {
    console.error('Could not find updatedLogic in update_app_final2.js');
}

// 6. Append delete/approve/pay functions
js += `
window.deleteClientAbstract = async function(id) {
    if(confirm('هل أنت متأكد من حذف هذا المستخلص؟')) {
        await window.DB.remove('client_abstracts', id);
        if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
    }
};

window.approveClientAbstract = async function(id) {
    if(confirm('هل أنت متأكد من اعتماد هذا المستخلص؟')) {
        const ab = currentClientAbstracts.find(a => a.id === id);
        if(ab) {
            ab.status = 'approved';
            await window.DB.update('client_abstracts', ab);
            if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
            alert('تم الاعتماد بنجاح.');
        }
    }
};

window.payClientAbstract = function(id) {
    const ab = currentClientAbstracts.find(a => a.id === id);
    if(ab) {
        document.getElementById('receipt-linked-invoice').value = 'cab-' + ab.id;
        document.getElementById('receipt-amount').value = ab.net_value;
        const proj = currentProjects.find(p => p.id === parseInt(ab.project_id));
        if (proj && proj.client_name) {
            document.getElementById('receipt-party-name').value = proj.client_name;
        } else {
            document.getElementById('receipt-party-name').value = ab.client_name || '';
        }
        showModal('receipt-modal');
    }
};
`;

// Save the reconstructed app_final.js
fs.writeFileSync('app_final.js', js, 'utf8');
console.log('Reconstructed base app_final.js!');

const scriptsToRun = [
    'update_abstracts_features.js',
    'fix_save.js',
    'fix_save_render.js',
    'fix_numbering.js',
    'update_client_ab_table.js'
];

for (const script of scriptsToRun) {
    if (fs.existsSync(script)) {
        console.log(`Running ${script}...`);
        try {
            execSync(`node ${script}`, { stdio: 'inherit' });
        } catch(e) {
            console.error(`Error running ${script}`);
        }
    } else {
        console.log(`Skipping ${script} (not found)`);
    }
}
console.log('Master Reconstruction Complete! app_final.js length:', fs.readFileSync('app_final.js').length);
