import { PACKAGE_VERSION, init_package_version } from "../package-version.js";
import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { SERVICE_VERSION_ENV_KEY } from "./constants.js";
import { existsSync } from "node:fs";
//#region src/daemon/service.ts
/**
* Daemon Service Abstraction - Cross-platform service management
*
* Provides:
* - Platform-specific service resolution (launchd / systemd / schtasks)
* - Availability detection
* - Unified start logic with repair detection
*/
init_logger();
init_package_version();
const log = createLogger("DaemonService");
let _isDaemonAvailable = null;
async function resolveGatewayService() {
	const platform = process.platform;
	if (platform === "darwin") {
		const { launchdService } = await import("./launchd.js");
		return launchdService;
	}
	if (platform === "linux") {
		const { systemdService } = await import("./systemd.js");
		return systemdService;
	}
	if (platform === "win32") {
		const { schtasksService } = await import("./schtasks.js");
		return schtasksService;
	}
	throw new Error(`Unsupported platform for daemon services: ${platform}`);
}
async function isDaemonAvailableAsync() {
	if (_isDaemonAvailable !== null) return _isDaemonAvailable;
	const platform = process.platform;
	try {
		if (platform === "darwin") {
			const { isLaunchdAvailable } = await import("./launchd.js");
			_isDaemonAvailable = isLaunchdAvailable();
		} else if (platform === "linux") {
			const { isSystemdAvailable } = await import("./systemd.js");
			_isDaemonAvailable = isSystemdAvailable();
		} else if (platform === "win32") {
			const { isSchtasksAvailable } = await import("./schtasks.js");
			_isDaemonAvailable = isSchtasksAvailable();
		} else _isDaemonAvailable = false;
	} catch (err) {
		log.error({ err }, "Failed to check daemon availability");
		_isDaemonAvailable = false;
	}
	return _isDaemonAvailable;
}
function isDaemonAvailable() {
	const platform = process.platform;
	return platform === "linux" || platform === "darwin" || platform === "win32";
}
async function startGatewayService(params) {
	const { service, env } = params;
	const serviceEnv = env || process.env;
	const initialState = await gatherServiceState(service, serviceEnv);
	if (!initialState.installed) return {
		outcome: "missing-install",
		state: initialState
	};
	const issues = detectStartRepairIssues(initialState.command);
	if (issues.length > 0) return {
		outcome: "repair-required",
		state: initialState,
		issues
	};
	const restartResult = await service.restart({ env: serviceEnv });
	const state = await gatherServiceState(service, serviceEnv);
	return {
		outcome: restartResult.outcome === "restarted" ? "started" : "scheduled",
		state
	};
}
function detectStartRepairIssues(command) {
	const issues = [];
	if (!command || command.programArguments.length === 0) {
		issues.push({
			code: "missing-program",
			message: "Service command configuration is missing"
		});
		return issues;
	}
	const program = command.programArguments[0];
	if (!existsSync(program)) {
		issues.push({
			code: "missing-program",
			message: `Service program not found: ${program}`
		});
		return issues;
	}
	const serviceVersion = command.environment?.[SERVICE_VERSION_ENV_KEY];
	if (serviceVersion && serviceVersion !== PACKAGE_VERSION) issues.push({
		code: "version-mismatch",
		message: `Service version ${serviceVersion} does not match current ${PACKAGE_VERSION}`
	});
	return issues;
}
async function gatherServiceState(service, env) {
	const [loaded, runtime, command] = await Promise.all([
		service.isLoaded({ env }),
		service.readRuntime(env),
		service.readCommand(env)
	]);
	return {
		installed: loaded || command !== null,
		loaded,
		running: runtime.status === "running",
		env,
		command,
		runtime
	};
}
function getPlatformName() {
	switch (process.platform) {
		case "darwin": return "macOS (launchd)";
		case "linux": return "Linux (systemd)";
		case "win32": return "Windows (Task Scheduler)";
		default: return process.platform;
	}
}
function getServiceLabel() {
	return "xopc-gateway";
}
/** Describe what a restart operation will do on the current platform */
function describeGatewayServiceRestart() {
	switch (process.platform) {
		case "darwin": return "launchctl kickstart -k (LaunchAgent restart)";
		case "linux": return "systemctl --user restart (systemd restart)";
		case "win32": return "schtasks /end + /run (Scheduled Task restart)";
		default: return "platform restart";
	}
}
//#endregion
export { describeGatewayServiceRestart, getPlatformName, getServiceLabel, isDaemonAvailable, isDaemonAvailableAsync, resolveGatewayService, startGatewayService };

//# sourceMappingURL=service.js.map