import { EventEmitter } from 'events';
import { v4 as uuidv4 } from 'uuid';
import * as fs from 'fs/promises';
import * as path from 'path';
export class TaskManager extends EventEmitter {
    constructor() {
        super();
        this.tasks = new Map();
        this.dataDir = path.join(process.cwd(), 'server', 'data');
        this.ensureDataDir();
    }
    async ensureDataDir() {
        try {
            await fs.mkdir(this.dataDir, { recursive: true });
        }
        catch (error) {
            console.error('创建数据目录失败:', error);
        }
    }
    createTask(type, data) {
        const id = uuidv4();
        const task = {
            id,
            type,
            status: 'pending',
            progress: 0,
            message: '任务已创建',
            createdAt: new Date(),
            updatedAt: new Date(),
            data
        };
        this.tasks.set(id, task);
        this.emit('taskCreated', task);
        return id;
    }
    updateTask(id, updates) {
        const task = this.tasks.get(id);
        if (!task)
            return;
        Object.assign(task, updates, { updatedAt: new Date() });
        this.tasks.set(id, task);
        this.emit('taskUpdated', task);
    }
    getTask(id) {
        return this.tasks.get(id);
    }
    getAllTasks() {
        return Array.from(this.tasks.values());
    }
    getActiveTasks() {
        return Array.from(this.tasks.values()).filter(task => task.status === 'pending' || task.status === 'running');
    }
    deleteTask(id) {
        const task = this.tasks.get(id);
        if (task) {
            this.tasks.delete(id);
            this.emit('taskDeleted', task);
        }
    }
    cleanupTasks() {
        const allTasks = Array.from(this.tasks.values());
        const completedTasks = allTasks
            .filter(task => task.status === 'completed' || task.status === 'failed')
            .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
        if (completedTasks.length > 100) {
            const tasksToDelete = completedTasks.slice(100);
            tasksToDelete.forEach(task => this.deleteTask(task.id));
        }
    }
}
export const taskManager = new TaskManager();
setInterval(() => {
    taskManager.cleanupTasks();
}, 60000);
