processUIEvent method

Future<void> processUIEvent(
  1. ObslyEventBase event
)

Execute rules for UI events with fresh appContext

Implementation

Future<void> processUIEvent(ObslyEventBase event) async {
  if (!_isAvailable || !_isExecutionEnabled) return;

  final rulesStartTime = DateTime.now();
  ObslyLogger.debug('DEBUGTIMING: 🔧 Rules processing started');

  const elementId = 'Unknown Element';
  const action = 'Unknown Action';

  try {
    final uiContext = _extractUIContext(event);
    if (uiContext != null) {
      final contextElementId = uiContext['elementId'] ?? elementId;
      final contextAction = uiContext['action'] ?? action;

      // Log UI rule processing
      ObslyLogger.verbose(
          '🖱️ UI Event: $contextAction on $contextElementId');
      ObslyLogger.verbose(
          '🎯 Starting UI rule evaluation: $contextElementId ($contextAction)');

      // Build fresh appContext for this evaluation
      final currentAppContext = _buildCurrentAppContext();

      // Log context access for debugging
      ObslyLogger.verbose('🗂️ UI Rule context access: app_context');

      // Merge UI context with app context
      final fullContext = {
        ...currentAppContext,
        'event': {
          'click': contextElementId,
          'domPath': uiContext['widgetPath'] ?? '',
          'action': contextAction,
          if (uiContext['metadata'] != null) ...uiContext['metadata'],
        },
      };

      // Log the merged context
      ObslyLogger.verbose('🗂️ UI Rule merged context prepared');

      // DEBUG: Log the exact context being sent to rules engine
      ObslyLogger.verbose('🔍 CONTEXT SENT TO RULES ENGINE:');
      ObslyLogger.verbose(
          '  event.click = "${fullContext['event']?['click']}"');
      ObslyLogger.verbose('  uiContext.elementId = "$contextElementId"');

      // Use unified execution method
      final results = await RulesManager.instance.executeRulesForEvent(
        eventType: 'ui',
        context: fullContext,
      );

      // Log results with new system
      final allTags = results
          .expand((r) => RulesResultFormatter.formatForUI(r.rawResult,
              includeTimestamp: false)['tags'] as List<Map<String, dynamic>>)
          .toList();
      final allVariables = results
          .expand((r) => RulesResultFormatter.formatForUI(r.rawResult,
                  includeTimestamp: false)['variables']
              as List<Map<String, dynamic>>)
          .toList();

      final resultStatus = results.isNotEmpty ? '✅ SUCCESS' : '❌ NO RESULTS';
      ObslyLogger.verbose(
          '🏁 UI Rules result: $resultStatus | Rules: ${results.length} | Tags: ${allTags.length} | Variables: ${allVariables.length}');

      ObslyLogger.log(
          '🖱️ UI Rules executed for: $contextElementId ($contextAction)');

      final rulesDuration = DateTime.now().difference(rulesStartTime);
      ObslyLogger.debug(
          'DEBUGTIMING: 🔧 Rules processing completed: ${rulesDuration.inMilliseconds}ms');
    }
  } catch (e, stackTrace) {
    final rulesDuration = DateTime.now().difference(rulesStartTime);
    ObslyLogger.debug(
        'DEBUGTIMING: 🔧 Rules processing failed after: ${rulesDuration.inMilliseconds}ms');
    ObslyLogger.errorWithContext(
      'RulesIntegration',
      'processUIEvent',
      e.toString(),
      stackTrace,
      context: {'elementId': elementId, 'action': action},
    );
  }
}