from contextlib import contextmanager

from swarmauri_standard.tracing.SimpleTracer import SimpleTracer
from swarmauri_standard.tracing.TracedVariable import TracedVariable

# Initialize a global instance of SimpleTracer for use across the application
global_tracer = SimpleTracer()


@contextmanager
def VariableTracer(name: str, initial_value=None):
    """
    Context manager for tracing the declaration, modification, and usage of a variable.
    """
    global_tracer.start_trace(
        name=f"Variable: {name}", initial_attributes={"initial_value": initial_value}
    )
    traced_variable = TracedVariable(name, initial_value, global_tracer)

    try:
        yield traced_variable
    finally:
        # Optionally record any final value or state of the variable before it goes out of scope
        global_tracer.annotate_trace(
            key=f"{name}_final", value={"final_value": traced_variable.value}
        )
        # End the trace, marking the variable's lifecycle
        global_tracer.end_trace()
