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, formatGatewayServiceDescription } from "./constants.js";
import { existsSync } from "node:fs";
import path from "node:path";
import { homedir } from "node:os";
//#region src/daemon/install-plan.ts
/**
* Install Plan Builder - Build gateway installation configuration
*
* Aligned with OpenClaw: adds XOPC_SERVICE_VERSION, StandardOut/ErrorPath,
* supports binary runtime detection, and --foreground arg passing.
*/
init_logger();
init_package_version();
const log = createLogger("InstallPlan");
function resolveDefaultConfigPath() {
	const envConfig = process.env.XOPC_CONFIG || process.env.XOPC_CONFIG_PATH;
	if (envConfig) return envConfig;
	return path.join(homedir(), ".xopc", "xopc.json");
}
function resolveDefaultWorkspace() {
	const envWorkspace = process.env.XOPC_WORKSPACE;
	if (envWorkspace) return envWorkspace;
	return path.join(homedir(), ".xopc", "workspace");
}
function resolveLogDir() {
	return path.join(homedir(), ".xopc", "logs");
}
function isSEABinary() {
	return !!process.pkg || process.execPath.endsWith("xopc") || process.execPath.endsWith("xopc.exe");
}
function resolveEntryPoint() {
	if (isSEABinary()) return process.execPath;
	const thisDir = path.dirname(new URL(import.meta.url).pathname);
	const sourceEntryPoint = path.join(thisDir, "..", "cli", "bin.ts");
	if (existsSync(sourceEntryPoint)) return sourceEntryPoint;
	return path.join(thisDir, "..", "cli", "bin.js");
}
function resolveServiceNodeArgs() {
	const serviceNodeArgs = [];
	const skipValueFlags = new Set([
		"-e",
		"--eval",
		"-p",
		"--print",
		"--test-name-pattern"
	]);
	for (let index = 0; index < process.execArgv.length; index += 1) {
		const arg = process.execArgv[index];
		if (!arg) continue;
		if (arg.startsWith("--inspect") || arg.startsWith("--debug")) continue;
		if (skipValueFlags.has(arg)) {
			index += 1;
			continue;
		}
		if ([...skipValueFlags].some((flag) => arg.startsWith(`${flag}=`))) continue;
		serviceNodeArgs.push(arg);
	}
	return serviceNodeArgs;
}
function buildGatewayInstallPlan(params) {
	const configPath = resolveDefaultConfigPath();
	const workspace = resolveDefaultWorkspace();
	const version = params.version || PACKAGE_VERSION;
	let programArguments;
	if (params.runtime === "binary" || isSEABinary()) programArguments = [
		process.execPath,
		"gateway",
		"--foreground",
		"--port",
		params.port.toString()
	];
	else {
		const nodeArgs = resolveServiceNodeArgs();
		const entryPoint = resolveEntryPoint();
		programArguments = [
			process.execPath,
			...nodeArgs,
			entryPoint,
			"gateway",
			"--foreground",
			"--port",
			params.port.toString()
		];
	}
	if (params.bind && params.bind !== "loopback") programArguments.push("--bind", params.bind);
	const environment = {
		XOPC_CONFIG: configPath,
		XOPC_WORKSPACE: workspace,
		XOPC_LOG_LEVEL: process.env.XOPC_LOG_LEVEL || "info",
		XOPC_LOG_FILE: "true",
		XOPC_LOG_CONSOLE: "false",
		XOPC_LOG_DIR: resolveLogDir(),
		[SERVICE_VERSION_ENV_KEY]: version,
		XOPC_SERVICE_MARKER: "1"
	};
	if (params.token) environment.XOPC_GATEWAY_TOKEN = params.token;
	for (const key of [
		"OPENAI_API_KEY",
		"ANTHROPIC_API_KEY",
		"GOOGLE_API_KEY",
		"BRAVE_API_KEY",
		"DASHSCOPE_API_KEY",
		"XOPC_LOG_RETENTION_DAYS"
	]) if (process.env[key]) environment[key] = process.env[key];
	if (params.env) {
		for (const [key, value] of Object.entries(params.env)) if (value !== void 0 && !key.startsWith("XOPC_")) environment[key] = value;
	}
	const description = formatGatewayServiceDescription({
		profile: params.env?.XOPC_PROFILE?.trim() || void 0,
		version
	});
	log.info({
		programArguments: programArguments.slice(0, 3),
		envKeys: Object.keys(environment),
		version
	}, "Built gateway install plan");
	return {
		programArguments,
		workingDirectory: path.dirname(configPath),
		environment,
		description
	};
}
function buildGatewayInstallArgs(params) {
	const plan = buildGatewayInstallPlan(params);
	return {
		env: params.env || process.env,
		programArguments: plan.programArguments,
		workingDirectory: plan.workingDirectory,
		environment: plan.environment,
		description: plan.description
	};
}
/** Check if the program in an install plan still exists on disk */
function validateInstallPlanProgram(programArguments) {
	if (programArguments.length === 0) return false;
	const program = programArguments[0];
	return existsSync(program);
}
//#endregion
export { buildGatewayInstallArgs, buildGatewayInstallPlan, validateInstallPlanProgram };

//# sourceMappingURL=install-plan.js.map