"""Shared fixtures for Staso SDK tests."""
from __future__ import annotations

import pytest
from opentelemetry import trace as otel_trace

import staso as st
from staso.client import _set_client
from staso.provider import TracerProvider, session_id_var

# Initialize once for the entire test session — OTel only allows one set_tracer_provider call.
_test_transport = None
_provider_installed = False


def install_test_provider():
    """Install a TracerProvider with a swappable transport, once per process."""
    global _provider_installed
    if _provider_installed:
        return
    provider = TracerProvider(transport=None, agent_id="test-agent")
    otel_trace.set_tracer_provider(provider)
    _provider_installed = True


def get_test_provider() -> TracerProvider:
    return otel_trace.get_tracer_provider()  # type: ignore[return-value]


@pytest.fixture(autouse=True)
def _clean_global_state():
    """Reset global SDK state between tests."""
    install_test_provider()
    yield
    client = st.get_client()
    if client and client._transport:
        try:
            client._transport.shutdown()
        except Exception:
            pass
    _set_client(None)  # type: ignore[arg-type]
    # Reset session and provider transport
    session_id_var.set("")
    get_test_provider()._transport = None


@pytest.fixture
def capturing(mocker):
    """Set up a mock transport that captures enqueued span dicts.

    Returns a list; each call to transport.enqueue(span_dict) appends to it.
    Installs the mock transport into the global TracerProvider.
    """
    captured: list[dict] = []
    transport = mocker.MagicMock()
    transport.enqueue.side_effect = lambda d: captured.append(d)

    provider = get_test_provider()
    provider._transport = transport
    provider._agent_id = "test-agent"
    return captured
