// storage/status-store/version-sync.ts — SPEC-753: Version sync at startup + per-session
//
// Ensures status.json.version always reflects the current runtime Planu version.
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { dirname } from 'node:path';
import { PLANU_VERSION } from '../../config/version.js';
/** Track which status.json paths have already been synced this server session. */
const syncedPaths = new Set();
/**
 * Sync the `version` field in status.json with the current runtime.
 * No-op if the version is already current or the file doesn't exist.
 * Idempotent within a session (tracks synced paths to avoid redundant I/O).
 */
export async function syncVersionField(statusPath, force = false) {
    if (!force && syncedPaths.has(statusPath)) {
        return { synced: false };
    }
    let raw;
    try {
        raw = await readFile(statusPath, 'utf-8');
    }
    catch {
        syncedPaths.add(statusPath);
        return { synced: false };
    }
    let parsed;
    try {
        const p = JSON.parse(raw);
        if (typeof p !== 'object' || p === null || Array.isArray(p)) {
            syncedPaths.add(statusPath);
            return { synced: false };
        }
        parsed = p;
    }
    catch {
        syncedPaths.add(statusPath);
        return { synced: false };
    }
    const currentVersion = typeof parsed.version === 'string' ? parsed.version : undefined;
    if (currentVersion === PLANU_VERSION) {
        syncedPaths.add(statusPath);
        return { synced: false };
    }
    parsed.version = PLANU_VERSION;
    parsed.updatedAt = new Date().toISOString();
    await mkdir(dirname(statusPath), { recursive: true });
    await writeFile(statusPath, JSON.stringify(parsed, null, 2), 'utf-8');
    syncedPaths.add(statusPath);
    return { synced: true, from: currentVersion, to: PLANU_VERSION };
}
/** Clear the session sync cache — TEST USE ONLY. */
export function clearVersionSyncCache() {
    syncedPaths.clear();
}
//# sourceMappingURL=version-sync.js.map