// Package observability also bootstraps OpenTelemetry tracing. The tracer is
// initialized via shared-go/tracer so push-gateway and api-gateway share the
// same SDK configuration.
package observability

import (
	"context"
	"fmt"
	"os"

	"github.com/edu-cloud/shared-go/tracer"
)

// InitTracer initializes the OTel tracer using shared-go/tracer. When the
// OTLP endpoint is empty (or "localhost:4318") the exporter still runs but
// emits no spans if no collector is listening. Returns a shutdown function
// that must be called on process exit.
func InitTracer(serviceName, endpoint string) func() {
	// shared-go/tracer reads OTEL_EXPORTER_OTLP_ENDPOINT directly; override it
	// explicitly so push-gateway's own config value takes precedence.
	if endpoint != "" {
		_ = os.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint)
	}
	if err := tracer.Init(serviceName); err != nil {
		// Tracing is best-effort: log and continue without a tracer rather than
		// failing the whole process.
		fmt.Fprintf(os.Stderr, "push-gateway: tracer init failed: %v (tracing disabled)\n", err)
		return func() {}
	}
	return func() {
		if err := tracer.Shutdown(context.Background()); err != nil {
			fmt.Fprintf(os.Stderr, "push-gateway: tracer shutdown failed: %v\n", err)
		}
	}
}
