compress_comics 1.1.0

High-performance comic book compression tool with WebP conversion supporting CBR, CBZ, and PDF formats
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
use anyhow::{Context, Result};
use clap::Parser;
use crossbeam_channel::{bounded, Receiver, Sender};
use glob::glob;
use image::ImageReader;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use rayon::prelude::*;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::thread;
use tempfile::TempDir;
use walkdir::WalkDir;
use zip::{write::FileOptions, ZipWriter};

#[derive(Parser)]
#[command(author, version, about = "Compress comic book files (CBR/CBZ/PDF) with parallel processing", long_about = None)]
struct Args {
    /// Input file or directory to process. If directory, processes all comic files
    #[arg(value_name = "INPUT")]
    input: Option<PathBuf>,

    /// WebP quality (1-100, default: 90)
    #[arg(short, long, default_value = "90")]
    quality: u8,

    /// Target height for images (default: 1800)
    #[arg(short = 'H', long, default_value = "1800")]
    target_height: u32,

    /// Maximum dimension for fallback (default: 1200)
    #[arg(short, long, default_value = "1200")]
    max_dimension: u32,

    /// Rename original file to <name>_original.<ext> and give compressed file the original name
    #[arg(short, long)]
    rename_original: bool,

    /// Glob pattern for file selection (e.g., "ABC*.cbr")
    #[arg(short, long)]
    glob_pattern: Option<String>,

    /// Minimum compression savings required to keep compressed file (default: 5%)
    #[arg(long, default_value = "5.0")]
    min_savings: f64,

    /// Enable verbose output with detailed warnings
    #[arg(short, long)]
    verbose: bool,
}

#[derive(Debug)]
struct ComicFile {
    path: PathBuf,
    file_type: ComicType,
}

#[derive(Debug)]
enum ComicType {
    Cbz,
    Cbr,
    Pdf,
}

#[derive(Debug)]
struct ProcessingStats {
    original_size: u64,
    compressed_size: u64,
    images_processed: usize,
    images_skipped: usize,
    compression_skipped: bool,
    error_message: Option<String>,
}

fn main() -> Result<()> {
    let args = Args::parse();

    if args.quality < 1 || args.quality > 100 {
        anyhow::bail!("Quality must be between 1 and 100");
    }

    let input_path = args.input.clone().unwrap_or_else(|| PathBuf::from("."));

    if !input_path.exists() {
        anyhow::bail!("Input path does not exist: {}", input_path.display());
    }

    let comic_files = if let Some(pattern) = &args.glob_pattern {
        find_comic_files_by_glob(pattern)?
    } else if input_path.is_file() {
        vec![detect_comic_file(&input_path)?]
    } else {
        find_comic_files(&input_path)?
    };

    if comic_files.is_empty() {
        if args.glob_pattern.is_some() {
            // Error message already printed in find_comic_files_by_glob
        } else {
            println!("No comic files found in the specified path.");
        }
        return Ok(());
    }

    if args.verbose {
        println!("📁 Found files:");
        for file in &comic_files {
            println!("   - {}", file.path.display());
        }
        println!();
    }

    println!("🚀 Found {} comic file(s) to process", comic_files.len());
    println!(
        "Settings: Quality={}, Target Height={}px",
        args.quality, args.target_height
    );
    println!("-----------------------------------------------------");

    let multi_progress = Arc::new(MultiProgress::new());
    let overall_progress = multi_progress.add(ProgressBar::new(comic_files.len() as u64));
    overall_progress.set_style(
        ProgressStyle::default_bar()
            .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} files ({eta})")?
            .progress_chars("█▉▊▋▌▍▎▏ "),
    );

    let stats = Arc::new(Mutex::new(HashMap::new()));

    comic_files.par_iter().for_each(|comic_file| {
        let file_progress = multi_progress.add(ProgressBar::new(100));
        let style_result = ProgressStyle::default_bar()
            .template("  📖 {msg} [{bar:30.green/yellow}] {percent}%")
            .unwrap()
            .progress_chars("█▉▊▋▌▍▎▏ ");
        file_progress.set_style(style_result);
        file_progress.set_message(format!(
            "{}",
            comic_file.path.file_name().unwrap().to_string_lossy()
        ));

        match process_comic_file(comic_file, &args, &file_progress) {
            Ok(file_stats) => {
                let mut stats_map = stats.lock().unwrap();
                
                if file_stats.compression_skipped {
                    file_progress.finish_with_message("⏭️  Skipped - already well-compressed");
                } else {
                    file_progress.finish_with_message("✅ Compressed");
                }
                
                stats_map.insert(comic_file.path.clone(), file_stats);
            }
            Err(e) => {
                // Create error stats entry
                let error_stats = ProcessingStats {
                    original_size: fs::metadata(&comic_file.path).map(|m| m.len()).unwrap_or(0),
                    compressed_size: 0,
                    images_processed: 0,
                    images_skipped: 0,
                    compression_skipped: false,
                    error_message: Some(e.to_string()),
                };
                
                let mut stats_map = stats.lock().unwrap();
                stats_map.insert(comic_file.path.clone(), error_stats);
                
                file_progress.finish_with_message(format!("❌ Failed: {}", e));
            }
        }
        overall_progress.inc(1);
    });

    overall_progress.finish_with_message("🎉 All files processed!");

    print_summary(&stats.lock().unwrap());

    Ok(())
}

