import { d as CleoError, E as ExitCode } from './paths-2M_UxD_H.js';
import { w as withLock } from './lock-BoHF25mx.js';
import 'node:fs';
import { dirname, basename, join } from 'node:path';
import 'node:crypto';
import { mkdir, readFile, stat, unlink, rename, copyFile } from 'node:fs/promises';
import { w as writeFileAtomic } from './index-Ca4C2M45.js';

//#region ../core/dist/store/atomic.js
/**
* Write data to a file atomically.
* Creates parent directories if they don't exist.
* Uses write-file-atomic for crash-safe writes (temp file -> rename).
*/
async function atomicWrite(filePath, data, options) {
	try {
		await mkdir(dirname(filePath), { recursive: true });
		await writeFileAtomic(filePath, data, {
			encoding: options?.encoding ?? "utf8",
			mode: options?.mode
		});
	} catch (err) {
		throw new CleoError(ExitCode.FILE_ERROR, `Atomic write failed: ${filePath}`, { cause: err });
	}
}
/**
* Read a file and return its contents.
* Returns null if the file does not exist.
*/
async function safeReadFile(filePath) {
	try {
		return await readFile(filePath, "utf8");
	} catch (err) {
		if (err instanceof Error && "code" in err && err.code === "ENOENT") return null;
		throw new CleoError(ExitCode.FILE_ERROR, `Failed to read: ${filePath}`, { cause: err });
	}
}
/**
* Write JSON data atomically with consistent formatting.
*/
async function atomicWriteJson(filePath, data, options) {
	await atomicWrite(filePath, JSON.stringify(data, null, options?.indent ?? 2) + "\n");
}
//#endregion
//#region ../core/dist/store/backup.js
/**
* Numbered backup system for CLEO data files.
* Maintains a rotating window of recent backups for rollback protection.
* @epic T4454
* @task T4457
*/
var DEFAULT_MAX_BACKUPS = 5;
/**
* Create a numbered backup of a file.
* Rotates existing backups (file.1 -> file.2, etc.) and removes excess.
*/
async function createBackup(filePath, backupDir, maxBackups = DEFAULT_MAX_BACKUPS) {
	try {
		await mkdir(backupDir, { recursive: true });
		const fileName = basename(filePath);
		try {
			await stat(filePath);
		} catch {
			throw new CleoError(ExitCode.FILE_ERROR, `Cannot backup: source file not found: ${filePath}`);
		}
		for (let i = maxBackups; i >= 1; i--) {
			const current = join(backupDir, `${fileName}.${i}`);
			if (i === maxBackups) try {
				await unlink(current);
			} catch {}
			else {
				const next = join(backupDir, `${fileName}.${i + 1}`);
				try {
					await stat(current);
					await rename(current, next);
				} catch {}
			}
		}
		const backupPath = join(backupDir, `${fileName}.1`);
		await copyFile(filePath, backupPath);
		return backupPath;
	} catch (err) {
		if (err instanceof CleoError) throw err;
		throw new CleoError(ExitCode.FILE_ERROR, `Backup failed for: ${filePath}`, { cause: err });
	}
}
//#endregion
//#region ../core/dist/store/json.js
/**
* Read and parse a JSON file.
* Returns null if the file does not exist.
*/
async function readJson(filePath) {
	const content = await safeReadFile(filePath);
	if (content === null) return null;
	try {
		return JSON.parse(content);
	} catch (err) {
		throw new CleoError(ExitCode.VALIDATION_ERROR, `Invalid JSON in: ${filePath}`, { cause: err });
	}
}
/**
* Save JSON data with optional locking, backup, and validation.
* Follows the CLEO atomic write pattern:
*   1. Acquire lock
*   2. Validate data
*   3. Create backup of existing file
*   4. Atomic write (temp file -> rename)
*   5. Release lock
*/
async function saveJson(filePath, data, options) {
	await withLock(filePath, async () => {
		if (options?.validate) ;
		if (options?.backupDir) ;
		await atomicWriteJson(filePath, data, { indent: options?.indent });
		const dispatchCwd = process.cwd();
		import('./registry-CpiJvLWz.js').then(({ hooks: h }) => h.dispatch("Notification", dispatchCwd, {
			timestamp: (/* @__PURE__ */ new Date()).toISOString(),
			filePath,
			changeType: "write"
		})).catch(() => {});
	});
}

export { atomicWriteJson as a, readJson as r, saveJson as s };
//# sourceMappingURL=json-DXl7iDYg.js.map
