import { ActivityWatchdog } from "./activity-watchdog.js";
import { parseInteractiveEngineMessage } from "./protocol.js";
export class InteractiveEngineMonitor {
    constructor(onDiagnostic, onMessage) {
        this.watchdog = new ActivityWatchdog({ onDiagnostic });
        this.onMessage = onMessage;
        this.readiness = new Promise((resolve) => {
            this.resolveReady = resolve;
        });
        this.bound = new Promise((resolve, reject) => {
            this.resolveBound = resolve;
            this.rejectBound = reject;
        });
    }
    stop() {
        this.watchdog.stop();
    }
    fail(error) { this.rejectBound(error); }
    async waitUntilReady(timeoutMs = 5_000) {
        let timeout;
        try {
            await Promise.race([
                this.readiness,
                new Promise((_, reject) => {
                    timeout = setTimeout(() => reject(new Error(`Interactive engine did not become ready within ${timeoutMs} ms`)), timeoutMs);
                }),
            ]);
        }
        finally {
            if (timeout)
                clearTimeout(timeout);
        }
    }
    waitUntilBound() { return this.bound; }
    handleLine(line) {
        const message = parseInteractiveEngineMessage(line);
        if (!message)
            return false;
        this.onMessage(message);
        switch (message.type) {
            case "engine_ready":
                this.watchdog.heartbeat();
                this.watchdog.start();
                this.resolveReady();
                break;
            case "engine_bound":
                this.resolveBound();
                break;
            case "engine_heartbeat":
                this.watchdog.heartbeat();
                this.watchdog.start();
                break;
            case "engine_activity_started":
                this.watchdog.activityStarted(message.activity);
                break;
            case "engine_activity_finished":
                this.watchdog.activityFinished(message.activityId);
                break;
        }
        return true;
    }
}
//# sourceMappingURL=engine-monitor.js.map