import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:laki_icu_app/utils/logger.dart';

typedef BluetoothPayloadParser<T> = T? Function(List<int> bytes, String rawHex);

final BleBluetoothManager appBluetoothManager = BleBluetoothManager();

enum BluetoothConnectionStatus {
  disconnected,
  connecting,
  connectedReady,
  active,
}

class BluetoothScanDevice {
  const BluetoothScanDevice({
    required this.device,
    required this.remoteId,
    required this.name,
    required this.hasName,
    required this.rssi,
  });

  final DiscoveredDevice device;
  final String remoteId;
  final String name;
  final bool hasName;
  final int rssi;
}

class BluetoothDataPacket<T> {
  const BluetoothDataPacket({
    required this.deviceId,
    required this.rawHex,
    required this.bytes,
    this.parsedData,
  });

  final String deviceId;
  final String rawHex;
  final List<int> bytes;
  final T? parsedData;
}

class BleBluetoothManager<T> {
  BleBluetoothManager({
    BluetoothPayloadParser<T>? parser,
    FlutterReactiveBle? ble,
    Uuid? serviceUuid,
    Uuid? notifyCharacteristicUuid,
    Uuid? writeCharacteristicUuid,
    this.connectionTimeout = const Duration(seconds: 15),
    this.enableCharacteristicDiscovery = false,
  })  : _parser = parser,
        _ble = ble ?? FlutterReactiveBle(),
        serviceUuid =
            serviceUuid ?? Uuid.parse('0000FFE0-0000-1000-8000-00805F9B34FB'),
        notifyCharacteristicUuid = notifyCharacteristicUuid ??
            Uuid.parse('0000FFE4-0000-1000-8000-00805F9B34FB'),
        writeCharacteristicUuid = writeCharacteristicUuid ??
            Uuid.parse('0000FFE9-0000-1000-8000-00805F9B34FB');

  final BluetoothPayloadParser<T>? _parser;
  final FlutterReactiveBle _ble;
  final Uuid serviceUuid;
  final Uuid notifyCharacteristicUuid;
  final Uuid writeCharacteristicUuid;
  final Duration connectionTimeout;
  final bool enableCharacteristicDiscovery;

  final _scanDevicesController =
      StreamController<List<BluetoothScanDevice>>.broadcast();
  final _dataController = StreamController<BluetoothDataPacket<T>>.broadcast();
  final _stateController =
      StreamController<BluetoothConnectionStatus>.broadcast();
  final _messageController = StreamController<String>.broadcast();
  final _sendResultController = StreamController<bool>.broadcast();

  Stream<List<BluetoothScanDevice>> get scanDevicesStream =>
      _scanDevicesController.stream;
  Stream<BluetoothDataPacket<T>> get dataStream => _dataController.stream;
  Stream<BluetoothConnectionStatus> get stateStream => _stateController.stream;
  Stream<String> get messageStream => _messageController.stream;
  Stream<bool> get sendResultStream => _sendResultController.stream;

  BluetoothConnectionStatus _status = BluetoothConnectionStatus.disconnected;
  String? _connectedDeviceId;
  QualifiedCharacteristic? _notifyCharacteristic;
  QualifiedCharacteristic? _writeCharacteristic;
  bool _writeCharacteristicOnlyWithoutResponse = false;
  StreamSubscription<DiscoveredDevice>? _scanSubscription;
  StreamSubscription<ConnectionStateUpdate>? _connectionSubscription;
  StreamSubscription<List<int>>? _notifySubscription;
  Timer? _scanTimer;
  Future<void> _writeQueue = Future<void>.value();
  Future<void>? _connectInProgress;

  final Map<String, BluetoothScanDevice> _scannedDevices = {};

  BluetoothConnectionStatus get status => _status;
  String? get connectedDeviceId => _connectedDeviceId;
  bool get isConnected =>
      _status == BluetoothConnectionStatus.connectedReady ||
      _status == BluetoothConnectionStatus.active;
  bool get isActive => _status == BluetoothConnectionStatus.active;
  List<BluetoothScanDevice> get scannedDevices => List.unmodifiable(
        _scannedDevices.values.toList()
          ..sort(
            (left, right) {
              if (left.hasName != right.hasName) {
                return left.hasName ? -1 : 1;
              }

              if (left.hasName && right.hasName) {
                final nameCompare = left.name.toUpperCase().compareTo(
                      right.name.toUpperCase(),
                    );
                if (nameCompare != 0) {
                  return nameCompare;
                }
              }

              return _normalizeRemoteIdForSort(
                left.remoteId,
              ).compareTo(_normalizeRemoteIdForSort(right.remoteId));
            },
          ),
      );

