import { ConfigSchema, init_schema } from "../../config/schema.js";
import { init_loader, loadConfig, saveConfig } from "../../config/loader.js";
import { randomBytes } from "node:crypto";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
//#region src/cli/utils/init-workspace-core.ts
init_schema();
init_loader();
async function assertChannelPluginsIfNeeded(cfg, assert) {
	if (assert) await assert(cfg);
}
async function serializeConfig(cfg, assertChannelPlugins) {
	const validated = ConfigSchema.parse(cfg);
	await assertChannelPluginsIfNeeded(validated, assertChannelPlugins);
	return JSON.stringify(validated, null, 2);
}
async function tryReadDiskConfig(configPath, assertChannelPlugins) {
	try {
		const raw = readFileSync(configPath, "utf-8");
		const cfg = ConfigSchema.parse(JSON.parse(raw));
		await assertChannelPluginsIfNeeded(cfg, assertChannelPlugins);
		return cfg;
	} catch {
		return null;
	}
}
/**
* Workspace + config initialisation without importing bundled channel plugins.
* Used by Electron main; CLI/gateway should call {@link initWorkspace} instead.
*/
async function initWorkspaceCore(options) {
	const gatewayPortDefaulted = options.gatewayPort ?? 18790;
	const persistWorkspacePath = options.persistWorkspacePath ?? false;
	const { configPath, workspacePath, assertChannelPlugins } = options;
	const persistedDefaultsWorkspace = persistWorkspacePath ? dirname(workspacePath) : void 0;
	mkdirSync(dirname(configPath), { recursive: true });
	const configExisted = existsSync(configPath);
	const workspaceExisted = existsSync(workspacePath);
	let config;
	if (configExisted) config = loadConfig(configPath);
	else {
		config = ConfigSchema.parse(void 0);
		await assertChannelPluginsIfNeeded(config, assertChannelPlugins);
	}
	mkdirSync(workspacePath, { recursive: true });
	mkdirSync(join(workspacePath, "memory"), { recursive: true });
	const configCreated = !configExisted;
	const workspaceCreated = !workspaceExisted;
	const token = config.gateway?.auth?.mode === "token" && typeof config.gateway?.auth?.token === "string" && config.gateway.auth.token.length > 0 ? config.gateway.auth.token : randomBytes(24).toString("hex");
	const port = configExisted ? config.gateway?.port ?? gatewayPortDefaulted : options.gatewayPort !== void 0 ? gatewayPortDefaulted : config.gateway?.port ?? 18790;
	const agentsDefaults = {
		...config.agents.defaults,
		...persistedDefaultsWorkspace !== void 0 ? { workspace: persistedDefaultsWorkspace } : {}
	};
	const nextConfig = {
		...config,
		agents: {
			...config.agents,
			defaults: agentsDefaults
		},
		gateway: {
			...config.gateway,
			port,
			auth: {
				...config.gateway?.auth,
				mode: "token",
				token
			}
		}
	};
	const nextFinal = ConfigSchema.parse(nextConfig);
	await assertChannelPluginsIfNeeded(nextFinal, assertChannelPlugins);
	let needsWrite = configCreated;
	if (!needsWrite) {
		const disk = await tryReadDiskConfig(configPath, assertChannelPlugins);
		if (!disk) needsWrite = true;
		else needsWrite = await serializeConfig(disk, assertChannelPlugins) !== await serializeConfig(nextFinal, assertChannelPlugins);
	}
	if (needsWrite) await saveConfig(nextFinal, configPath);
	return {
		config: nextFinal,
		token,
		configCreated,
		workspaceCreated
	};
}
//#endregion
export { initWorkspaceCore };

//# sourceMappingURL=init-workspace-core.js.map