from __future__ import annotations

import logging

from .config import Config
from .provider import Tracer, TracerProvider
from .transport import BatchTransport

logger = logging.getLogger("staso")

_global_client: Client | None = None


class Client:
    """Core SDK client -- manages configuration, provider, and transport."""

    def __init__(self, config: Config) -> None:
        self._config = config
        self._transport: BatchTransport | None = None
        if config.enabled:
            self._transport = BatchTransport(
                base_url=config.base_url,
                api_key=config.api_key,
                batch_size=config.batch_size,
                flush_interval=config.flush_interval,
                max_queue_size=config.max_queue_size,
                environment=config.environment,
                workspace_slug=config.workspace_slug,
            )
        self._provider = TracerProvider(
            transport=self._transport,
            agent_id=config.agent_id,
            enabled=config.enabled,
        )

        if config.debug:
            logging.getLogger("staso").setLevel(logging.DEBUG)

    @property
    def config(self) -> Config:
        return self._config

    @property
    def provider(self) -> TracerProvider:
        return self._provider

    def shutdown(self) -> None:
        """Flush pending spans and stop the background transport."""
        self._provider.shutdown()
        from .annotation import shutdown_annotation_client
        shutdown_annotation_client()


def get_client() -> Client | None:
    """Return the globally initialised client, or ``None``."""
    return _global_client


def _set_client(client: Client) -> None:
    global _global_client
    _global_client = client


def get_tracer() -> Tracer:
    """Return a Tracer from the global client, or a noop tracer."""
    client = _global_client
    if client:
        return client.provider.get_tracer()
    # Return a tracer that creates non-recording spans
    return TracerProvider(transport=None, agent_id="", enabled=False).get_tracer()
