import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { init_paths_state, resolveStateDir } from "../config/paths-state.js";
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
//#region src/infra/restart.ts
/**
* Gateway restart coordination — OpenClaw-aligned SIGUSR1 authorization and restart intent.
*/
init_paths_state();
init_logger();
const log = createLogger("Restart");
const SIGUSR1_AUTH_GRACE_MS = 5e3;
const GATEWAY_RESTART_INTENT_FILENAME = "gateway-restart-intent.json";
const GATEWAY_RESTART_INTENT_TTL_MS = 6e4;
let sigusr1AuthorizedCount = 0;
let sigusr1AuthorizedUntil = 0;
let sigusr1ExternalAllowed = false;
let pendingRestartTimer = null;
let pendingRestartCallback = null;
function resolveGatewayRestartIntentPath(env = process.env) {
	const stateDir = env.XOPC_STATE_DIR?.trim() || resolveStateDir();
	return path.join(stateDir, GATEWAY_RESTART_INTENT_FILENAME);
}
function normalizeRestartIntentPid(pid) {
	return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 ? pid : null;
}
function writeGatewayRestartIntentSync(opts = {}) {
	const targetPid = normalizeRestartIntentPid(opts.targetPid);
	if (targetPid === null) return false;
	const intentPath = resolveGatewayRestartIntentPath(opts.env ?? process.env);
	const payload = {
		kind: "gateway-restart",
		pid: targetPid,
		createdAt: Date.now()
	};
	try {
		mkdirSync(path.dirname(intentPath), { recursive: true });
		writeFileSync(intentPath, `${JSON.stringify(payload)}\n`, "utf8");
		return true;
	} catch (err) {
		log.warn({ err }, "Failed to write gateway restart intent");
		return false;
	}
}
function clearGatewayRestartIntentSync(env = process.env) {
	try {
		rmSync(resolveGatewayRestartIntentPath(env));
	} catch {}
}
function parseGatewayRestartIntent(raw) {
	try {
		const parsed = JSON.parse(raw);
		if (parsed.kind === "gateway-restart" && typeof parsed.pid === "number" && Number.isFinite(parsed.pid) && typeof parsed.createdAt === "number" && Number.isFinite(parsed.createdAt)) return parsed;
	} catch {
		return null;
	}
	return null;
}
function consumeGatewayRestartIntentSync(env = process.env, now = Date.now()) {
	const intentPath = resolveGatewayRestartIntentPath(env);
	let raw;
	try {
		raw = readFileSync(intentPath, "utf8");
	} catch {
		return false;
	} finally {
		clearGatewayRestartIntentSync(env);
	}
	const payload = parseGatewayRestartIntent(raw);
	if (!payload) return false;
	if (payload.pid !== process.pid) return false;
	const ageMs = now - payload.createdAt;
	return ageMs >= 0 && ageMs <= GATEWAY_RESTART_INTENT_TTL_MS;
}
function setGatewaySigusr1RestartPolicy(opts) {
	sigusr1ExternalAllowed = opts?.allowExternal === true;
}
function isGatewaySigusr1RestartExternallyAllowed() {
	return sigusr1ExternalAllowed;
}
function resetSigusr1AuthorizationIfExpired(now = Date.now()) {
	if (sigusr1AuthorizedCount <= 0) return;
	if (now <= sigusr1AuthorizedUntil) return;
	sigusr1AuthorizedCount = 0;
	sigusr1AuthorizedUntil = 0;
}
function authorizeGatewaySigusr1Restart(delayMs = 0) {
	const delay = Math.max(0, Math.floor(delayMs));
	const expiresAt = Date.now() + delay + SIGUSR1_AUTH_GRACE_MS;
	sigusr1AuthorizedCount += 1;
	if (expiresAt > sigusr1AuthorizedUntil) sigusr1AuthorizedUntil = expiresAt;
}
function consumeGatewaySigusr1RestartAuthorization() {
	resetSigusr1AuthorizationIfExpired();
	if (sigusr1AuthorizedCount <= 0) return false;
	sigusr1AuthorizedCount -= 1;
	if (sigusr1AuthorizedCount <= 0) sigusr1AuthorizedUntil = 0;
	return true;
}
function resetGatewayRestartStateForInProcessRestart() {
	if (pendingRestartTimer) {
		clearTimeout(pendingRestartTimer);
		pendingRestartTimer = null;
	}
	pendingRestartCallback = null;
}
function scheduleGatewaySigusr1Restart(params) {
	if (pendingRestartTimer) clearTimeout(pendingRestartTimer);
	pendingRestartCallback = params.onRestart;
	const delayMs = Math.max(0, params.delayMs ?? 0);
	pendingRestartTimer = setTimeout(() => {
		pendingRestartTimer = null;
		const callback = pendingRestartCallback;
		pendingRestartCallback = null;
		callback?.();
	}, delayMs);
}
//#endregion
export { authorizeGatewaySigusr1Restart, clearGatewayRestartIntentSync, consumeGatewayRestartIntentSync, consumeGatewaySigusr1RestartAuthorization, isGatewaySigusr1RestartExternallyAllowed, resetGatewayRestartStateForInProcessRestart, scheduleGatewaySigusr1Restart, setGatewaySigusr1RestartPolicy, writeGatewayRestartIntentSync };

//# sourceMappingURL=restart.js.map