fn detect_comic_file(path: &Path) -> Result<ComicFile> {
    let extension = path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|s| s.to_lowercase());

    let file_type = match extension.as_deref() {
        Some("cbz") => ComicType::Cbz,
        Some("cbr") => ComicType::Cbr,
        Some("pdf") => ComicType::Pdf,
        _ => anyhow::bail!("Unsupported file type. Only CBR, CBZ, and PDF files are supported."),
    };

    Ok(ComicFile {
        path: path.to_path_buf(),
        file_type,
    })
}

fn find_comic_files(dir: &Path) -> Result<Vec<ComicFile>> {
    let mut comic_files = Vec::new();

    for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) {
        if entry.file_type().is_file() {
            if let Ok(comic_file) = detect_comic_file(entry.path()) {
                comic_files.push(comic_file);
            }
        }
    }

    Ok(comic_files)
}

fn find_comic_files_by_glob(pattern: &str) -> Result<Vec<ComicFile>> {
    let mut comic_files = Vec::new();
    
    // Try the pattern as provided first
    let patterns_to_try = vec![
        pattern.to_string(),
        // If pattern doesn't start with / or **, try making it recursive
        if !pattern.starts_with('/') && !pattern.starts_with("**") {
            format!("**/{}", pattern)
        } else {
            pattern.to_string()
        }
    ];
    
    for pattern_attempt in patterns_to_try {
        for entry in glob(&pattern_attempt).context("Failed to read glob pattern")? {
            match entry {
                Ok(path) => {
                    if path.is_file() {
                        if let Ok(comic_file) = detect_comic_file(&path) {
                            comic_files.push(comic_file);
                        }
                    }
                }
                Err(_) => {
                    // Silently skip glob pattern errors
                }
            }
        }
        
        // If we found files with this pattern, don't try others
        if !comic_files.is_empty() {
            break;
        }
    }

    if comic_files.is_empty() {
        println!("⚠️  No comic files found matching pattern: '{}'", pattern);
        println!("💡 Try patterns like:");
        println!("   - \"**/*Killer*.cbr\" (recursive search)");
        println!("   - \"/full/path/**/Killer*.cbr\" (absolute path)");
        println!("   - \"**/De Killer*.cbr\" (your specific case)");
    }

    Ok(comic_files)
}

