/**
 * student-bff OpenTelemetry tracer.
 *
 * 仲裁依据: coord-final-decisions §1 G6 (首次实现即 OTel SDK + OTLP exporter + 完整资源属性 + 全链路 span)
 *           02-architecture-design.md §6.5 (serviceName: student-bff)
 */
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 | null = null;

export function initTracer(): void {
  if (!env.OTEL_EXPORTER_OTLP_ENDPOINT) {
    logger.warn("OTEL_EXPORTER_OTLP_ENDPOINT not set, tracer disabled");
    return;
  }

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

  sdk.start();
  logger.info(
    { endpoint: env.OTEL_EXPORTER_OTLP_ENDPOINT, service: env.OTEL_SERVICE_NAME },
    "Tracer initialized with auto-instrumentations",
  );
}

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