const path = require('path');
const WorkerPool = require('./WorkerPool');
const config = {
    workerScript: path.join(__dirname, 'recv_change_config_worker.js'),
    numWorkers: process.env.NUM_WORKERS || 4,
    maxRetries: 3,
    timeout: 5000
};
class ConfigTaskManager {
    constructor() {
        this.workerPool = new WorkerPool(
            config.workerScript,
            config.numWorkers
        );
        this.setupCleanup();
    }

    setupCleanup() {
        process.on('SIGINT', async () => {
            await this.shutdown();
            process.exit(0);
        });
    }

    async shutdown() {
        console.log('Shutting down worker pool...');
        await this.workerPool.terminate();
    }

    async processTask(data) {
        try {
            return await executeWithRetry(this.workerPool, data);
        } catch (error) {
            console.error('Task processing failed:', error);
            throw error;
        }
    }

    async processBatch(items) {
        try {
            return await processBatch(this.workerPool, items);
        } catch (error) {
            console.error('Batch processing failed:', error);
            throw error;
        }
    }
}

// 2. 带重试机制的执行器
async function executeWithRetry(workerPool, data, retries = config.maxRetries) {
    try {
        return await Promise.race([
            workerPool.execute(data),
            new Promise((_, reject) => 
                setTimeout(() => reject(new Error('Task timeout')), config.timeout)
            )
        ]);
    } catch (error) {
        if (retries > 0) {
            console.warn(`Retrying task, ${retries} attempts remaining`);
            return executeWithRetry(workerPool, data, retries - 1);
        }
        throw error;
    }
}

// 3. 批量处理示例
async function processBatch(workerPool, items, batchSize = 100) {
    const results = [];
    for (let i = 0; i < items.length; i += batchSize) {
        const batch = items.slice(i, i + batchSize);
        const batchResults = await Promise.all(
            batch.map(item => executeWithRetry(workerPool, item))
        );
        results.push(...batchResults);
    }
    return results;
}
module.exports = ConfigTaskManager;
// 使用示例
// async function main() {
//     const taskManager = new ConfigTaskManager();

//     try {
//         // 单个任务
//         const result = await taskManager.processTask({ type: 'single', data: 'test' });
//         console.log('Single task result:', result);

//         // 批量任务
//         const batchItems = Array(1000).fill().map((_, i) => ({
//             type: 'batch',
//             data: `item-${i}`
//         }));
//         const results = await taskManager.processBatch(batchItems);
//         console.log('Batch processing completed:', results.length);

//     } catch (error) {
//         console.error('Main process error:', error);
//     } finally {
//         await taskManager.shutdown();
//     }
// }

// main().catch(console.error);