import { init_write_file_atomic, writeTextAtomic } from "../../infra/write-file-atomic.js";
import { readSessionsJsonFileRaw } from "./sessions-json-file-read.js";
import { commitSessionsJsonWrite, getSessionsJsonWriteStats, invalidateSessionsJsonCache, noteSessionsJsonWritten, readSessionsJsonCached, resetSessionsJsonCacheForTest } from "./sessions-json-cache.js";
import { existsSync } from "node:fs";
import { mkdir } from "node:fs/promises";
import { dirname } from "node:path";
import lockfile from "proper-lockfile";
//#region src/session/parity/sessions-json-file.ts
init_write_file_atomic();
async function ensureDirForFile(filePath) {
	await mkdir(dirname(filePath), { recursive: true });
}
function serializeSessionsJson(store) {
	return `${JSON.stringify(store, null, 2)}\n`;
}
/**
* Read JSON object from `sessions.json`. Missing file → `{}`.
* Uses mtime/size cache when enabled.
*/
async function readSessionsJsonFile(storePath) {
	if (!existsSync(storePath)) return {};
	const { store } = await readSessionsJsonCached(storePath);
	return store;
}
/**
* Exclusive update: lock → read → mutate → atomic write (skipped when serialized unchanged) → unlock.
*/
async function withSessionsJsonLock(storePath, fn) {
	await ensureDirForFile(storePath);
	if (!existsSync(storePath)) {
		await writeTextAtomic(storePath, "{}\n");
		noteSessionsJsonWritten(storePath, "{}\n", {});
	}
	const release = await lockfile.lock(storePath, { retries: {
		retries: 30,
		minTimeout: 50,
		maxTimeout: 500
	} });
	try {
		const data = existsSync(storePath) ? await readSessionsJsonFileRaw(storePath) : {};
		const result = await fn(data);
		const serialized = serializeSessionsJson(data);
		if (commitSessionsJsonWrite(storePath, data, serialized)) await writeTextAtomic(storePath, serialized);
		return result;
	} finally {
		await release();
	}
}
//#endregion
export { getSessionsJsonWriteStats, invalidateSessionsJsonCache, readSessionsJsonFile, resetSessionsJsonCacheForTest, withSessionsJsonLock };

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