import path from "node:path";
import { getRunEventBus } from "../runs/runEventBus.js";
export class SessionHub {
    runs = new Map();
    remotes = new Map();
    subscription;
    start() {
        if (this.subscription)
            return;
        this.subscription = getRunEventBus().subscribe({}, (event) => {
            if (!event.runId || !event.projectPath)
                return;
            const key = normalizeProject(event.projectPath);
            const previous = this.runs.get(key);
            this.runs.set(key, {
                runId: event.runId,
                projectPath: event.projectPath,
                status: runStatusFromEvent(event.kind, event.payload) ?? previous?.status ?? "unknown",
                lastEventKind: event.kind,
                lastEventAtMs: event.createdAtMs,
            });
        });
    }
    stop() {
        this.subscription?.unsubscribe();
        this.subscription = undefined;
    }
    updateRemote(input) {
        this.remotes.set(`${input.channel}:${normalizeProject(input.projectPath)}`, input);
    }
    latestRun(projectPath) {
        this.start();
        return this.runs.get(normalizeProject(projectPath));
    }
    remoteStatus(channel, projectPath) {
        return this.remotes.get(`${channel}:${normalizeProject(projectPath)}`);
    }
}
const singleton = new SessionHub();
export function getSessionHub() {
    singleton.start();
    return singleton;
}
function normalizeProject(projectPath) {
    return path.resolve(projectPath).replace(/\\/g, "/").toLowerCase();
}
function runStatusFromEvent(kind, payload) {
    if (kind !== "run_status_updated")
        return kind === "run_created" ? "running" : undefined;
    if (!payload || typeof payload !== "object")
        return undefined;
    const status = payload.status;
    if (status === "running" || status === "succeeded" || status === "failed" || status === "paused" || status === "cancelled") {
        return status;
    }
    return undefined;
}
