# Copyright 2026, Jiri Eischmann <jiri@eischmann.cz> and the meshy contributors
# SPDX-License-Identifier: GPL-3.0-or-later

"""BLE transport factory for cross-platform support.

This module provides a platform-agnostic interface for BLE communication.
The actual implementation is selected at runtime based on the platform:
- Linux: BlueZ D-Bus API
- macOS: CoreBluetooth framework (to be implemented)
"""

from meshy.platforms import is_linux, is_macos

# Re-export BleDevice for backwards compatibility
from meshy.platforms.ble_base import BleDevice

__all__ = ["BleDevice", "BleTransport", "create_ble_transport"]


def create_ble_transport():
    """Factory function to create platform-appropriate BLE transport.

    Returns:
        BleTransportBase: Platform-specific BLE transport implementation

    Note: On macOS, if CoreBluetooth fails to initialize (metaclass conflict),
    this returns None and BLE features will be unavailable.
    """
    if is_macos():
        try:
            from meshy.platforms.macos.ble_corebluetooth import BleTransportCoreBluetooth

            # Use PyObjC alloc/init pattern for NSObject subclasses
            return BleTransportCoreBluetooth.alloc().init()
        except (TypeError, ImportError) as e:
            import logging

            log = logging.getLogger(__name__)
            log.warning(f"BLE not available on macOS: {e}")
            log.info("USB and TCP connectivity still available")
            return None
    elif is_linux():
        from meshy.platforms.linux.ble_bluez import BleTransportBlueZ

        return BleTransportBlueZ()
    else:
        import logging

        logging.getLogger(__name__).info(
            "BLE not available on this platform, USB and TCP connectivity still available"
        )
        return None


class BleTransport:
    """BLE transport factory class for backwards compatibility.

    Usage:
        transport = BleTransport()  # Returns platform-specific implementation
    """

    def __new__(cls):
        return create_ble_transport()
