from opentelemetry.sdk.trace import TracerProvider
from opentelemetry import trace
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

from obs.utils.config import get_env
import base64

_initialized = False

def init_tracer():

  global _initialized

  if _initialized:
    return trace.get_tracer_provider()

  provider = TracerProvider()
  trace.set_tracer_provider(provider)

  host = get_env("LANGFUSE_HOST")
  pk = get_env("LANGFUSE_PUBLIC_KEY")
  sk = get_env("LANGFUSE_SECRET_KEY")

  creds = f"{pk}:{sk}"
  encoded = base64.b64encode(creds.encode()).decode()

  headers = {
    "Authorization": f"Basic {encoded}"
  }

  langfuse_exporter = OTLPSpanExporter(
    endpoint=f"{host}/api/public/otel/v1/traces",
    headers=headers
  )

  provider.add_span_processor(BatchSpanProcessor(langfuse_exporter))

  phoenix_exporter = OTLPSpanExporter(
    endpoint=get_env("PHOENIX_ENDPOINT")
  )

  provider.add_span_processor(BatchSpanProcessor(phoenix_exporter))

  print("🚀 OBS SDK INITIALIZED")

  _initialized = True

  return provider