  Future<bool> ensureBluetoothReady() async {
    await _ble.initialize();

    final status = _ble.status;
    debugPrint('🔥🔥🔥 BLE_CONNECT_DEBUG ensure_ready status=$status');
    if (status == BleStatus.ready) {
      return true;
    }

    final nextStatus = await _ble.statusStream
        .where((value) => value != BleStatus.unknown)
        .first
        .timeout(const Duration(seconds: 8), onTimeout: () => status);

    if (nextStatus != BleStatus.ready) {
      debugPrint(
          '🔥🔥🔥 BLE_CONNECT_DEBUG ensure_ready_failed nextStatus=$nextStatus');
      _notifyMessage('蓝牙未就绪或未授权: $nextStatus');
      return false;
    }

    debugPrint(
        '🔥🔥🔥 BLE_CONNECT_DEBUG ensure_ready_success nextStatus=$nextStatus');
    return true;
  }

  Future<void> scanForDevices({
    required List<String> namePrefixes,
    Duration timeout = const Duration(seconds: 10),
  }) async {
    if (!await ensureBluetoothReady()) {
      return;
    }

    await stopScan();
    _scannedDevices.clear();
    _scanDevicesController.add(scannedDevices);
    _notifyMessage(
        namePrefixes.isEmpty ? '开始扫描全部蓝牙设备' : '开始扫描蓝牙设备: $namePrefixes');

    _scanSubscription = _ble.scanForDevices(
      withServices: const [],
      scanMode: ScanMode.lowLatency,
      requireLocationServicesEnabled: false,
    ).listen(
      (device) {
        if (namePrefixes.isNotEmpty &&
            !_startsWithAny(device.name, namePrefixes)) {
          return;
        }

        final deviceName = device.name.trim();
        _scannedDevices[device.id] = BluetoothScanDevice(
          device: device,
          remoteId: device.id,
          name: deviceName.isEmpty ? '未知设备' : deviceName,
          hasName: deviceName.isNotEmpty,
          rssi: device.rssi,
        );
        _scanDevicesController.add(scannedDevices);
      },
      onError: (Object error) => _notifyMessage('扫描失败: $error'),
    );

    await Future<void>.delayed(timeout);
    await stopScan();
    _scanDevicesController.add(scannedDevices);
    _notifyMessage('蓝牙扫描结束，共发现 ${_scannedDevices.length} 个设备');
  }

  Future<void> prepareConnection(String targetName) async {
    if (targetName.isEmpty) {
      _notifyMessage('无效的蓝牙设备名称');
      return;
    }

    if (_status != BluetoothConnectionStatus.disconnected) {
      _notifyMessage('蓝牙已在连接或已连接状态，跳过连接');
      return;
    }

    if (!await ensureBluetoothReady()) {
      return;
    }

    _setStatus(BluetoothConnectionStatus.connecting);
    await stopScan();
    _notifyMessage('开始扫描目标蓝牙设备: $targetName');

    var found = false;
    _scanSubscription = _ble.scanForDevices(
      withServices: const [],
      scanMode: ScanMode.lowLatency,
      requireLocationServicesEnabled: false,
    ).listen(
      (device) async {
        if (found || !device.name.contains(targetName)) {
          return;
        }
        found = true;
        await stopScan();
        await connectToDeviceId(device.id);
      },
      onError: (Object error) {
        _setStatus(BluetoothConnectionStatus.disconnected);
        _notifyMessage('扫描目标设备失败: $error');
      },
    );

    _scanTimer = Timer(connectionTimeout, () async {
      if (!found && _status == BluetoothConnectionStatus.connecting) {
        await stopScan();
        _setStatus(BluetoothConnectionStatus.disconnected);
        _notifyMessage('未找到目标蓝牙设备: $targetName');
      }
    });
  }

  Future<void> connectByRemoteId(String remoteId) {
    return connectToDeviceId(remoteId);
  }

  Future<void> connectToDevice(BluetoothScanDevice device) {
    return connectToDeviceId(device.remoteId);
  }

