/**
 * @module        runtimeSnapshot
 * @description   项目运行时快照聚合，提供全局状态视图
 *
 * @author        eddy
 * @organization  wykj
 * @ownership     wykj/eddy
 *
 * @created       2026-03-27
 * @updated       2026-04-03
 *
 * @role          state
 * @layer         core
 * @boundedContext runtime
 */
import { existsSync, readFileSync } from 'node:fs';
import { RuntimeCoordinator } from '../manager/runtime-coordinator.js';
import { createTaskBackend } from '../providers/registry.js';
import { ProjectContext } from './context.js';
import { isProcessAlive } from './sessionLiveness.js';
import { readState } from './state.js';
function detectTickRunning(ctx) {
    if (!existsSync(ctx.paths.tickLockFile))
        return false;
    try {
        const lock = JSON.parse(readFileSync(ctx.paths.tickLockFile, 'utf-8'));
        return !!(lock.pid && isProcessAlive(lock.pid));
    }
    catch {
        return false;
    }
}
export async function loadRuntimeSnapshot(projectName, options = {}) {
    const ctx = ProjectContext.load(projectName);
    const tickRunning = detectTickRunning(ctx);
    const projectWhenTickStopped = options.projectWhenTickStopped ?? true;
    if (tickRunning || !projectWhenTickStopped) {
        const state = readState(ctx.paths.stateFile, ctx.maxWorkers);
        return {
            ctx,
            tickRunning,
            state,
            acpState: { version: state.version, updatedAt: state.updatedAt, updatedBy: state.updatedBy, sessions: state.sessions },
        };
    }
    const taskBackend = createTaskBackend(ctx.config);
    const coordinator = new RuntimeCoordinator(ctx, taskBackend);
    const { state: projectedState } = await coordinator.buildRuntimeProjection();
    return {
        ctx,
        tickRunning,
        state: projectedState,
        acpState: { version: projectedState.version, updatedAt: projectedState.updatedAt, updatedBy: projectedState.updatedBy, sessions: projectedState.sessions },
    };
}
//# sourceMappingURL=runtimeSnapshot.js.map