"""Global SDK state — singleton buffer and processor."""
from __future__ import annotations

import threading
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from fibinaci.buffer.batch_processor import BatchProcessor
    from fibinaci.buffer.memory_buffer import MemoryBuffer
    from fibinaci._config import FibinaciConfig

_lock = threading.Lock()
_config: FibinaciConfig | None = None
_buffer: MemoryBuffer | None = None
_processor: BatchProcessor | None = None
_initialized = False


def init_globals(config: FibinaciConfig) -> None:
    global _config, _buffer, _processor, _initialized
    with _lock:
        if _initialized:
            return
        from fibinaci.buffer.memory_buffer import MemoryBuffer
        from fibinaci.buffer.batch_processor import BatchProcessor

        _config = config
        _buffer = MemoryBuffer(max_size=config.max_buffer_size)
        _processor = BatchProcessor(config=config, buffer=_buffer)
        _processor.start()
        _initialized = True


def get_config() -> FibinaciConfig:
    if _config is None:
        from fibinaci._config import FibinaciConfig
        init_globals(FibinaciConfig())
    return _config  # type: ignore[return-value]


def get_buffer() -> MemoryBuffer:
    if _buffer is None:
        get_config()  # triggers init
    return _buffer  # type: ignore[return-value]


def get_processor() -> BatchProcessor:
    if _processor is None:
        get_config()  # triggers init
    return _processor  # type: ignore[return-value]


def shutdown() -> None:
    global _processor, _buffer, _initialized
    with _lock:
        if _processor is not None:
            _processor.stop()
            _processor = None
        _buffer = None
        _initialized = False