  Future<void> connectToDeviceId(
    String deviceId, {
    bool prescan = false,
  }) {
    final pending = _connectInProgress;
    if (pending != null) {
      debugPrint(
        '🔥🔥🔥 BLE_CONNECT_DEBUG connect_join_existing deviceId=$deviceId',
      );
      return pending;
    }

    final task = _connectToDeviceIdLocked(deviceId, prescan: prescan);
    _connectInProgress = task.whenComplete(() {
      _connectInProgress = null;
    });
    return _connectInProgress!;
  }

  Future<void> _connectToDeviceIdLocked(
    String deviceId, {
    required bool prescan,
  }) async {
    debugPrint(
        '🔥🔥🔥 BLE_CONNECT_DEBUG connect_to_device_id start deviceId=$deviceId');
    if (deviceId.isEmpty) {
      debugPrint(
          '🔥🔥🔥 BLE_CONNECT_DEBUG connect_to_device_id empty_device_id');
      _notifyMessage('无效的蓝牙设备地址');
      throw ArgumentError('无效的蓝牙设备地址');
    }

    if (!await ensureBluetoothReady()) {
      debugPrint(
          '🔥🔥🔥 BLE_CONNECT_DEBUG connect_to_device_id bluetooth_not_ready');
      _setStatus(BluetoothConnectionStatus.disconnected);
      throw StateError('蓝牙未就绪或未授权');
    }

    await disconnect();
    await Future<void>.delayed(const Duration(milliseconds: 600));
    _connectedDeviceId = deviceId;
    _notifyCharacteristic = QualifiedCharacteristic(
      deviceId: deviceId,
      serviceId: serviceUuid,
      characteristicId: notifyCharacteristicUuid,
    );
    _writeCharacteristic = QualifiedCharacteristic(
      deviceId: deviceId,
      serviceId: serviceUuid,
      characteristicId: writeCharacteristicUuid,
    );

    _setStatus(BluetoothConnectionStatus.connecting);
    _notifyMessage('正在连接蓝牙设备: $deviceId');
    debugPrint('🔥🔥🔥 BLE_CONNECT_DEBUG connecting deviceId=$deviceId');

    final completer = Completer<void>();
    final connectionStream = prescan
        ? _ble.connectToAdvertisingDevice(
            id: deviceId,
            withServices: const [],
            prescanDuration: const Duration(seconds: 5),
            servicesWithCharacteristicsToDiscover: {
              serviceUuid: [notifyCharacteristicUuid, writeCharacteristicUuid],
            },
            connectionTimeout: connectionTimeout,
          )
        : _ble.connectToDevice(
            id: deviceId,
            servicesWithCharacteristicsToDiscover: {
              serviceUuid: [notifyCharacteristicUuid, writeCharacteristicUuid],
            },
            connectionTimeout: connectionTimeout,
          );
    _connectionSubscription = connectionStream
        .listen(
      (update) async {
        switch (update.connectionState) {
          case DeviceConnectionState.connecting:
            _setStatus(BluetoothConnectionStatus.connecting);
            debugPrint(
                '🔥🔥🔥 BLE_CONNECT_DEBUG state_connecting deviceId=$deviceId');
            break;
          case DeviceConnectionState.connected:
            _setStatus(BluetoothConnectionStatus.connectedReady);
            _notifyMessage('蓝牙连接成功: $deviceId');
            debugPrint(
                '🔥🔥🔥 BLE_CONNECT_DEBUG state_connected deviceId=$deviceId');
            try {
              if (enableCharacteristicDiscovery) {
                await _discoverServicesAndResolveWriteCharacteristic(deviceId);
              }
              await Future<void>.delayed(const Duration(milliseconds: 500));
              final notifyReady = await _enableNotifications(deviceId);
              if (notifyReady) {
                activateDataSource();
              } else {
                _notifyMessage('蓝牙已连接，但未找到可订阅的接收特征值');
                debugPrint(
                  '🔥🔥🔥 BLE_CONNECT_DEBUG connected_without_notify '
                  'deviceId=$deviceId',
                );
              }
              if (!completer.isCompleted) {
                completer.complete();
              }
            } catch (error) {
              debugPrint(
                '🔥🔥🔥 BLE_CONNECT_DEBUG connected_setup_error '
                'deviceId=$deviceId error=$error',
              );
              _notifyMessage('蓝牙连接初始化失败: $error');
              if (!completer.isCompleted) {
                completer.completeError(error);
              }
            }
            break;
          case DeviceConnectionState.disconnecting:
            _setStatus(BluetoothConnectionStatus.disconnected);
            debugPrint(
                '🔥🔥🔥 BLE_CONNECT_DEBUG state_disconnecting deviceId=$deviceId');
            break;
          case DeviceConnectionState.disconnected:
            _setStatus(BluetoothConnectionStatus.disconnected);
            _notifyMessage('蓝牙连接断开: $deviceId');
            debugPrint(
              '🔥🔥🔥 BLE_CONNECT_DEBUG state_disconnected deviceId=$deviceId '
              'failure=${update.failure}',
            );
            _clearCharacteristics();
            if (!completer.isCompleted) {
              completer.completeError(
                update.failure ?? StateError('蓝牙连接已断开'),
              );
            }
            break;
        }
      },
      onError: (Object error) {
        _setStatus(BluetoothConnectionStatus.disconnected);
        _notifyMessage('蓝牙连接失败: $error');
        debugPrint(
            '🔥🔥🔥 BLE_CONNECT_DEBUG connect_error deviceId=$deviceId error=$error');
        if (!completer.isCompleted) {
          completer.completeError(error);
        }
      },
    );

    try {
      await completer.future.timeout(connectionTimeout);
    } catch (_) {
      debugPrint(
          '🔥🔥🔥 BLE_CONNECT_DEBUG connect_timeout_or_error deviceId=$deviceId');
      await disconnect();
      rethrow;
    }
  }

