"""
Device detection and connection utilities for Phone Copilot.

This module provides functions to detect and connect to devices using ADB and HDC protocols.

Example usage:

    >>> from phone_copilot.device import detect_device
    >>> device = detect_device()  # Auto-detect the first connected device
    >>> device = detect_device(device_id)  # Detect a specific device by ID
    >>> device = detect_device(device_instance)  # Use an existing device instance

    >>> from phone_copilot.device import connection, DeviceType
    >>> adb_connection = connection(DeviceType.ADB)  # Get ADB connection
    >>> hdc_connection = connection(DeviceType.HDC)  # Get HDC connection
    >>> adb_devices = adb_connection.devices  # List of connected ADB devices
    >>> hdc_devices = hdc_connection.devices  # List of connected HDC devices
"""

from loguru import logger
from xpdc import DeviceType, connection
from xpdc.adb.device import ADBDevice
from xpdc.hdc.device import HDCDevice

__all__ = ['connection', 'DeviceType', 'ADBDevice', 'HDCDevice']


def detect_device(*, device: str = None) -> ADBDevice | HDCDevice:
    """Detects a connected device.

    Specify a device ID to select a specific device,
    or leave it empty to auto-detect the first connected device.

    Args:
        device (str, optional): The device ID to select. Defaults to None.

    Raises:
        RuntimeError: If no connected device is found or the specified device is not found via both ADB and HDC.
        TypeError: If the provided device parameter is not a string or None.

    Returns:
        ADBDevice | HDCDevice: The detected device instance.
    """
    if not device:
        logger.debug('No device specified, trying to detect connected devices via [adb]...')
        try:
            return connection(DeviceType.ADB).devices[0]
        except Exception:  # noqa: BLE001
            logger.debug('No ADB devices detected, trying to detect connected devices via [hdc]...')

        try:
            return connection(DeviceType.HDC).devices[0]
        except Exception:  # noqa: BLE001
            logger.debug('No HDC devices detected.')

        msg = 'No connected device found via [adb] and [hdc], please check your connection and try again.'
        raise RuntimeError(msg)

    elif isinstance(device, str):
        try:
            for d in connection(DeviceType.ADB).devices:
                if device == d.device_id:
                    return d
        except Exception:  # noqa: BLE001
            logger.debug('Failed to find device via [adb], trying to find device via [hdc]...')

        try:
            for d in connection(DeviceType.HDC).devices:
                if device == d.device_id:
                    return d
        except Exception:  # noqa: BLE001
            logger.debug('Failed to find device via [hdc].')

        msg = f'No connected device with id [{device}] found via [adb] and [hdc], please check your connection and try again.'  # noqa: E501
        raise RuntimeError(msg)

    msg = f'Invalid device parameter: expected a string device ID or None, but got {type(device)}.'
    raise TypeError(msg)
