"""Singleton access to the default Mingx client."""

import atexit
from threading import Lock
from typing import Optional

from mingx._client.client import MingxClient

_lock = Lock()
_default_client: Optional[MingxClient] = None


def _flush_on_exit() -> None:
    """Flush pending spans when the process exits (so short scripts don't need manual flush)."""
    if _default_client is not None:
        _default_client.flush()


def get_client(
    *,
    endpoint: Optional[str] = None,
    token: Optional[str] = None,
) -> MingxClient:
    """Return the default global MingxClient, creating it on first call.
    On first creation, endpoint and token are passed to MingxClient (OTLP receiver URL and Basic auth token).
    Later calls ignore these arguments.
    """
    global _default_client
    with _lock:
        if _default_client is None:
            _default_client = MingxClient(endpoint=endpoint, token=token)
            atexit.register(_flush_on_exit)
        return _default_client