fn process_comic_file(
    comic_file: &ComicFile,
    args: &Args,
    progress: &ProgressBar,
) -> Result<ProcessingStats> {
    let original_size = fs::metadata(&comic_file.path)?.len();

    let temp_dir = TempDir::new().context("Failed to create temporary directory")?;
    progress.set_position(10);

    extract_comic(&comic_file, temp_dir.path(), progress)?;
    progress.set_position(30);

    let image_files = find_image_files(temp_dir.path())?;
    let stats = process_images(&image_files, args, progress)?;
    progress.set_position(80);

    // Always create compressed file with temporary name first to avoid overwriting original
    let temp_output_path = if args.rename_original {
        let parent = comic_file.path.parent().unwrap_or_else(|| Path::new("."));
        let stem = comic_file.path.file_stem().unwrap().to_string_lossy();
        parent.join(format!("{}_temp_compressed.cbr", stem))
    } else {
        generate_output_path(&comic_file.path, args.quality, false)
    };
    
    create_cbr_archive(temp_dir.path(), &temp_output_path, progress)?;
    progress.set_position(90);

    let compressed_size = fs::metadata(&temp_output_path)?.len();

    // Calculate compression savings
    let savings_percent = if original_size > 0 {
        ((original_size as f64 - compressed_size as f64) / original_size as f64) * 100.0
    } else {
        0.0
    };

    // Check if compression provides significant benefit
    let compression_skipped = savings_percent < args.min_savings;
    
    if compression_skipped {
        // Remove the compressed file and keep original
        fs::remove_file(&temp_output_path)
            .context("Failed to remove temporary compressed file")?;
        
        progress.set_position(100);
        
        return Ok(ProcessingStats {
            original_size,
            compressed_size: original_size, // No compression applied
            images_processed: stats.0,
            images_skipped: stats.1,
            compression_skipped: true,
            error_message: None,
        });
    }

    // Handle renaming if requested and compression was beneficial
    if args.rename_original {
        let original_path = &comic_file.path;
        let original_extension = original_path.extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("cbr");
        
        let parent = original_path.parent().unwrap_or_else(|| Path::new("."));
        let stem = original_path.file_stem().unwrap().to_string_lossy();
        let backup_path = parent.join(format!("{}_original.{}", stem, original_extension));
        let final_compressed_path = parent.join(format!("{}.cbr", stem));
        
        // Rename original file to backup name
        fs::rename(original_path, &backup_path)
            .context("Failed to rename original file")?;
            
        // Rename compressed file to original name
        fs::rename(&temp_output_path, &final_compressed_path)
            .context("Failed to rename compressed file")?;
    }
    
    progress.set_position(100);

    Ok(ProcessingStats {
        original_size,
        compressed_size,
        images_processed: stats.0,
        images_skipped: stats.1,
        compression_skipped: false,
        error_message: None,
    })
}

fn extract_comic(comic_file: &ComicFile, temp_dir: &Path, _progress: &ProgressBar) -> Result<()> {
    match comic_file.file_type {
        ComicType::Cbz => {
            extract_zip_archive(&comic_file.path, temp_dir)?;
        }
        ComicType::Cbr => {
            // Try RAR first, fallback to ZIP if it fails (some CBR files are actually ZIP)
            if let Err(_) = extract_rar_archive(&comic_file.path, temp_dir) {
                extract_zip_archive(&comic_file.path, temp_dir)
                    .context("Failed to extract CBR file as both RAR and ZIP")?;
            }
        }
        ComicType::Pdf => {
            extract_pdf_archive(&comic_file.path, temp_dir)?;
        }
    }
    Ok(())
}

fn extract_zip_archive(archive_path: &Path, temp_dir: &Path) -> Result<()> {
    let file = File::open(archive_path)?;
    let reader = BufReader::new(file);
    let mut archive = zip::ZipArchive::new(reader)?;

    for i in 0..archive.len() {
        let mut file = archive.by_index(i)?;
        let file_path = temp_dir.join(file.name());

        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent)?;
        }

        let mut output_file = File::create(&file_path)?;
        std::io::copy(&mut file, &mut output_file)?;
    }

    Ok(())
}

fn extract_rar_archive(archive_path: &Path, temp_dir: &Path) -> Result<()> {
    let archive = unrar::Archive::new(archive_path)
        .open_for_processing()
        .map_err(|e| anyhow::anyhow!("Failed to open RAR archive: {:?}", e))?;

    let mut current_archive = archive;

    loop {
        match current_archive.read_header() {
            Ok(Some(archive_with_header)) => {
                // Extract the current file to the temp directory
                let archive_after_extract = archive_with_header
                    .extract_with_base(temp_dir)
                    .map_err(|e| anyhow::anyhow!("Failed to extract RAR entry: {:?}", e))?;

                current_archive = archive_after_extract;
            }
            Ok(None) => {
                // No more files in the archive
                break;
            }
            Err(e) => {
                return Err(anyhow::anyhow!("Failed to read RAR header: {:?}", e));
            }
        }
    }

    Ok(())
}

