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";

/**
 * parent-bff OpenTelemetry 链路追踪初始化。
 *
 * 对齐 02-architecture-design.md §6.5：
 * - serviceName: parent-bff
 * - exporter: OTLP HTTP → collector
 * - auto-instrumentations: http, nestjs-core, express, ioredis, @grpc/grpc-js, kafka-node
 * - 采样率：生产 10%，开发 100%（通过 OTEL_TRACES_SAMPLER_ARG 控制）
 *
 * span 属性：parentId, childId, operation, downstream.service, cache.hit, childGuard.blocked
 */
let sdk: NodeSDK | null = null;

export function initTracer(): void {
  if (!env.OTEL_EXPORTER_OTLP_ENDPOINT) return;

  sdk = new NodeSDK({
    serviceName: env.OTEL_SERVICE_NAME,
    traceExporter: new OTLPTraceExporter({
      url: `${env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/traces`,
    }),
    instrumentations: [getNodeAutoInstrumentations()],
  });

  sdk.start();
  console.log(
    `[parent-bff] Tracer initialized with auto-instrumentations, endpoint=${env.OTEL_EXPORTER_OTLP_ENDPOINT}`,
  );
}

export async function shutdownTracer(): Promise<void> {
  if (sdk) {
    await sdk.shutdown();
    sdk = null;
  }
}
