// ═══════════════════════════════════════════════════════════
// 🔭 OpenTelemetry Tracing Setup for Ophion
// ═══════════════════════════════════════════════════════════
//
// This file initializes OpenTelemetry tracing and sends spans
// to Ophion's OTLP HTTP endpoint.
//
// Usage: node --require ./tracing.js app.js

const { NodeSDK } = require('@opentelemetry/sdk-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');

// Configure the OTLP exporter to send to Ophion
const traceExporter = new OTLPTraceExporter({
  // Ophion OTLP endpoint - adjust host/port as needed
  url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:8080/v1/traces',
  headers: {
    // Optional: add authorization if Ophion requires it
    // 'Authorization': `Bearer ${process.env.OPHION_API_KEY}`,
  },
});

// Create the SDK with auto-instrumentation
const sdk = new NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || 'nodejs-example',
    [SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0',
    [SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]: process.env.NODE_ENV || 'development',
  }),
  traceExporter,
  instrumentations: [
    getNodeAutoInstrumentations({
      // Disable fs instrumentation to reduce noise
      '@opentelemetry/instrumentation-fs': { enabled: false },
    }),
  ],
});

// Start the SDK
sdk.start();
console.log('🔭 OpenTelemetry tracing initialized - sending to Ophion');

// Graceful shutdown
process.on('SIGTERM', () => {
  sdk.shutdown()
    .then(() => console.log('OpenTelemetry SDK shut down'))
    .catch((error) => console.error('Error shutting down SDK', error))
    .finally(() => process.exit(0));
});