  void activateDataSource() {
    if (_status == BluetoothConnectionStatus.connectedReady ||
        _status == BluetoothConnectionStatus.active) {
      _setStatus(BluetoothConnectionStatus.active);
      _notifyMessage('蓝牙数据源已激活');
      debugPrint(
          '🔥🔥🔥 BLE_CONNECT_DEBUG data_source_active deviceId=$_connectedDeviceId');
    }
  }

  Future<void> writeData(List<int> data, {bool withoutResponse = false}) {
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG enqueue data=$data hex=${bytesToHex(data)}',
    );
    _writeQueue = _writeQueue.then(
      (_) => _writeDataLocked(data, withoutResponse: withoutResponse),
      onError: (_) => _writeDataLocked(data, withoutResponse: withoutResponse),
    );
    return _writeQueue;
  }

  Future<void> _writeDataLocked(
    List<int> data, {
    bool withoutResponse = false,
  }) async {
    if (data.isEmpty) {
      _notifyMessage('发送数据为空');
      _sendResultController.add(false);
      return;
    }

    final characteristic = _writeCharacteristic;
    if (!isConnected || characteristic == null) {
      _notifyMessage('蓝牙未连接或未找到发送特征值，无法发送数据');
      _sendResultController.add(false);
      return;
    }

    final hex = bytesToHex(data);
    final effectiveWithoutResponse =
        withoutResponse || _writeCharacteristicOnlyWithoutResponse;
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG write_data '
      'deviceId=${characteristic.deviceId} '
      'service=${characteristic.serviceId} '
      'characteristic=${characteristic.characteristicId} '
      'withoutResponse=$effectiveWithoutResponse '
      'data=$data '
      'hex=$hex',
    );
    try {
      if (effectiveWithoutResponse) {
        await _ble.writeCharacteristicWithoutResponse(
          characteristic,
          value: data,
        );
      } else {
        await _ble.writeCharacteristicWithResponse(characteristic, value: data);
      }
      Log.warn('🔥🔥🔥 BLE_WRITE_DEBUG write_success hex=$hex');
      _notifyMessage('蓝牙数据发送成功: $hex');
      _sendResultController.add(true);
    } catch (error) {
      Log.warn('🔥🔥🔥 BLE_WRITE_DEBUG write_error hex=$hex error=$error');
      _notifyMessage('蓝牙数据发送失败: $error');
      _sendResultController.add(false);
    } finally {
      await Future<void>.delayed(const Duration(milliseconds: 120));
    }
  }

  Future<void> writeHex(String hex, {bool withoutResponse = false}) {
    return writeData(hexToBytes(hex), withoutResponse: withoutResponse);
  }

  Future<void> stopScan() async {
    _scanTimer?.cancel();
    _scanTimer = null;
    await _scanSubscription?.cancel();
    _scanSubscription = null;
  }

  Future<void> disconnect() async {
    await stopScan();
    await _notifySubscription?.cancel();
    _notifySubscription = null;
    await _connectionSubscription?.cancel();
    _connectionSubscription = null;
    _connectedDeviceId = null;
    _clearCharacteristics();
    _setStatus(BluetoothConnectionStatus.disconnected);
  }

  Future<void> release() async {
    await disconnect();
    await _scanDevicesController.close();
    await _dataController.close();
    await _stateController.close();
    await _messageController.close();
    await _sendResultController.close();
  }

  Future<bool> _enableNotifications(String deviceId) async {
    final characteristic = _notifyCharacteristic;
    if (characteristic == null) {
      debugPrint(
          '🔥🔥🔥 BLE_CONNECT_DEBUG notify_characteristic_null deviceId=$deviceId');
      return false;
    }

    try {
      await _notifySubscription?.cancel();
      debugPrint(
        '🔥🔥🔥 BLE_CONNECT_DEBUG notify_subscribe_start deviceId=$deviceId '
        'service=${characteristic.serviceId} '
        'characteristic=${characteristic.characteristicId}',
      );
      _notifySubscription =
          _ble.subscribeToCharacteristic(characteristic).listen(
        (bytes) {
          if (!isActive || bytes.isEmpty) {
            return;
          }

          final rawHex = bytesToHex(bytes);
          debugPrint(
              '🔥🔥🔥 BLE_READ_DEBUG manager_notify deviceId=$deviceId len=${bytes.length} hex=$rawHex');
          Log.warn('🔥🔥🔥 BLE_READ_DEBUG manager_notify deviceId=$deviceId '
              'len=${bytes.length} hex=$rawHex');
          final parsedData = _parser?.call(bytes, rawHex);
          _dataController.add(
            BluetoothDataPacket<T>(
              deviceId: deviceId,
              rawHex: rawHex,
              bytes: List.unmodifiable(bytes),
              parsedData: parsedData,
            ),
          );
        },
        onError: (Object error) {
          debugPrint(
              '🔥🔥🔥 BLE_CONNECT_DEBUG notify_error deviceId=$deviceId error=$error');
          _notifyMessage('接收蓝牙数据失败: $error');
        },
      );
      debugPrint(
          '🔥🔥🔥 BLE_CONNECT_DEBUG notify_subscribe_done deviceId=$deviceId');
      return true;
    } catch (error) {
      debugPrint(
          '🔥🔥🔥 BLE_CONNECT_DEBUG notify_subscribe_error deviceId=$deviceId error=$error');
      _notifyMessage('订阅蓝牙数据失败: $error');
      return false;
    }
  }

  Future<void> _discoverServicesAndResolveWriteCharacteristic(
    String deviceId,
  ) async {
    try {
      Log.warn('🔥🔥🔥 BLE_DISCOVER_DEBUG start deviceId=$deviceId');
      final services = await _ble.getDiscoveredServices(deviceId);
      QualifiedCharacteristic? fallbackWriteCharacteristic;
      QualifiedCharacteristic? fallbackNotifyCharacteristic;
      var fallbackOnlyWithoutResponse = false;
      var preferredWriteFound = false;
      var preferredNotifyFound = false;

      for (final service in services) {
        Log.warn('🔥🔥🔥 BLE_DISCOVER_DEBUG service=${service.id}');
        for (final characteristic in service.characteristics) {
          final isPreferredWrite =
              _isSameUuid(characteristic.id, writeCharacteristicUuid);
          final isPreferredNotify =
              _isSameUuid(characteristic.id, notifyCharacteristicUuid);
          final canWrite = characteristic.isWritableWithResponse ||
              characteristic.isWritableWithoutResponse;
          final canNotify =
              characteristic.isNotifiable || characteristic.isIndicatable;
          Log.warn(
            '🔥🔥🔥 BLE_DISCOVER_DEBUG characteristic=${characteristic.id} '
            'service=${service.id} '
            'read=${characteristic.isReadable} '
            'write=${characteristic.isWritableWithResponse} '
            'writeNoResp=${characteristic.isWritableWithoutResponse} '
            'notify=${characteristic.isNotifiable} '
            'indicate=${characteristic.isIndicatable}'
            '${isPreferredWrite ? ' preferredWrite=true' : ''}'
            '${isPreferredNotify ? ' preferredNotify=true' : ''}',
          );

          final resolved = QualifiedCharacteristic(
            deviceId: deviceId,
            serviceId: service.id,
            characteristicId: characteristic.id,
          );

          if (canNotify) {
            fallbackNotifyCharacteristic ??= resolved;
            if (isPreferredNotify) {
              _notifyCharacteristic = resolved;
              preferredNotifyFound = true;
            }
          }

          if (!canWrite) continue;

          final onlyWithoutResponse =
              !characteristic.isWritableWithResponse &&
                  characteristic.isWritableWithoutResponse;

          fallbackWriteCharacteristic ??= resolved;
          fallbackOnlyWithoutResponse = onlyWithoutResponse;

          if (isPreferredWrite) {
            _writeCharacteristic = resolved;
            _writeCharacteristicOnlyWithoutResponse = onlyWithoutResponse;
            preferredWriteFound = true;
          }
        }
      }

      if (!preferredNotifyFound && fallbackNotifyCharacteristic != null) {
        _notifyCharacteristic = fallbackNotifyCharacteristic;
        Log.warn(
          '🔥🔥🔥 BLE_DISCOVER_DEBUG preferred_notify_not_available '
          'fallback=${_notifyCharacteristic!.characteristicId} '
          'service=${_notifyCharacteristic!.serviceId}',
        );
      }

      if (!preferredWriteFound && fallbackWriteCharacteristic != null) {
        _writeCharacteristic = fallbackWriteCharacteristic;
        _writeCharacteristicOnlyWithoutResponse = fallbackOnlyWithoutResponse;
        Log.warn(
          '🔥🔥🔥 BLE_DISCOVER_DEBUG preferred_write_not_writable '
          'fallback=${_writeCharacteristic!.characteristicId} '
          'service=${_writeCharacteristic!.serviceId} '
          'onlyWithoutResponse=$_writeCharacteristicOnlyWithoutResponse',
        );
      }

      final resolvedNotify = _notifyCharacteristic;
      final resolvedWrite = _writeCharacteristic;
      Log.warn(
        '🔥🔥🔥 BLE_DISCOVER_DEBUG resolved_notify '
        'characteristic=${resolvedNotify?.characteristicId} '
        'service=${resolvedNotify?.serviceId}',
      );
      Log.warn(
        '🔥🔥🔥 BLE_DISCOVER_DEBUG resolved_write '
        'characteristic=${resolvedWrite?.characteristicId} '
        'service=${resolvedWrite?.serviceId} '
        'onlyWithoutResponse=$_writeCharacteristicOnlyWithoutResponse',
      );
    } catch (error) {
      Log.warn(
        '🔥🔥🔥 BLE_DISCOVER_DEBUG error deviceId=$deviceId error=$error',
      );
    }
  }

  void _clearCharacteristics() {
    _notifyCharacteristic = null;
    _writeCharacteristic = null;
    _writeCharacteristicOnlyWithoutResponse = false;
  }

  void _setStatus(BluetoothConnectionStatus status) {
    _status = status;
    debugPrint(
      '🔥🔥🔥 BLE_CONNECT_DEBUG manager_status status=$status '
      'deviceId=$_connectedDeviceId',
    );
    if (!_stateController.isClosed) {
      _stateController.add(status);
    }
  }

  void _notifyMessage(String message) {
    if (!_messageController.isClosed) {
      _messageController.add(message);
    }
  }

  static String bytesToHex(List<int> bytes) {
    return bytes
        .map((item) => item.toRadixString(16).padLeft(2, '0'))
        .join()
        .toUpperCase();
  }

  static List<int> hexToBytes(String hex) {
    final clean = hex.replaceAll(RegExp(r'\s+'), '');
    if (clean.length.isOdd) {
      throw FormatException('Hex 字符串长度必须为偶数: $hex');
    }

    return [
      for (var index = 0; index < clean.length; index += 2)
        int.parse(clean.substring(index, index + 2), radix: 16),
    ];
  }

  static bool _startsWithAny(String value, List<String> prefixes) {
    return prefixes.any(value.startsWith);
  }

  static bool _isSameUuid(Uuid left, Uuid right) {
    return left.toString().toLowerCase() == right.toString().toLowerCase();
  }

  static String _normalizeRemoteIdForSort(String remoteId) {
    return remoteId.replaceAll(RegExp(r'[^0-9a-zA-Z]'), '').toUpperCase();
  }
}
