import { getMonitoringConfig } from './config';

let initialized = false;

export function initDatadog() {
  if (initialized) return;

  const config = getMonitoringConfig();

  if (config.DD_TRACE_ENABLED !== 'true') {
    console.log('[Datadog] APM tracing disabled');
    return;
  }

  try {
    const tracer = require('dd-trace').init({
      service: config.DD_SERVICE,
      env: config.DD_ENV,
      version: config.DD_VERSION,
      sampleRate: config.DD_TRACE_SAMPLE_RATE,
      logInjection: config.DD_LOGS_INJECTION === 'true',
      agentHost: config.DD_AGENT_HOST,
      agentPort: config.DD_AGENT_PORT,
      plugins: true,
      debug: config.DD_ENV === 'development',
    });

    initialized = true;
    console.log(`[Datadog] APM initialized for service "${config.DD_SERVICE}" in "${config.DD_ENV}"`);
    return tracer;
  } catch (err) {
    console.warn('[Datadog] APM initialization skipped:', (err as Error).message);
  }
}

export function getDatadogTracer() {
  try {
    return require('dd-trace').tracer;
  } catch {
    return null;
  }
}

export function createDatadogSpan(name: string, options?: Record<string, unknown>) {
  const tracer = getDatadogTracer();
  if (!tracer) return;

  return tracer.startChild(name, options);
}
