import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { env } from "../../config/env.js";
import { logger } from "./logger.js";

let sdk: NodeSDK | undefined;

export function initTracer(): void {
  if (!env.OTEL_EXPORTER_OTLP_ENDPOINT) {
    logger.warn("OTEL_EXPORTER_OTLP_ENDPOINT not set, tracing disabled");
    return;
  }
  sdk = new NodeSDK({
    serviceName: "core-edu",
    traceExporter: new OTLPTraceExporter({
      url: `${env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/traces`,
    }),
    instrumentations: [getNodeAutoInstrumentations()],
  });
  sdk.start();
  logger.info("OpenTelemetry tracer initialized with auto-instrumentations");
}

export async function shutdownTracer(): Promise<void> {
  if (sdk) {
    await sdk.shutdown();
    sdk = undefined;
    logger.info("OpenTelemetry tracer shutdown");
  }
}