fn extract_pdf_archive(pdf_path: &Path, temp_dir: &Path) -> Result<()> {
    use lopdf::{Document, Object};
    
    // Load the PDF document
    let doc = Document::load(pdf_path)
        .map_err(|e| anyhow::anyhow!("Failed to load PDF: {:?}", e))?;
    
    let mut image_counter = 1;
    
    // Iterate through all pages
    let pages = doc.get_pages();
    for (_, page_object_id) in pages {
        // Get page object
        if let Ok(page_object) = doc.get_object(page_object_id) {
            if let Object::Dictionary(page_dict) = page_object {
                extract_images_from_page(&doc, page_dict, temp_dir, &mut image_counter)?;
            }
        }
    }
    
    if image_counter == 1 {
        anyhow::bail!("No images found in PDF - this might not be a comic book PDF with embedded images");
    }
    
    Ok(())
}

fn extract_images_from_page(
    doc: &lopdf::Document, 
    page_dict: &lopdf::Dictionary,
    temp_dir: &Path,
    image_counter: &mut usize
) -> Result<()> {
    use lopdf::Object;
    
    // Look for Resources -> XObject
    if let Ok(Object::Dictionary(resources)) = page_dict.get(b"Resources") {
        if let Ok(Object::Dictionary(xobject)) = resources.get(b"XObject") {
            // Iterate through XObjects to find images
            for (name, obj_ref) in xobject {
                if let Object::Reference(ref_id) = obj_ref {
                    if let Ok(Object::Stream(stream)) = doc.get_object(*ref_id) {
                        if let Ok(Object::Name(subtype)) = stream.dict.get(b"Subtype") {
                            if subtype == b"Image" {
                                // Extract the image
                                extract_image_from_stream(&stream, temp_dir, *image_counter, name)?;
                                *image_counter += 1;
                            }
                        }
                    }
                }
            }
        }
    }
    
    Ok(())
}

fn extract_image_from_stream(
    stream: &lopdf::Stream,
    temp_dir: &Path,
    image_number: usize,
    _name: &[u8]
) -> Result<()> {
    use lopdf::Object;
    
    // Get image properties
    let width = stream.dict.get(b"Width")
        .ok()
        .and_then(|obj| obj.as_i64().ok())
        .unwrap_or(0);
    
    let height = stream.dict.get(b"Height")
        .ok()
        .and_then(|obj| obj.as_i64().ok())
        .unwrap_or(0);
    
    let bits_per_component = stream.dict.get(b"BitsPerComponent")
        .ok()
        .and_then(|obj| obj.as_i64().ok())
        .unwrap_or(8) as u32;
    
    // Check the filter to determine image format
    if let Ok(Object::Name(filter)) = stream.dict.get(b"Filter") {
        match filter.as_slice() {
            b"DCTDecode" => {
                // JPEG - save directly
                let output_path = temp_dir.join(format!("page_{:04}.jpg", image_number));
                fs::write(&output_path, &stream.content)
                    .map_err(|e| anyhow::anyhow!("Failed to save JPEG image: {:?}", e))?;
                return Ok(());
            }
            b"FlateDecode" => {
                // PNG or other compressed format - need to reconstruct
                extract_flate_decoded_image(stream, temp_dir, image_number, width as u32, height as u32, bits_per_component)?;
                return Ok(());
            }
            b"CCITTFaxDecode" => {
                // TIFF/Fax format - skip for now
                println!("Skipping CCITT Fax image {}x{} (not supported yet)", width, height);
                return Ok(());
            }
            _ => {
                println!("Skipping unsupported image format {}x{} (filter: {:?})", 
                         width, height, filter);
                return Ok(());
            }
        }
    } else {
        // No filter - raw image data
        extract_raw_image(stream, temp_dir, image_number, width as u32, height as u32, bits_per_component)?;
    }
    
    Ok(())
}

