import { init_paths, resolveConfigPath } from "../../../config/paths.js";
import { getContextWithOpts } from "../../context.js";
import { addGatewayClientOptions, parseGatewayClientOptions } from "../../utils/gateway-client-options.js";
import { Command } from "commander";
//#region src/cli/commands/gateway/status.ts
init_paths();
function formatUptime(seconds) {
	if (!seconds || seconds <= 0) return "unknown";
	const days = Math.floor(seconds / 86400);
	const hours = Math.floor(seconds % 86400 / 3600);
	const minutes = Math.floor(seconds % 3600 / 60);
	const parts = [];
	if (days > 0) parts.push(`${days}d`);
	if (hours > 0) parts.push(`${hours}h`);
	parts.push(`${minutes}m`);
	return parts.join(" ");
}
function createStatusCommand() {
	const cmd = new Command("status").description("Check gateway status (service + connectivity)");
	addGatewayClientOptions(cmd);
	cmd.option("--no-probe", "Skip HTTP probe (only check service/lock)");
	cmd.action(async (options) => {
		const configPath = getContextWithOpts().configPath || resolveConfigPath();
		const [{ loadConfig }, { acquireGatewayLock, GatewayLockError }, { callGatewayApi, resolveGatewayUrl }, { resolveGatewayService, isDaemonAvailableAsync, getPlatformName }] = await Promise.all([
			import("../../../config/index.js"),
			import("../../../gateway/lock.js"),
			import("../../utils/gateway-client.js"),
			import("../../../daemon/service.js")
		]);
		const config = loadConfig(configPath);
		const port = config?.gateway?.port ?? 18790;
		const clientOpts = {
			...parseGatewayClientOptions(options),
			configPath
		};
		const gatewayUrl = resolveGatewayUrl({
			url: clientOpts.url,
			configPath
		});
		let serviceLoaded = false;
		let serviceRuntime = null;
		let serviceVersion;
		const daemonAvailable = await isDaemonAvailableAsync();
		if (daemonAvailable) try {
			const service = await resolveGatewayService();
			serviceLoaded = await service.isLoaded({ env: process.env });
			if (serviceLoaded) {
				serviceRuntime = await service.readRuntime();
				serviceVersion = (await service.readCommand())?.environment?.XOPC_SERVICE_VERSION;
			}
		} catch {}
		let lockAlive = false;
		let lockPid;
		try {
			await (await acquireGatewayLock(configPath, {
				timeoutMs: 100,
				port
			})).release();
			lockAlive = false;
		} catch (err) {
			if (err instanceof GatewayLockError) {
				lockAlive = true;
				const pidMatch = err.message.match(/pid\s+(\d+)/);
				if (pidMatch) lockPid = parseInt(pidMatch[1], 10);
			} else {
				console.error("❌ Failed to check status:", err);
				process.exit(1);
			}
		}
		const shouldProbe = options.probe !== false;
		let probeResult = null;
		if (shouldProbe) {
			const healthProbe = await callGatewayApi("GET", "/api/health", {
				...clientOpts,
				timeoutMs: clientOpts.timeoutMs ?? 5e3
			});
			if (healthProbe.ok) {
				const statusProbe = await callGatewayApi("GET", "/api/status", clientOpts);
				probeResult = statusProbe.ok ? statusProbe : {
					ok: true,
					durationMs: healthProbe.durationMs,
					data: { status: "ok" }
				};
			} else probeResult = {
				ok: false,
				error: healthProbe.error,
				durationMs: healthProbe.durationMs
			};
		}
		if (clientOpts.json) {
			console.log(JSON.stringify({
				running: lockAlive || (probeResult?.ok ?? false),
				service: daemonAvailable ? {
					platform: getPlatformName(),
					loaded: serviceLoaded,
					runtime: serviceRuntime,
					version: serviceVersion
				} : null,
				lock: {
					alive: lockAlive,
					pid: lockPid
				},
				probe: probeResult ? {
					reachable: probeResult.ok,
					durationMs: probeResult.durationMs,
					...probeResult.data ?? {},
					...probeResult.error ? { error: probeResult.error } : {}
				} : null,
				url: gatewayUrl,
				port
			}, null, 2));
			process.exit(probeResult?.ok || lockAlive ? 0 : 1);
		}
		if (!(lockAlive || (probeResult?.ok ?? false) || serviceRuntime?.status === "running")) {
			console.log("⚠️  Gateway is not running");
			if (daemonAvailable) console.log(`   Service: ${serviceLoaded ? "installed (not running)" : "not installed"}`);
			if (probeResult && !probeResult.ok) console.log(`   Probe: ${probeResult.error} (${probeResult.durationMs}ms)`);
			console.log("");
			console.log("💡 Start with: xopc gateway");
			if (!serviceLoaded && daemonAvailable) console.log("   Or install service: xopc gateway service install");
			process.exit(1);
		}
		console.log("Gateway Status");
		console.log("");
		if (daemonAvailable && serviceLoaded) {
			const runtimeStatus = serviceRuntime?.status ?? "unknown";
			const pid = serviceRuntime?.pid || lockPid;
			console.log(`  Service:  ${getPlatformName()} (loaded)`);
			console.log(`  Runtime:  ${runtimeStatus}${pid ? ` (pid ${pid})` : ""}`);
		} else if (lockPid) console.log(`  PID:      ${lockPid}`);
		console.log(`  Port:     ${port}`);
		console.log(`  URL:      ${gatewayUrl}`);
		const version = probeResult?.data?.version || serviceVersion;
		if (version) console.log(`  Version:  ${version}`);
		if (probeResult?.ok && probeResult.data?.uptime != null) console.log(`  Uptime:   ${formatUptime(probeResult.data.uptime)}`);
		if (probeResult?.ok) console.log(`  Probe:    OK (${probeResult.durationMs}ms)`);
		else if (probeResult && !probeResult.ok) console.log(`  Probe:    Failed (${probeResult.error})`);
		else if (!shouldProbe) console.log("  Probe:    skipped");
		if (config?.gateway?.auth?.token) console.log(`  Token:    configured ✓`);
		if (probeResult?.ok && probeResult.data?.channels) {
			const channels = probeResult.data.channels;
			if (Object.keys(channels).length > 0) {
				console.log("");
				console.log("Channels:");
				for (const [name, info] of Object.entries(channels)) {
					const icon = info.status === "connected" ? "✅" : info.status === "disabled" ? "⚪" : "❌";
					console.log(`  ${icon} ${name}: ${info.status}`);
				}
			}
		}
		process.exit(0);
	});
	return cmd;
}
//#endregion
export { createStatusCommand };

//# sourceMappingURL=status.js.map