saveOptimizationReport method

Future<void> saveOptimizationReport(
  1. List<OptimizationResult> results,
  2. String outputPath
)

Implementation

Future<void> saveOptimizationReport(
  List<OptimizationResult> results,
  String outputPath,
) async {
  try {
    final directory = Directory(path_util.dirname(outputPath));
    if (!await directory.exists()) {
      await directory.create(recursive: true);
    }

    final file = File(outputPath);
    final totalSaved = results.fold(
      0,
      (sum, result) => sum + result.savedBytes,
    );

    final report = {
      'timestamp': DateTime.now().toIso8601String(),
      'totalOptimized': results.length,
      'totalSaved': totalSaved,
      'savingsPercentage': results.isNotEmpty
          ? (totalSaved /
                  results.fold(0, (sum, r) => sum + r.originalAsset.size) *
                  100)
              .toStringAsFixed(2)
          : '0',
      'results': results
          .map((r) => {
                'path': r.originalAsset.path,
                'originalSize': r.originalAsset.size,
                'optimizedSize': r.optimizedSize,
                'savedBytes': r.savedBytes,
                'savingsPercentage': r.savingsPercentage.toStringAsFixed(2),
                'optimizedAt': r.optimizedAt.toIso8601String(),
              })
          .toList(),
    };

    await file.writeAsString(
      JsonEncoder.withIndent('  ').convert(report),
    );
  } catch (e) {
    throw AssetOptException('Failed to save optimization report: $e');
  }
}