import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
import { ZoneContextManager } from '@opentelemetry/context-zone';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';

const exporter = new OTLPTraceExporter({
    url: `${window.location.origin}/otel/v1/traces`
});

const provider = new WebTracerProvider({
    resource: resourceFromAttributes({
        [ATTR_SERVICE_NAME]: 'magistr-frontend'
    }),
    spanProcessors: [new BatchSpanProcessor(exporter)]
});

provider.register({
    contextManager: new ZoneContextManager()
});

registerInstrumentations({
    instrumentations: [
        getWebAutoInstrumentations({
            '@opentelemetry/instrumentation-fetch': {
                propagateTraceHeaderCorsUrls: [window.location.origin],
                clearTimingResources: true
            },
            '@opentelemetry/instrumentation-xml-http-request': {
                propagateTraceHeaderCorsUrls: [window.location.origin],
                clearTimingResources: true
            }
        })
    ]
});

console.info('Браузерная телеметрия OpenTelemetry инициализирована');
