from contextlib import contextmanager
import time
import uuid

class Tool:

  def init(self, tools=None):

    from obs.utils.otel import init_tracer
    from obs.tools import (
      LangfuseTool,
      PhoenixTool,
      LangSmithTool,
      SentryTool
    )

    init_tracer()

    if tools is None:
      tools = [
        LangfuseTool(),
        PhoenixTool(),
        LangSmithTool(),
        SentryTool()
      ]

    self.tools = tools

    for t in self.tools:
      try:
        t.init()
      except Exception as e:
        print(f"[OBS INIT ERROR] {t.__class__.__name__}: {e}")


  @contextmanager
  def trace(self, name, input=None):

    trace_id = str(uuid.uuid4())
    start_time = time.time()
    error = None

    class TraceObj:
      output = None

    t = TraceObj()

    try:
      yield t
    except Exception as e:
      error = str(e)
      raise e
    finally:
      end_time = time.time()

      for tool in self.tools:
        try:
          tool.push(
            trace_id=trace_id,
            name=name,
            input=input,
            output=t.output,
            start_time=start_time,
            end_time=end_time,
            error=error
          )
        except Exception as e:
          print(f"[OBS ERROR] {tool.__class__.__name__}: {e}")