import threading

import pytest

from cascade import tracing
import cascade.tracing as tracing_module


def test_session_id_is_thread_local(reset_tracing_state):
    tracing.set_session_id("main-session")
    observed = {"thread": None}

    def worker():
        observed["thread"] = tracing.get_session_id()
        tracing.set_session_id("thread-session")

    t = threading.Thread(target=worker)
    t.start()
    t.join()

    # contextvars do not automatically propagate to new threads
    assert observed["thread"] is None
    assert tracing.get_session_id() == "main-session"


def test_trace_session_restores_previous_session(reset_tracing_state, monkeypatch, fake_tracer):
    # Use fake tracer to avoid OTLP export/network calls.
    monkeypatch.setattr(tracing_module, "_tracer", fake_tracer)
    monkeypatch.setattr(tracing_module.trace, "get_current_span", lambda: fake_tracer.current_span)
    tracing.set_session_id("outer")

    captured = []

    def fake_send_trace_start(**kwargs):
        captured.append(kwargs.get("session_id"))

    monkeypatch.setattr(tracing, "_send_trace_start", fake_send_trace_start)

    with tracing.trace_session("inner"):
        with tracing.trace_run("Inside"):
            pass

    with tracing.trace_run("Outside"):
        pass

    assert captured == ["inner", "outer"]