fn extract_flate_decoded_image(
    stream: &lopdf::Stream,
    temp_dir: &Path,
    image_number: usize,
    width: u32,
    height: u32,
    bits_per_component: u32,
) -> Result<()> {
    use lopdf::Object;
    use flate2::read::ZlibDecoder;
    use std::io::Read;
    
    // Decompress the data
    let mut decoder = ZlibDecoder::new(stream.content.as_slice());
    let mut decompressed_data = Vec::new();
    decoder.read_to_end(&mut decompressed_data)
        .map_err(|e| anyhow::anyhow!("Failed to decompress image data: {:?}", e))?;
    
    // Get color space
    let color_space = stream.dict.get(b"ColorSpace")
        .ok()
        .and_then(|obj| match obj {
            Object::Name(name) => Some(name.as_slice()),
            _ => None,
        });
    
    // Create image based on color space and bit depth
    let output_path = temp_dir.join(format!("page_{:04}.png", image_number));
    
    match (color_space.map(|cs| cs), bits_per_component) {
        (Some(b"DeviceRGB"), 8) => {
            // RGB image
            let img = image::RgbImage::from_raw(width, height, decompressed_data)
                .ok_or_else(|| anyhow::anyhow!("Failed to create RGB image from raw data"))?;
            image::DynamicImage::ImageRgb8(img).save(&output_path)
                .map_err(|e| anyhow::anyhow!("Failed to save PNG image: {:?}", e))?;
        }
        (Some(b"DeviceGray"), 8) => {
            // Grayscale image
            let img = image::GrayImage::from_raw(width, height, decompressed_data)
                .ok_or_else(|| anyhow::anyhow!("Failed to create grayscale image from raw data"))?;
            image::DynamicImage::ImageLuma8(img).save(&output_path)
                .map_err(|e| anyhow::anyhow!("Failed to save PNG image: {:?}", e))?;
        }
        (Some(b"DeviceCMYK"), 8) => {
            // CMYK - convert to RGB (simplified conversion)
            if decompressed_data.len() == (width * height * 4) as usize {
                let mut rgb_data = Vec::with_capacity((width * height * 3) as usize);
                for chunk in decompressed_data.chunks(4) {
                    let c = chunk[0] as f32 / 255.0;
                    let m = chunk[1] as f32 / 255.0;
                    let y = chunk[2] as f32 / 255.0;
                    let k = chunk[3] as f32 / 255.0;
                    
                    // Simple CMYK to RGB conversion
                    let r = ((1.0 - c) * (1.0 - k) * 255.0) as u8;
                    let g = ((1.0 - m) * (1.0 - k) * 255.0) as u8;
                    let b = ((1.0 - y) * (1.0 - k) * 255.0) as u8;
                    
                    rgb_data.extend_from_slice(&[r, g, b]);
                }
                
                let img = image::RgbImage::from_raw(width, height, rgb_data)
                    .ok_or_else(|| anyhow::anyhow!("Failed to create RGB image from CMYK data"))?;
                image::DynamicImage::ImageRgb8(img).save(&output_path)
                    .map_err(|e| anyhow::anyhow!("Failed to save PNG image: {:?}", e))?;
            } else {
                return Err(anyhow::anyhow!("CMYK data size mismatch"));
            }
        }
        _ => {
            println!("Skipping unsupported color space/bit depth: {:?}/{}", 
                     color_space.map(|cs| std::str::from_utf8(cs).unwrap_or("invalid")), 
                     bits_per_component);
            return Ok(());
        }
    }
    
    Ok(())
}

fn extract_raw_image(
    stream: &lopdf::Stream,
    temp_dir: &Path,
    image_number: usize,
    width: u32,
    height: u32,
    bits_per_component: u32,
) -> Result<()> {
    use lopdf::Object;
    
    // Get color space
    let color_space = stream.dict.get(b"ColorSpace")
        .ok()
        .and_then(|obj| match obj {
            Object::Name(name) => Some(name.as_slice()),
            _ => None,
        });
    
    let output_path = temp_dir.join(format!("page_{:04}.png", image_number));
    
    match (color_space.map(|cs| cs), bits_per_component) {
        (Some(b"DeviceRGB"), 8) => {
            let img = image::RgbImage::from_raw(width, height, stream.content.clone())
                .ok_or_else(|| anyhow::anyhow!("Failed to create RGB image from raw data"))?;
            image::DynamicImage::ImageRgb8(img).save(&output_path)
                .map_err(|e| anyhow::anyhow!("Failed to save PNG image: {:?}", e))?;
        }
        (Some(b"DeviceGray"), 8) => {
            let img = image::GrayImage::from_raw(width, height, stream.content.clone())
                .ok_or_else(|| anyhow::anyhow!("Failed to create grayscale image from raw data"))?;
            image::DynamicImage::ImageLuma8(img).save(&output_path)
                .map_err(|e| anyhow::anyhow!("Failed to save PNG image: {:?}", e))?;
        }
        _ => {
            println!("Skipping unsupported raw image format: {:?}/{}", 
                     color_space.map(|cs| std::str::from_utf8(cs).unwrap_or("invalid")), 
                     bits_per_component);
            return Ok(());
        }
    }
    
    Ok(())
}

