initialize static method

Future<void> initialize({
  1. required SDKEnvironment environment,
  2. required String deviceId,
  3. String? baseURL,
})

Complete telemetry init (Phase 2): fill in device info. Reuses the manager created in Phase 1 via attachSinkPhase1; only creates one here as a fallback (gated on a real baseURL) if Phase-1 attach never ran.

Implementation

static Future<void> initialize({
  required SDKEnvironment environment,
  required String deviceId,
  String? baseURL,
}) async {
  if (_isInitialized) {
    _logger.debug('Telemetry already initialized');
    return;
  }
  _environment = environment;

  try {
    final lib = PlatformLoader.loadCommons();

    if (_managerPtr == null) {
      // Fallback: Phase-1 attach didn't run. The auth token isn't available
      // yet (applied at send time — Kotlin parity); only the baseURL must be
      // real, else creating a manager that can never flush is wasteful.
      if (!DartBridgeDevConfig.isUsableCredential(baseURL)) {
        _logger.warning(
          'Telemetry skipped — baseURL looks like a placeholder. '
          'Set a real base URL via dart-define or runtime config.',
        );
        _isInitialized = true; // Suppress retry.
        return;
      }
      _createManagerAndAttach(lib, environment, deviceId);
    }

    if (_managerPtr == null || _managerPtr == nullptr) {
      _isInitialized = true;
      return;
    }

    // Device info — the model/OS lookup is async (device_info_plus), so it
    // only happens here. Ensure the device snapshot is populated first; this
    // runs before Phase 2 device registration refreshes it, so without this
    // the manager would be stamped with the placeholder defaults (model
    // "unknown" + the Platform.operatingSystemVersion build string).
    await DartBridgeDevice.ensureDeviceInfoSnapshot();
    final deviceModel = await _getDeviceModel();
    final cachedOs = DartBridgeDevice.cachedOsVersion.trim();
    final osVersion = cachedOs.isNotEmpty
        ? cachedOs
        : Platform.operatingSystemVersion;
    final setDeviceInfo = lib
        .lookupFunction<
          Void Function(Pointer<Void>, Pointer<Utf8>, Pointer<Utf8>),
          void Function(Pointer<Void>, Pointer<Utf8>, Pointer<Utf8>)
        >('rac_telemetry_manager_set_device_info');
    final deviceModelPtr = deviceModel.toNativeUtf8();
    final osVersionPtr = osVersion.toNativeUtf8();
    setDeviceInfo(_managerPtr!, deviceModelPtr, osVersionPtr);
    calloc.free(deviceModelPtr);
    calloc.free(osVersionPtr);

    _isInitialized = true;
    _logger.debug('Telemetry manager initialized');
  } catch (_) {
    _logger.debug('Telemetry initialization failed');
    _isInitialized = true; // Avoid retry loops
  }
}