import { init_write_file_atomic, writeTextAtomic } from "./write-file-atomic.js";
import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { init_paths_state, resolveUpdateLockPath } from "../config/paths-state.js";
import { mkdir, readFile, unlink } from "node:fs/promises";
import { dirname } from "node:path";
//#region src/infra/update-lock.ts
init_write_file_atomic();
init_paths_state();
init_logger();
const log = createLogger("UpdateLock");
const STALE_THRESHOLD_MS = 3600 * 1e3;
function resolveLockPath() {
	return resolveUpdateLockPath();
}
function isProcessAlive(pid) {
	try {
		process.kill(pid, 0);
		return true;
	} catch {
		return false;
	}
}
/**
* Attempt to acquire the update lock. Returns a release function on success, or null if
* another live process holds the lock.
*/
async function acquireUpdateLock(source) {
	const lockPath = resolveLockPath();
	try {
		const raw = await readFile(lockPath, "utf-8");
		const existing = JSON.parse(raw);
		const startedAt = Date.parse(existing.startedAt);
		const age = Date.now() - startedAt;
		if (isProcessAlive(existing.pid) && age < STALE_THRESHOLD_MS) {
			log.info({
				existingPid: existing.pid,
				source: existing.source,
				ageMs: age
			}, "Update lock held by another live process");
			return null;
		}
		log.warn({
			existingPid: existing.pid,
			source: existing.source,
			ageMs: age
		}, "Reclaiming stale update lock");
	} catch (err) {
		if (err.code !== "ENOENT") log.warn({ err }, "Failed to read update lock; proceeding");
	}
	const info = {
		pid: process.pid,
		startedAt: (/* @__PURE__ */ new Date()).toISOString(),
		source
	};
	await mkdir(dirname(lockPath), { recursive: true });
	await writeTextAtomic(lockPath, JSON.stringify(info, null, 2));
	const release = async () => {
		try {
			const raw = await readFile(lockPath, "utf-8");
			if (JSON.parse(raw).pid === process.pid) await unlink(lockPath);
		} catch {}
	};
	return { release };
}
//#endregion
export { acquireUpdateLock };

//# sourceMappingURL=update-lock.js.map