import { getLogger } from "../utils/logger.js";
import { SpanEventMapper } from "./mapper.js";
import { AmplitudeEventSpanProcessor } from "./processor.js";
import { createRequire } from "node:module";

//#region src/otel/setup.ts
/**
* Internal setup logic for AmplitudeAI.enableOtel().
*/
const _require = createRequire(import.meta.url);
const logger = getLogger();
function setupOtel(options) {
	let api;
	let TracerProviderCtor;
	try {
		api = _require("@opentelemetry/api");
		TracerProviderCtor = _require("@opentelemetry/sdk-trace-base").BasicTracerProvider;
	} catch {
		throw new Error("OpenTelemetry SDK is not installed. Install with: npm install @opentelemetry/api @opentelemetry/sdk-trace-base");
	}
	const mapper = new SpanEventMapper({
		amplitude: options.amplitude,
		defaultUserId: options.defaultUserId,
		defaultDeviceId: options.defaultDeviceId,
		privacyConfig: options.privacyConfig
	});
	const processor = new AmplitudeEventSpanProcessor(mapper);
	const spanProcessors = [processor];
	if (options.otelEndpoint) try {
		const otlpExporter = new (_require("@opentelemetry/exporter-trace-otlp-grpc")).OTLPTraceExporter({ url: options.otelEndpoint });
		const BatchSpanProcessorCtor = _require("@opentelemetry/sdk-trace-base").BatchSpanProcessor;
		spanProcessors.push(new BatchSpanProcessorCtor(otlpExporter));
		logger.info(`OTLP dual export enabled: ${options.otelEndpoint}`);
	} catch {
		logger.warn("OTLP exporter not installed. Install with: npm install @opentelemetry/exporter-trace-otlp-grpc");
	}
	const existingProvider = api.trace.getTracerProvider();
	const delegate = existingProvider._delegate;
	const isExistingBasic = delegate?.constructor?.name === "BasicTracerProvider" || delegate?.constructor?.name === "NodeTracerProvider" || existingProvider.constructor?.name === "BasicTracerProvider" || existingProvider.constructor?.name === "NodeTracerProvider";
	let provider;
	if (isExistingBasic) {
		const target = delegate ?? existingProvider;
		const existingProcessors = target._registeredSpanProcessors;
		if (Array.isArray(existingProcessors) && existingProcessors.some((p) => p instanceof AmplitudeEventSpanProcessor)) {
			logger.debug("AmplitudeEventSpanProcessor already registered — skipping duplicate");
			provider = target;
		} else if (typeof target.addSpanProcessor === "function") {
			for (const sp of spanProcessors) target.addSpanProcessor(sp);
			provider = target;
		} else {
			provider = new TracerProviderCtor({ spanProcessors });
			api.trace.setGlobalTracerProvider(provider);
		}
	} else {
		provider = new TracerProviderCtor({ spanProcessors });
		api.trace.setGlobalTracerProvider(provider);
	}
	return {
		provider,
		mapper,
		processor
	};
}

//#endregion
export { setupOtel };
//# sourceMappingURL=setup.js.map