import 'dotenv/config';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto';
import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { NestInstrumentation } from '@opentelemetry/instrumentation-nestjs-core';

/**
 * Export OTLP des traces et des logs vers OTEL_EXPORTER_OTLP_ENDPOINT
 * (les exporters lisent eux-mêmes cette variable, ainsi que
 * OTEL_EXPORTER_OTLP_HEADERS pour l'auth, et ajoutent /v1/traces et /v1/logs).
 *
 * En local : OpenObserve (projet « observability »), http://localhost:5080/api/default,
 * auth Basic via un service account dédié. En prod : pointer la variable vers le
 * backend choisi, sans toucher au code.
 *
 * Ce fichier doit rester le PREMIER import de main.ts : l'instrumentation HTTP
 * patche le module `http` de Node avant que Fastify ne le charge.
 * Sans endpoint configuré (tests, dev sans serveur), aucun export ni bruit réseau.
 */
if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {
  // Le NodeSDK active l'export OTLP des métriques par défaut dès qu'un endpoint
  // est défini (OTEL_METRICS_EXPORTER vaut « otlp » selon la spec). Les métriques
  // HTTP (http_server_duration_*) ne sont pas exploitées et représentaient
  // l'essentiel de l'ingestion OpenObserve — on ne garde que traces et logs.
  process.env.OTEL_METRICS_EXPORTER ??= 'none';

  const sdk = new NodeSDK({
    traceExporter: new OTLPTraceExporter(),
    logRecordProcessors: [
      new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),
    ],
    instrumentations: [
      new HttpInstrumentation({
        ignoreIncomingRequestHook: (req) =>
          (req.url ?? '').startsWith('/health'),
      }),
      new NestInstrumentation(),
    ],
  });

  sdk.start();

  process.on('SIGTERM', () => {
    sdk.shutdown().finally(() => process.exit(0));
  });
}