fn find_image_files(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut image_files = Vec::new();

    for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) {
        if entry.file_type().is_file() {
            let path = entry.path();
            if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
                match extension.to_lowercase().as_str() {
                    "jpg" | "jpeg" | "png" | "bmp" | "tiff" | "tif" => {
                        image_files.push(path.to_path_buf());
                    }
                    _ => {}
                }
            }
        }
    }

    image_files.sort();
    Ok(image_files)
}

fn process_images(
    image_files: &[PathBuf],
    args: &Args,
    progress: &ProgressBar,
) -> Result<(usize, usize)> {
    let (sender, receiver): (Sender<(PathBuf, bool)>, Receiver<(PathBuf, bool)>) = bounded(100);
    let processed_count = Arc::new(Mutex::new(0));
    let skipped_count = Arc::new(Mutex::new(0));
    let total_images = image_files.len();

    let progress_clone = progress.clone();
    let processed_clone = Arc::clone(&processed_count);
    let skipped_clone = Arc::clone(&skipped_count);

    thread::spawn(move || {
        for (_, success) in receiver {
            if success {
                *processed_clone.lock().unwrap() += 1;
            } else {
                *skipped_clone.lock().unwrap() += 1;
            }

            let current = *processed_clone.lock().unwrap() + *skipped_clone.lock().unwrap();
            let progress_percent = 30 + ((current * 50) / total_images);
            // Only update progress every 10% to reduce output noise, plus important milestones
            if progress_percent % 10 == 0 || current == total_images || progress_percent >= 80 {
                progress_clone.set_position(progress_percent as u64);
            }
        }
    });

    image_files.par_iter().for_each(|image_path| {
        let result = process_single_image(image_path, args);
        match &result {
            Err(e) => {
                if args.verbose {
                    eprintln!("Warning: Failed to process image {}: {}. Skipping...", 
                              image_path.display(), e);
                }
                sender.send((image_path.clone(), false)).unwrap();
            }
            Ok(_) => {
                sender.send((image_path.clone(), true)).unwrap();
            }
        }
    });

    drop(sender);
    thread::sleep(std::time::Duration::from_millis(100));

    let processed = *processed_count.lock().unwrap();
    let skipped = *skipped_count.lock().unwrap();

    Ok((processed, skipped))
}

fn process_single_image(image_path: &Path, args: &Args) -> Result<()> {
    let img = ImageReader::open(image_path)?.decode()?;

    let (width, height) = (img.width(), img.height());
    let aspect_ratio = width as f32 / height as f32;

    let new_height = args.target_height;
    let new_width = if aspect_ratio > 1.3 {
        (new_height as f32 * aspect_ratio) as u32
    } else {
        (new_height as f32 * aspect_ratio) as u32
    };

    let resized = img.resize(new_width, new_height, image::imageops::FilterType::Lanczos3);

    let webp_path = image_path.with_extension("webp");

    let webp_bytes = encode_webp(&resized, args.quality)?;

    if webp_bytes.len() < fs::metadata(image_path)?.len() as usize {
        fs::write(&webp_path, webp_bytes)?;
        fs::remove_file(image_path)?;
        Ok(())
    } else {
        Err(anyhow::anyhow!("WebP compression didn't reduce file size"))
    }
}

fn encode_webp(img: &image::DynamicImage, quality: u8) -> Result<Vec<u8>> {
    let rgb_img = img.to_rgb8();
    let (width, height) = rgb_img.dimensions();

    let encoder = webp::Encoder::from_rgb(&rgb_img, width, height);
    let encoded = encoder.encode(quality as f32);

    Ok(encoded.to_vec())
}

