/**
 * Server heartbeat scheduler host.
 *
 * Owns process-level scheduler lifecycle for all known workspaces in the local
 * control-plane catalog. Core decides when and how tasks run; this host starts
 * and stops one core scheduler per workspace while the daemon/server process is
 * alive.
 */
import { HeartbeatSchedulerService } from '../core/heartbeat/index.js';
import { RuntimeWorkspaceService } from '../core/runtime/workspaces/index.js';
export class HeddleHeartbeatSchedulerHost {
    options;
    schedulers = new Map();
    constructor(options) {
        this.options = options;
    }
    start() {
        this.sync();
    }
    sync() {
        const context = RuntimeWorkspaceService.resolveContext({
            workspaceRoot: this.options.workspaceRoot,
            stateRoot: this.options.stateRoot,
        });
        const workspacesByKey = new Map(context.workspaces.map((workspace) => [
            HeddleHeartbeatSchedulerHost.workspaceKey(workspace),
            workspace,
        ]));
        workspacesByKey.forEach((workspace, key) => {
            if (!this.schedulers.has(key)) {
                this.schedulers.set(key, {
                    workspace,
                    scheduler: this.startWorkspaceScheduler(workspace),
                });
            }
        });
        [...this.schedulers.entries()]
            .filter(([key]) => !workspacesByKey.has(key))
            .forEach(([key, handle]) => {
            handle.scheduler.stop();
            this.schedulers.delete(key);
        });
    }
    stop() {
        this.schedulers.forEach((handle) => handle.scheduler.stop());
        this.schedulers.clear();
    }
    startWorkspaceScheduler(workspace) {
        return HeartbeatSchedulerService.start({
            workspaceRoot: workspace.workspaceRoot,
            stateRoot: workspace.stateRoot,
            preferApiKey: this.options.preferApiKey,
            pollIntervalMs: this.options.pollIntervalMs,
            onEvent: (event) => this.options.onEvent?.(workspace, event),
            onError: (error) => this.options.onError?.(workspace, error),
        });
    }
    static workspaceKey(workspace) {
        return `${workspace.id}:${workspace.stateRoot}`;
    }
}
//# sourceMappingURL=heartbeat-scheduler-host.js.map