init method

Future<void> init({
  1. bool deferIndexWarmup = false,
})

Initialize the source database.

Implementation

Future<void> init({bool deferIndexWarmup = false}) async {
  try {
    debugPrint('[SourceRagService] init: Starting...');

    // 1-3. Initialize Logger (only if not already active)

    // Skipping re-init avoids potential deadlocks with closeLogStream/logging threads
    if (_logSubscription == null) {
      debugPrint('[SourceRagService] init: Initializing logger system...');
      await initLogger(); // Idempotent

      // Close any existing (though _logSubscription is null, be safe)
      await _cleanupLogStream();

      // Start fresh log stream
      debugPrint('[SourceRagService] init: Starting log stream...');
      _logSubscription = initLogStream().listen((log) {
        debugPrint(log);
      });
    } else {
      debugPrint(
        '[SourceRagService] init: Logger stream already active, skipping re-init.',
      );
    }

    // 4. Initialize DB
    debugPrint('[SourceRagService] init: Initializing Source DB...');
    await rust_rag.initSourceDb();

    // 4.1 Check for dirty marker (Crash Recovery)
    if (await _dirtyMarkerFile.exists()) {
      debugPrint(
        '[SourceRagService] Found dirty marker. Previous session might have crashed.',
      );
      debugPrint('[SourceRagService] Index will be rebuilt automatically.');
      if (!_needsRebuild) {
        _needsRebuild = true;
        _dirtyVersion++;
      }
    }

    // 5. Load or rebuild indexes.
    final warmup = _enqueueIndexTask(_runIndexWarmup);
    _warmupFuture = warmup;

    if (deferIndexWarmup) {
      debugPrint(
        '[SourceRagService] init: deferIndexWarmup=true, continuing while index warms up in background.',
      );
      unawaited(
        warmup.catchError((error, _) {
          debugPrint('[SourceRagService] Background warmup failed: $error');
          _isIndexReady = false;
        }),
      );
    } else {
      await warmup;
    }

    debugPrint('[SourceRagService] init: Done!');
  } on RagError catch (e) {
    // Smart Error Handling integration
    debugPrint(
      '[SmartError] ${e.userFriendlyMessage} (Tech: ${e.technicalMessage})',
    );
    rethrow;
  }
}