import { g as resolveStateDir } from "./paths-mmi2xb99.js";
import { t as formatCliCommand } from "./command-format-D8drL8c2.js";
import path from "node:path";
import fs from "node:fs/promises";

//#region ../../src/infra/restart-sentinel.ts
const SENTINEL_FILENAME = "restart-sentinel.json";
function formatDoctorNonInteractiveHint(env = process.env) {
	return `Run: ${formatCliCommand("edwinpai doctor --non-interactive", env)}`;
}
function resolveRestartSentinelPath(env = process.env) {
	return path.join(resolveStateDir(env), SENTINEL_FILENAME);
}
async function writeRestartSentinel(payload, env = process.env) {
	const filePath = resolveRestartSentinelPath(env);
	await fs.mkdir(path.dirname(filePath), { recursive: true });
	const data = {
		version: 1,
		payload
	};
	await fs.writeFile(filePath, `${JSON.stringify(data, null, 2)}\n`, "utf-8");
	return filePath;
}
async function readRestartSentinel(env = process.env) {
	const filePath = resolveRestartSentinelPath(env);
	try {
		const raw = await fs.readFile(filePath, "utf-8");
		let parsed;
		try {
			parsed = JSON.parse(raw);
		} catch {
			await fs.unlink(filePath).catch(() => {});
			return null;
		}
		if (!parsed || parsed.version !== 1 || !parsed.payload) {
			await fs.unlink(filePath).catch(() => {});
			return null;
		}
		return parsed;
	} catch {
		return null;
	}
}
async function consumeRestartSentinel(env = process.env) {
	const filePath = resolveRestartSentinelPath(env);
	const parsed = await readRestartSentinel(env);
	if (!parsed) return null;
	await fs.unlink(filePath).catch(() => {});
	return parsed;
}
function formatRestartSentinelMessage(payload) {
	const lines = [];
	const { kind, status, stats, message, doctorHint } = payload;
	const mode = stats?.mode ? ` (${stats.mode})` : "";
	lines.push(`GatewayRestart: ${kind} ${status}${mode}`);
	if (stats?.before || stats?.after) {
		const before = stats.before;
		const after = stats.after;
		const bSha = before?.sha?.slice(0, 10) ?? "?";
		const aSha = after?.sha?.slice(0, 10) ?? "?";
		const changed = bSha !== aSha;
		lines.push(changed ? `Version: ${before?.version ?? "?"} (${bSha}) → ${after?.version ?? "?"} (${aSha})` : `Version: ${before?.version ?? "?"} (${bSha}) (no change)`);
	}
	if (stats?.reason) lines.push(`Reason: ${stats.reason}`);
	if (stats?.durationMs != null) lines.push(`Duration: ${(stats.durationMs / 1e3).toFixed(1)}s`);
	if (stats?.steps?.length) {
		const stepSummaries = [];
		for (const step of stats.steps) {
			const ok = step.log?.exitCode === 0;
			const dur = step.durationMs != null ? ` (${(step.durationMs / 1e3).toFixed(1)}s)` : "";
			if (ok) stepSummaries.push(`  ✅ ${step.name}${dur}`);
			else {
				const errSnippet = (step.log?.stderrTail ?? step.log?.stdoutTail ?? "").split("\n").filter(Boolean).slice(-3).join(" | ");
				const snippet = errSnippet ? `: ${errSnippet.slice(0, 200)}` : "";
				stepSummaries.push(`  ❌ ${step.name}${dur}${snippet}`);
			}
		}
		lines.push("Steps:", ...stepSummaries);
	}
	if (message) lines.push(`Message: ${message}`);
	if (doctorHint) lines.push(doctorHint);
	return lines.join("\n");
}
function summarizeRestartSentinel(payload) {
	return `Gateway restart ${payload.kind} ${payload.status}${payload.stats?.mode ? ` (${payload.stats.mode})` : ""}`.trim();
}
function trimLogTail(input, maxChars = 8e3) {
	if (!input) return null;
	const text = input.trimEnd();
	if (text.length <= maxChars) return text;
	return `…${text.slice(text.length - maxChars)}`;
}

//#endregion
export { summarizeRestartSentinel as a, readRestartSentinel as i, formatDoctorNonInteractiveHint as n, trimLogTail as o, formatRestartSentinelMessage as r, writeRestartSentinel as s, consumeRestartSentinel as t };