# ---------------------------------------------------------------------------
# Minimal debugging shim to avoid importing v0.relationalai (which pulls in
# Snowflake packages and adds ~500ms import overhead).
# This shim mimics the essential functionality of v0.relationalai.debugging
# so that tests using the Capturer handler can still capture span events.
# ---------------------------------------------------------------------------
import logging as _logging
import uuid as _uuid
import time as _pytime
import contextlib as _contextlib
from typing import Generator as _Generator

_debug_logger = _logging.getLogger("pyrellogger")
_debug_logger.setLevel(_logging.DEBUG)
_debug_logger.propagate = False  # Prevent double logging if root logger is configured

class _DebugSpan:
    """Span that mimics v0.relationalai.debugging.Span."""

    def __init__(self, type_: str, attrs: dict):
        self.id = _uuid.uuid4()
        self.type = type_
        self.attrs = attrs
        self.end_attrs: dict = {}
        self.precise_start = _pytime.perf_counter()

    def __setitem__(self, key, value):
        self.end_attrs[key] = value

    def __getitem__(self, key):
        return self.end_attrs.get(key)

    def update(self, attrs: dict):
        if attrs:
            self.end_attrs.update(attrs)
        return self


class _DebugShim:
    """Minimal shim for v0.relationalai.debugging."""

    @staticmethod
    @_contextlib.contextmanager
    def span(type_: str, tag=None, export_to: str = "", **kwargs) -> _Generator[_DebugSpan, None, None]:
        span = _DebugSpan(type_, kwargs)

        # Emit span_start event
        msg = {"event": "span_start", "span": span}
        _debug_logger.debug(msg, msg)

        try:
            yield span
        finally:
            # Emit span_end event
            elapsed = _pytime.perf_counter() - span.precise_start
            msg = {
                "event": "span_end",
                "id": str(span.id),
                "elapsed": elapsed,
                "end_attrs": span.end_attrs,
            }
            _debug_logger.debug(msg, msg)


_debugging_shim = _DebugShim()

def span(type_: str, **kwargs):
    return _debugging_shim.span(type_, **kwargs)