fn create_cbr_archive(temp_dir: &Path, output_path: &Path, _progress: &ProgressBar) -> Result<()> {
    let file = File::create(output_path)?;
    let mut zip = ZipWriter::new(file);
    let options = FileOptions::<()>::default().compression_method(zip::CompressionMethod::Deflated);

    for entry in WalkDir::new(temp_dir).into_iter().filter_map(|e| e.ok()) {
        if entry.file_type().is_file() {
            let path = entry.path();
            let relative_path = path.strip_prefix(temp_dir)?;

            zip.start_file(relative_path.to_string_lossy(), options)?;
            let file_content = fs::read(path)?;
            zip.write_all(&file_content)?;
        }
    }

    zip.finish()?;
    Ok(())
}

fn generate_output_path(input_path: &Path, quality: u8, rename_original: bool) -> PathBuf {
    let parent = input_path.parent().unwrap_or_else(|| Path::new("."));
    let stem = input_path.file_stem().unwrap().to_string_lossy();
    
    if rename_original {
        // When renaming original, compressed file gets the original name (but as .cbr)
        parent.join(format!("{}.cbr", stem))
    } else {
        // Traditional naming with suffix
        parent.join(format!("{} optimized_webp_q{}.cbr", stem, quality))
    }
}

fn print_summary(stats: &HashMap<PathBuf, ProcessingStats>) {
    println!("\n📊 Processing Summary:");
    println!("-----------------------------------------------------");

    let mut total_original = 0u64;
    let mut total_compressed = 0u64;
    let mut total_images = 0;
    let mut total_skipped = 0;
    let mut files_compression_skipped = 0;
    let mut files_with_errors = 0;

    for (path, stat) in stats {
        if let Some(error_msg) = &stat.error_message {
            println!(
                "{}: Failed - {}",
                path.file_name().unwrap().to_string_lossy(),
                error_msg
            );
            files_with_errors += 1;
            continue;
        }

        if stat.compression_skipped {
            println!(
                "⏭️  {}: Skipped (already well-compressed, < {:.1}% potential savings)",
                path.file_name().unwrap().to_string_lossy(),
                // Calculate what the savings would have been
                if stat.original_size > 0 {
                    ((stat.original_size as f64 - stat.compressed_size as f64) / stat.original_size as f64) * 100.0
                } else { 0.0 }
            );
            files_compression_skipped += 1;
            total_original += stat.original_size;
            total_compressed += stat.compressed_size; // Same as original for skipped files
            continue;
        }

        let savings = if stat.original_size > stat.compressed_size {
            ((stat.original_size - stat.compressed_size) as f64 / stat.original_size as f64) * 100.0
        } else {
            0.0
        };

        let savings_mb = (stat.original_size - stat.compressed_size) as f64 / 1_048_576.0;
        println!(
            "📖 {}: {:.1}% savings ({:.1} MB saved, {} images processed, {} skipped)",
            path.file_name().unwrap().to_string_lossy(),
            savings,
            savings_mb,
            stat.images_processed,
            stat.images_skipped
        );

        total_original += stat.original_size;
        total_compressed += stat.compressed_size;
        total_images += stat.images_processed;
        total_skipped += stat.images_skipped;
    }

    let actually_compressed_files = stats.len() - files_compression_skipped - files_with_errors;
    let overall_savings = if total_original > total_compressed {
        ((total_original - total_compressed) as f64 / total_original as f64) * 100.0
    } else {
        0.0
    };

    println!("\n🎯 Overall Results:");
    println!("   Total files found: {}", stats.len());
    println!("   Files successfully compressed: {}", actually_compressed_files);
    if files_compression_skipped > 0 {
        println!("   Files skipped (already well-compressed): {}", files_compression_skipped);
    }
    if files_with_errors > 0 {
        println!("   Files with errors: {}", files_with_errors);
    }
    println!("   Total images processed: {}", total_images);
    println!("   Total images skipped: {}", total_skipped);
    let total_savings_mb = (total_original - total_compressed) as f64 / 1_048_576.0;
    println!("   Overall size reduction: {:.1}% ({:.1} MB saved)", overall_savings, total_savings_mb);
    println!(
        "   Original size: {:.1} MB",
        total_original as f64 / 1_048_576.0
    );
    println!(
        "   Final size: {:.1} MB",
        total_compressed as f64 / 1_048_576.0
    );

    if files_compression_skipped > 0 {
        println!(
            "\n💡 {} file(s) were already well-compressed and were left unchanged.",
            files_compression_skipped
        );
        println!("   These files likely use efficient compression already (e.g., RAR archives).");
    }
}