import { readJson, writeJson, projectDataDir } from '../../storage/index.js';
import { pruneExpiredLocks } from '../orchestrate-locking.js';
export const EMPTY_STATE = { sessions: [], locks: [], conflicts: [] };
export const SESSION_IDLE_TIMEOUT_MS = 10 * 60 * 1000;
export function orchStatePath(projectId) {
    return `${projectDataDir(projectId)}/orchestration.json`;
}
export async function loadState(projectId) {
    return readJson(orchStatePath(projectId), { ...EMPTY_STATE });
}
export async function saveState(projectId, state) {
    await writeJson(orchStatePath(projectId), state);
}
export function pruneIdleSessions(state) {
    const now = Date.now();
    for (const session of state.sessions) {
        if (session.status === 'active' || session.status === 'idle') {
            if (now - new Date(session.lastActivity).getTime() > SESSION_IDLE_TIMEOUT_MS) {
                session.status = 'disconnected';
            }
        }
    }
    return state;
}
export async function getCleanState(projectId) {
    let state = await loadState(projectId);
    state = pruneExpiredLocks(state);
    state = pruneIdleSessions(state);
    return state;
}
//# sourceMappingURL=state.js.map