import { a as resolveCanonicalConfigPath } from "./paths-mmi2xb99.js";
import { n as isSupportedNodeVersion } from "./runtime-guard-DD5U3rmV.js";
import { I as VERSION } from "./config-C9wUwpYY.js";
import { a as NODE_SERVICE_MARKER, d as resolveGatewaySystemdServiceName, g as resolveNodeWindowsTaskName, h as resolveNodeSystemdServiceName, i as NODE_SERVICE_KIND, l as resolveGatewayLaunchAgentLabel, m as resolveNodeLaunchAgentLabel, n as GATEWAY_SERVICE_KIND, o as NODE_WINDOWS_TASK_SCRIPT_NAME, r as GATEWAY_SERVICE_MARKER } from "./constants-CJLwmrLm.js";
import { p as resolveGatewayStateDir } from "./systemd-B3oVOU-l.js";
import path from "node:path";
import { promisify } from "node:util";
import fs from "node:fs/promises";
import { execFile } from "node:child_process";

//#region ../../src/daemon/runtime-paths.ts
const VERSION_MANAGER_MARKERS = [
	"/.nvm/",
	"/.fnm/",
	"/.volta/",
	"/.asdf/",
	"/.n/",
	"/.nodenv/",
	"/.nodebrew/",
	"/nvs/"
];
function getPathModule(platform) {
	return platform === "win32" ? path.win32 : path.posix;
}
function normalizeForCompare(input, platform) {
	const normalized = getPathModule(platform).normalize(input).replaceAll("\\", "/");
	if (platform === "win32") return normalized.toLowerCase();
	return normalized;
}
function buildSystemNodeCandidates(env, platform) {
	if (platform === "darwin") return [
		"/opt/homebrew/bin/node",
		"/usr/local/bin/node",
		"/usr/bin/node"
	];
	if (platform === "linux") return ["/usr/local/bin/node", "/usr/bin/node"];
	if (platform === "win32") {
		const pathModule = getPathModule(platform);
		const programFiles = env.ProgramFiles ?? "C:\\Program Files";
		const programFilesX86 = env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)";
		return [pathModule.join(programFiles, "nodejs", "node.exe"), pathModule.join(programFilesX86, "nodejs", "node.exe")];
	}
	return [];
}
const execFileAsync = promisify(execFile);
async function resolveNodeVersion(nodePath, execFileImpl) {
	try {
		const { stdout } = await execFileImpl(nodePath, ["-p", "process.versions.node"], { encoding: "utf8" });
		const value = stdout.trim();
		return value ? value : null;
	} catch {
		return null;
	}
}
function isVersionManagedNodePath(nodePath, platform = process.platform) {
	const normalized = normalizeForCompare(nodePath, platform);
	return VERSION_MANAGER_MARKERS.some((marker) => normalized.includes(marker));
}
function isSystemNodePath(nodePath, env = process.env, platform = process.platform) {
	const normalized = normalizeForCompare(nodePath, platform);
	return buildSystemNodeCandidates(env, platform).some((candidate) => {
		return normalized === normalizeForCompare(candidate, platform);
	});
}
async function resolveSystemNodePath(env = process.env, platform = process.platform) {
	const candidates = buildSystemNodeCandidates(env, platform);
	for (const candidate of candidates) try {
		await fs.access(candidate);
		return candidate;
	} catch {}
	return null;
}
async function resolveSystemNodeInfo(params) {
	const systemNode = await resolveSystemNodePath(params.env ?? process.env, params.platform ?? process.platform);
	if (!systemNode) return null;
	const version = await resolveNodeVersion(systemNode, params.execFile ?? execFileAsync);
	return {
		path: systemNode,
		version,
		supported: isSupportedNodeVersion(version)
	};
}
function renderSystemNodeWarning(systemNode, selectedNodePath) {
	if (!systemNode || systemNode.supported) return null;
	const versionLabel = systemNode.version ?? "unknown";
	const selectedLabel = selectedNodePath ? ` Using ${selectedNodePath} for the daemon.` : "";
	return `System Node ${versionLabel} at ${systemNode.path} is below the required Node 22+.${selectedLabel} Install Node 22+ from nodejs.org or Homebrew.`;
}
async function resolvePreferredNodePath(params) {
	if (params.runtime !== "node") return;
	const systemNode = await resolveSystemNodeInfo(params);
	if (!systemNode?.supported) return;
	return systemNode.path;
}

