"""Telemetry context and global state management."""

import threading
from dataclasses import dataclass
from typing import Any, Optional

from thoughtful.supervisor.telemetry.config.builder import TelemetryConfig


@dataclass
class TelemetryContext:
    """Context object holding initialized telemetry components."""

    root_span_cm: Optional[Any] = None
    root_span: Optional[Any] = None
    meter_provider: Optional[Any] = None
    meter: Optional[Any] = None
    config: Optional[TelemetryConfig] = None
    resource: Optional[Any] = None


# Thread-safe global telemetry state management
_context_lock = threading.Lock()
_global_telemetry_context: Optional[TelemetryContext] = None
_telemetry_initialized_early: bool = False
_service_name: str = "supervisor"


def get_service_name() -> str:
    """Get the configured service name."""
    with _context_lock:
        return _service_name


def set_service_name(name: str) -> None:
    """Set the service name for telemetry."""
    global _service_name
    with _context_lock:
        _service_name = name


def get_global_telemetry_context() -> Optional[TelemetryContext]:
    """Get the global telemetry context if it exists."""
    with _context_lock:
        return _global_telemetry_context


def set_global_telemetry_context(context: TelemetryContext) -> None:
    """Set the global telemetry context."""
    global _global_telemetry_context
    with _context_lock:
        _global_telemetry_context = context


def clear_global_telemetry_context() -> None:
    """Clear the global telemetry context."""
    global _global_telemetry_context
    with _context_lock:
        _global_telemetry_context = None


def was_telemetry_initialized_early() -> bool:
    """Check if telemetry was initialized via init_supervision()."""
    with _context_lock:
        return _telemetry_initialized_early


def mark_telemetry_initialized_early() -> None:
    """Mark that telemetry was initialized early (before agent imports)."""
    global _telemetry_initialized_early
    with _context_lock:
        _telemetry_initialized_early = True


def reset_telemetry_early_flag() -> None:
    """Reset the early initialization flag. Used for testing."""
    global _telemetry_initialized_early
    with _context_lock:
        _telemetry_initialized_early = False
