import { readSessionsJsonFileRaw } from "./sessions-json-file-read.js";
import { existsSync } from "node:fs";
import { stat } from "node:fs/promises";
//#region src/session/parity/sessions-json-cache.ts
const readCache = /* @__PURE__ */ new Map();
const serializedWriteCache = /* @__PURE__ */ new Map();
let writeStats = {
	performed: 0,
	skippedUnchanged: 0
};
function getSessionsJsonWriteStats() {
	return writeStats;
}
function resetSessionsJsonCacheForTest() {
	readCache.clear();
	serializedWriteCache.clear();
	writeStats = {
		performed: 0,
		skippedUnchanged: 0
	};
}
function invalidateSessionsJsonCache(storePath) {
	readCache.delete(storePath);
	serializedWriteCache.delete(storePath);
}
function serializeSessionsJson(store) {
	return `${JSON.stringify(store, null, 2)}\n`;
}
async function readSessionsJsonCached(storePath) {
	if (!existsSync(storePath)) return {
		store: {},
		serialized: "{}\n"
	};
	let mtimeMs = 0;
	let sizeBytes = 0;
	try {
		const st = await stat(storePath);
		mtimeMs = st.mtimeMs;
		sizeBytes = st.size;
	} catch {
		return {
			store: {},
			serialized: "{}\n"
		};
	}
	const cached = readCache.get(storePath);
	if (cached && cached.mtimeMs === mtimeMs && cached.sizeBytes === sizeBytes) return {
		store: structuredClone(cached.parsed),
		serialized: cached.serialized
	};
	const store = await readSessionsJsonFileRaw(storePath);
	const serialized = serializeSessionsJson(store);
	readCache.set(storePath, {
		mtimeMs,
		sizeBytes,
		parsed: structuredClone(store),
		serialized
	});
	serializedWriteCache.set(storePath, serialized);
	return {
		store: structuredClone(store),
		serialized
	};
}
function commitSessionsJsonWrite(storePath, store, serialized) {
	if (serializedWriteCache.get(storePath) === serialized) {
		writeStats.skippedUnchanged += 1;
		readCache.set(storePath, {
			mtimeMs: readCache.get(storePath)?.mtimeMs ?? Date.now(),
			sizeBytes: serialized.length,
			parsed: structuredClone(store),
			serialized
		});
		return false;
	}
	serializedWriteCache.set(storePath, serialized);
	writeStats.performed += 1;
	readCache.set(storePath, {
		mtimeMs: Date.now(),
		sizeBytes: serialized.length,
		parsed: structuredClone(store),
		serialized
	});
	return true;
}
function noteSessionsJsonWritten(storePath, serialized, store) {
	serializedWriteCache.set(storePath, serialized);
	readCache.set(storePath, {
		mtimeMs: Date.now(),
		sizeBytes: serialized.length,
		parsed: structuredClone(store),
		serialized
	});
}
//#endregion
export { commitSessionsJsonWrite, getSessionsJsonWriteStats, invalidateSessionsJsonCache, noteSessionsJsonWritten, readSessionsJsonCached, resetSessionsJsonCacheForTest };

//# sourceMappingURL=sessions-json-cache.js.map