//#endregion
//#region ../../src/daemon/service-env.ts
function resolveSystemPathDirs(platform) {
	if (platform === "darwin") return [
		"/opt/homebrew/bin",
		"/usr/local/bin",
		"/usr/bin",
		"/bin"
	];
	if (platform === "linux") return [
		"/usr/local/bin",
		"/usr/bin",
		"/bin"
	];
	return [];
}
/**
* Resolve common user bin directories for Unix-like platforms.
* These are paths where npm global installs, Bun, pnpm, Shad, Cargo,
* and node version managers commonly place binaries.
*/
function resolveUnixUserBinDirs(home, env, platform) {
	if (!home || platform === "win32") return [];
	const dirs = [];
	const add = (dir) => {
		if (dir) dirs.push(dir);
	};
	const appendSubdir = (base, subdir) => {
		if (!base) return;
		return base.endsWith(`/${subdir}`) ? base : path.posix.join(base, subdir);
	};
	add(env?.PNPM_HOME);
	add(appendSubdir(env?.NPM_CONFIG_PREFIX, "bin"));
	add(appendSubdir(env?.BUN_INSTALL, "bin"));
	add(appendSubdir(env?.VOLTA_HOME, "bin"));
	add(appendSubdir(env?.ASDF_DATA_DIR, "shims"));
	add(appendSubdir(env?.NVM_DIR, "current/bin"));
	add(appendSubdir(env?.FNM_DIR, "current/bin"));
	add(appendSubdir(env?.CARGO_HOME, "bin"));
	dirs.push(`${home}/.local/bin`);
	dirs.push(`${home}/bin`);
	dirs.push(`${home}/.bun/bin`);
	dirs.push(`${home}/.cargo/bin`);
	dirs.push(`${home}/.volta/bin`);
	dirs.push(`${home}/.asdf/shims`);
	dirs.push(`${home}/.nvm/current/bin`);
	dirs.push(`${home}/.fnm/current/bin`);
	dirs.push(`${home}/.shad/bin`);
	if (platform === "linux") {
		dirs.push(`${home}/.npm-global/bin`);
		dirs.push(`${home}/.local/share/pnpm`);
	}
	if (platform === "darwin") dirs.push(`${home}/Library/pnpm`);
	return dirs;
}
function getMinimalServicePathParts(options = {}) {
	const platform = options.platform ?? process.platform;
	if (platform === "win32") return [];
	const parts = [];
	const extraDirs = options.extraDirs ?? [];
	const systemDirs = resolveSystemPathDirs(platform);
	const unixUserDirs = resolveUnixUserBinDirs(options.home, options.env, platform);
	const add = (dir) => {
		if (!dir) return;
		if (!parts.includes(dir)) parts.push(dir);
	};
	for (const dir of extraDirs) add(dir);
	for (const dir of unixUserDirs) add(dir);
	for (const dir of systemDirs) add(dir);
	return parts;
}
function getMinimalServicePathPartsFromEnv(options = {}) {
	const env = options.env ?? process.env;
	return getMinimalServicePathParts({
		...options,
		home: options.home ?? env.HOME,
		env
	});
}
function buildMinimalServicePath(options = {}) {
	const env = options.env ?? process.env;
	if ((options.platform ?? process.platform) === "win32") return env.PATH ?? "";
	return getMinimalServicePathPartsFromEnv({
		...options,
		env
	}).join(path.posix.delimiter);
}
function buildServiceEnvironment(params) {
	const { env, port, token, launchdLabel } = params;
	const profile = env.EDWINPAI_PROFILE;
	const resolvedLaunchdLabel = launchdLabel || (process.platform === "darwin" ? resolveGatewayLaunchAgentLabel(profile) : void 0);
	const systemdUnit = `${resolveGatewaySystemdServiceName(profile)}.service`;
	const stateDir = env.EDWINPAI_STATE_DIR?.trim() || resolveGatewayStateDir(env);
	const configPath = env.EDWINPAI_CONFIG_PATH?.trim() || resolveCanonicalConfigPath({
		...env,
		EDWINPAI_STATE_DIR: stateDir
	});
	const shadCollectionPath = env.SHAD_COLLECTION_PATH?.trim() || path.join(stateDir, "workspace");
	return {
		HOME: env.HOME,
		PATH: buildMinimalServicePath({ env }),
		SHAD_COLLECTION_PATH: shadCollectionPath,
		EDWINPAI_PROFILE: profile,
		EDWINPAI_STATE_DIR: stateDir,
		EDWINPAI_CONFIG_PATH: configPath,
		EDWINPAI_GATEWAY_PORT: String(port),
		EDWINPAI_GATEWAY_TOKEN: token,
		EDWINPAI_LAUNCHD_LABEL: resolvedLaunchdLabel,
		EDWINPAI_SYSTEMD_UNIT: systemdUnit,
		EDWINPAI_SERVICE_MARKER: GATEWAY_SERVICE_MARKER,
		EDWINPAI_SERVICE_KIND: GATEWAY_SERVICE_KIND,
		EDWINPAI_SERVICE_VERSION: VERSION
	};
}
function buildNodeServiceEnvironment(params) {
	const { env } = params;
	const stateDir = env.EDWINPAI_STATE_DIR?.trim() || resolveGatewayStateDir(env);
	const configPath = env.EDWINPAI_CONFIG_PATH?.trim() || resolveCanonicalConfigPath({
		...env,
		EDWINPAI_STATE_DIR: stateDir
	});
	const shadCollectionPath = env.SHAD_COLLECTION_PATH?.trim() || path.join(stateDir, "workspace");
	return {
		HOME: env.HOME,
		PATH: buildMinimalServicePath({ env }),
		SHAD_COLLECTION_PATH: shadCollectionPath,
		EDWINPAI_STATE_DIR: stateDir,
		EDWINPAI_CONFIG_PATH: configPath,
		EDWINPAI_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel(),
		EDWINPAI_SYSTEMD_UNIT: resolveNodeSystemdServiceName(),
		EDWINPAI_WINDOWS_TASK_NAME: resolveNodeWindowsTaskName(),
		EDWINPAI_TASK_SCRIPT_NAME: NODE_WINDOWS_TASK_SCRIPT_NAME,
		EDWINPAI_LOG_PREFIX: "node",
		EDWINPAI_SERVICE_MARKER: NODE_SERVICE_MARKER,
		EDWINPAI_SERVICE_KIND: NODE_SERVICE_KIND,
		EDWINPAI_SERVICE_VERSION: VERSION
	};
}

//#endregion
export { isVersionManagedNodePath as a, resolveSystemNodeInfo as c, isSystemNodePath as i, resolveSystemNodePath as l, buildServiceEnvironment as n, renderSystemNodeWarning as o, getMinimalServicePathPartsFromEnv as r, resolvePreferredNodePath as s, buildNodeServiceEnvironment as t };