"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processManager = exports.ProcessManager = void 0;
const child_process_1 = require("child_process");
const events_1 = require("events");
class ProcessManager extends events_1.EventEmitter {
    processes = new Map();
    constructor() {
        super();
    }
    async startProcess(info) {
        const processInfo = {
            ...info,
            status: 'starting',
            startTime: new Date()
        };
        try {
            const childProcess = (0, child_process_1.spawn)(info.command, info.args, {
                stdio: ['pipe', 'pipe', 'pipe'],
                detached: false
            });
            processInfo.pid = childProcess.pid;
            processInfo.status = 'running';
            this.processes.set(info.id, { info: processInfo, process: childProcess });
            childProcess.on('exit', (code) => {
                processInfo.status = code === 0 ? 'stopped' : 'error';
                this.emit('processExit', processInfo, code);
            });
            childProcess.on('error', (error) => {
                processInfo.status = 'error';
                this.emit('processError', processInfo, error);
            });
            this.emit('processStarted', processInfo);
            return processInfo;
        }
        catch (error) {
            processInfo.status = 'error';
            this.processes.set(info.id, { info: processInfo });
            throw error;
        }
    }
    stopProcess(id) {
        const processEntry = this.processes.get(id);
        if (!processEntry || !processEntry.process) {
            return false;
        }
        try {
            processEntry.process.kill('SIGTERM');
            processEntry.info.status = 'stopped';
            this.emit('processStopped', processEntry.info);
            return true;
        }
        catch (error) {
            processEntry.info.status = 'error';
            return false;
        }
    }
    getProcess(id) {
        return this.processes.get(id)?.info;
    }
    getAllProcesses() {
        return Array.from(this.processes.values()).map(entry => entry.info);
    }
    isProcessRunning(id) {
        const processInfo = this.getProcess(id);
        return processInfo?.status === 'running';
    }
    isPortInUse(port) {
        return Array.from(this.processes.values())
            .some(entry => entry.info.port === port && entry.info.status === 'running');
    }
    stopAllProcesses() {
        for (const [id] of this.processes) {
            this.stopProcess(id);
        }
    }
    cleanup() {
        this.stopAllProcesses();
        this.processes.clear();
    }
}
exports.ProcessManager = ProcessManager;
// Singleton instance
exports.processManager = new ProcessManager();
//# sourceMappingURL=processManager.js.map