<?php
/**
 * OPHION PHP OpenTelemetry Initialization
 * Include this file in your application bootstrap
 */

use OpenTelemetry\SDK\Sdk;
use OpenTelemetry\SDK\Trace\TracerProvider;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
use OpenTelemetry\SDK\Common\Export\Http\PsrTransportFactory;
use OpenTelemetry\SDK\Resource\ResourceInfo;
use OpenTelemetry\SDK\Common\Attribute\Attributes;

$endpoint = getenv('OTEL_EXPORTER_OTLP_ENDPOINT') ?: 'http://localhost:4318';
$serviceName = getenv('OTEL_SERVICE_NAME') ?: 'php-app';

try {
    $transport = (new PsrTransportFactory())->create($endpoint . '/v1/traces', 'application/json');
    $exporter = new SpanExporter($transport);
    $tracerProvider = TracerProvider::builder()
        ->addSpanProcessor(new SimpleSpanProcessor($exporter))
        ->setResource(ResourceInfo::create(Attributes::create(['service.name' => $serviceName])))
        ->build();
    Sdk::builder()->setTracerProvider($tracerProvider)->buildAndRegisterGlobal();
    error_log('[OPHION] OpenTelemetry initialized for PHP');
} catch (Exception $e) {
    error_log('[OPHION] Failed to initialize OpenTelemetry: ' . $e->getMessage());
}
