import { a as unregisterAcpRuntimeBackend, n as registerAcpRuntimeBackend, t as getAcpRuntimeBackend } from "./registry-ChKH2B-n.js";
import "./acp-runtime-backend-DiBTNPo0.js";
import { t as createLazyAcpRuntimeProxy } from "./runtime-proxy-B5Q8EtBN.js";
//#region extensions/acpx/register.runtime.ts
const ACPX_BACKEND_ID = "acpx";
let serviceModulePromise = null;
function loadServiceModule() {
	serviceModulePromise ??= import("./service-BAVGGrEk.js");
	return serviceModulePromise;
}
async function startRealService(state) {
	if (state.realRuntime) return state.realRuntime;
	if (!state.ctx) throw new Error("ACPX runtime service is not started");
	state.startPromise ??= (async () => {
		const { createAcpxRuntimeService: createAcpxRuntimeServiceLocal } = await loadServiceModule();
		const service = createAcpxRuntimeServiceLocal(state.params);
		state.realService = service;
		await service.start(state.ctx);
		const backend = getAcpRuntimeBackend(ACPX_BACKEND_ID);
		if (!backend?.runtime) throw new Error("ACPX runtime service did not register an ACP backend");
		state.realRuntime = backend.runtime;
		return state.realRuntime;
	})();
	try {
		return await state.startPromise;
	} catch (error) {
		state.startPromise = null;
		state.realService = null;
		throw error;
	}
}
function createDeferredRuntime(state) {
	const resolveRuntime = () => startRealService(state);
	return createLazyAcpRuntimeProxy(resolveRuntime);
}
function createAcpxRuntimeService(params = {}) {
	const state = {
		ctx: null,
		params,
		realRuntime: null,
		realService: null,
		startPromise: null
	};
	return {
		id: "acpx-runtime",
		async start(ctx) {
			if (process.env.DEX_SKIP_ACPX_RUNTIME === "1") {
				ctx.logger.info("skipping embedded acpx runtime backend (DEX_SKIP_ACPX_RUNTIME=1)");
				return;
			}
			state.ctx = ctx;
			registerAcpRuntimeBackend({
				id: ACPX_BACKEND_ID,
				runtime: createDeferredRuntime(state)
			});
			ctx.logger.info("embedded acpx runtime backend registered lazily");
		},
		async stop(ctx) {
			if (state.realService) await state.realService.stop?.(ctx);
			else unregisterAcpRuntimeBackend(ACPX_BACKEND_ID);
			state.ctx = null;
			state.realRuntime = null;
			state.realService = null;
			state.startPromise = null;
		}
	};
}
//#endregion
export { createAcpxRuntimeService as t };
