analyze static method

NiceTreeShakingResult analyze()

Analyze component usage and return results.

Implementation

static NiceTreeShakingResult analyze() {
  final tracker = NiceUsageTracker.instance;
  final allComponents = NiceComponentCatalog.allComponents;
  final usedNames = tracker.usedComponents;

  final updatedComponents = <NiceComponentInfo>[];
  final unusedComponents = <NiceComponentInfo>[];
  var usedSize = 0;
  var unusedSize = 0;

  for (final component in allComponents) {
    final isUsed = usedNames.contains(component.name);
    final updated = component.copyWith(isUsed: isUsed);
    updatedComponents.add(updated);

    if (isUsed) {
      usedSize += component.estimatedSizeBytes;
    } else {
      unusedSize += component.estimatedSizeBytes;
      unusedComponents.add(updated);
    }
  }

  // Generate recommendations
  final recommendations = <String>[];

  if (unusedComponents.length > 10) {
    recommendations.add(
      'Consider using selective imports instead of importing the entire library. '
      '${unusedComponents.length} components appear unused.',
    );
  }

  // Find heavy unused components
  final heavyUnused = unusedComponents
      .where((c) => c.estimatedSizeBytes > 20000)
      .toList()
    ..sort((a, b) => b.estimatedSizeBytes.compareTo(a.estimatedSizeBytes));

  if (heavyUnused.isNotEmpty) {
    final names = heavyUnused.take(5).map((c) => c.name).join(', ');
    recommendations.add(
      'Large unused components detected: $names. '
      'Removing these could save significant bundle size.',
    );
  }

  // Category-level recommendations
  final categoryUsage = <String, int>{};
  final categoryTotal = <String, int>{};
  for (final entry in NiceComponentCatalog.components.entries) {
    final categoryName = entry.key;
    final categoryComponents = entry.value;
    final used = categoryComponents.where((c) => usedNames.contains(c.name)).length;
    categoryUsage[categoryName] = used;
    categoryTotal[categoryName] = categoryComponents.length;
  }

  for (final entry in categoryUsage.entries) {
    final category = entry.key;
    final used = entry.value;
    final total = categoryTotal[category] ?? 0;
    if (used == 0 && total > 0) {
      recommendations.add(
        'Category "$category" has no used components. Consider removing the import.',
      );
    }
  }

  return NiceTreeShakingResult(
    timestamp: DateTime.now(),
    totalComponents: allComponents.length,
    usedComponents: usedNames.length,
    unusedComponents: unusedComponents.length,
    totalSizeBytes: NiceComponentCatalog.totalEstimatedSize,
    usedSizeBytes: usedSize,
    unusedSizeBytes: unusedSize,
    allComponents: updatedComponents,
    unusedComponentsList: unusedComponents,
    recommendations: recommendations,
  );
}