import { randomUUID } from 'node:crypto';
export class SetupRunRegistry {
    processGateway;
    activeRun = null;
    constructor(processGateway) {
        this.processGateway = processGateway;
    }
    start(options) {
        if (this.activeRun !== null && !this.activeRun.exited) {
            return { status: 'already-active', runId: this.activeRun.runId };
        }
        const handle = this.processGateway.spawn(options);
        const run = {
            runId: randomUUID(),
            handle,
            bufferedLines: [],
            subscribers: new Set(),
            exitCode: null,
            exited: false,
        };
        this.activeRun = run;
        handle.onLine((line) => {
            run.bufferedLines.push(line);
            for (const subscriber of run.subscribers) {
                subscriber.onEvent(line);
            }
        });
        handle.onExit((code) => {
            run.exited = true;
            run.exitCode = code;
            for (const subscriber of run.subscribers) {
                subscriber.onClose(code);
            }
        });
        return { status: 'started', runId: run.runId };
    }
    subscribe(runId, subscriber) {
        const run = this.activeRun;
        if (run === null || run.runId !== runId) {
            return () => { };
        }
        for (const line of run.bufferedLines) {
            subscriber.onEvent(line);
        }
        if (run.exited) {
            subscriber.onClose(run.exitCode);
            return () => { };
        }
        run.subscribers.add(subscriber);
        return () => {
            run.subscribers.delete(subscriber);
        };
    }
    submitInput(runId, line) {
        const run = this.activeRun;
        if (run === null || run.runId !== runId || run.exited) {
            return { status: 'no-active-run' };
        }
        run.handle.writeLine(line);
        return { status: 'written' };
    }
    hasActiveRun() {
        return this.activeRun !== null && !this.activeRun.exited;
    }
}
//# sourceMappingURL=streamSetupRun.usecase.js.map