wsb 0.155.49

Workspace - A tool suite for file operations, version management, and development workflow automation
Documentation
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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
use anyhow::{Context, Result};
use rayon::prelude::*;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use walkdir::{DirEntry, WalkDir};

use super::{
    cli::{Args, Mode, OutputFormat},
    collision_detector::{CollisionDetector, CollisionType},
    file_ops::FileOperations,
    patterns_file::PatternPair,
    progress::{ProgressTracker, SimpleOutput},
};
use crate::{utils, ItemType, RenameConfig, RenameItem, RenameStats};

/// Detailed information about changes to a specific file/directory
#[derive(Debug, Clone)]
pub struct FileChangeReport {
    pub path: PathBuf,
    pub content_changes: Option<usize>, // Number of content occurrences to replace
    pub rename_target: Option<PathBuf>, // New path if being renamed
    pub item_type: ItemType,
}

/// Organized summary of all changes, grouped and sorted by location
#[derive(Debug, Clone)]
pub struct DetailedChangeReport {
    pub file_changes: Vec<FileChangeReport>,
    pub total_stats: RenameStats,
}

/// Structured validation error with location and context information
#[derive(Debug, Clone)]
pub struct ValidationError {
    pub location: PathBuf,
    pub error_type: ValidationErrorType,
    pub message: String,
    pub suggestion: Option<String>,
}

#[derive(Debug, Clone)]
pub enum ValidationErrorType {
    FileNotFound,
    PermissionDenied,
    EncodingError,
    NotAFile,
    NotADirectory,
    ReadOnlyFile,
    TargetExists,
    ParentDirectoryError,
    ContentNotFound,
    EmptyDirectoryIssue,
}

/// Main engine for executing rename operations
pub struct RenameEngine {
    config: RenameConfig,
    /// All pattern/substitute pairs to apply. For single-pair mode this has one entry.
    pairs: Vec<PatternPair>,
    mode: Mode,
    file_ops: FileOperations,
    progress: Option<ProgressTracker>,
    simple_output: Option<SimpleOutput>,
    thread_count: usize,
    output_format: OutputFormat,
    max_depth: Option<usize>,
    include_patterns: Vec<String>,
    exclude_patterns: Vec<String>,
    ignore_case: bool,
    use_regex: bool,
    include_hidden: bool,
    binary_names: bool,
}

impl RenameEngine {
    pub fn new(args: Args) -> Result<Self> {
        Self::new_with_pairs(args, Vec::new())
    }

    /// Construct engine with explicit pattern pairs (from --patterns-file or positional args).
    /// If `pairs` is empty, falls back to extracting from args.pattern/args.substitute.
    pub fn new_with_pairs(args: Args, pairs: Vec<PatternPair>) -> Result<Self> {
        args.validate().map_err(|e| anyhow::anyhow!(e))?;

        let pairs = if pairs.is_empty() {
            let pattern = args
                .pattern
                .clone()
                .ok_or_else(|| anyhow::anyhow!("Pattern is required"))?;
            let substitute = args
                .substitute
                .clone()
                .ok_or_else(|| anyhow::anyhow!("Substitute is required"))?;
            vec![PatternPair {
                pattern,
                substitute,
            }]
        } else {
            pairs
        };

        // Config uses first pair for root_dir canonicalization and flags.
        // The actual pattern/substitute come from self.pairs, not config.
        let config = RenameConfig::new(
            &args.root_dir,
            pairs[0].pattern.clone(),
            pairs[0].substitute.clone(),
        )?
        .with_assume_yes(args.assume_yes)
        .with_verbose(args.verbose)
        .with_follow_symlinks(args.follow_symlinks)
        .with_backup(args.backup);

        let show_progress = match args.progress {
            super::cli::ProgressMode::Always => true,
            super::cli::ProgressMode::Never => false,
            super::cli::ProgressMode::Auto => atty::is(atty::Stream::Stdout),
        };

        let (progress, simple_output) = if show_progress && args.format == OutputFormat::Human {
            (Some(ProgressTracker::new(true, args.verbose)), None)
        } else {
            (None, Some(SimpleOutput::new(args.verbose)))
        };

        Ok(Self {
            config,
            pairs,
            mode: args.get_mode(),
            file_ops: FileOperations::new().with_backup(args.backup),
            progress,
            simple_output,
            thread_count: args.get_thread_count(),
            output_format: args.format,
            max_depth: if args.max_depth > 0 {
                Some(args.max_depth)
            } else {
                None
            },
            include_patterns: args.include_patterns,
            exclude_patterns: args.exclude_patterns,
            ignore_case: args.ignore_case,
            use_regex: args.use_regex,
            include_hidden: args.include_hidden,
            binary_names: args.binary_names,
        })
    }

    /// Execute the rename operation
    pub fn execute(&self) -> Result<()> {
        self.print_header()?;

        // Phase 1: Discovery
        self.print_info("Phase 1: Discovering files and directories...")?;
        let (content_files, rename_items) = self.discover_items()?;

        // Phase 2: Collision Detection
        self.print_info("Phase 2: Checking for naming collisions...")?;
        self.check_collisions(&rename_items)?;

        // Phase 3: Mandatory Validation (Dry-Run)
        self.print_info("Phase 3: Validating all operations...")?;
        self.validate_all_operations(&content_files, &rename_items)?;

        // Phase 4: Summary and Confirmation
        let stats = self.show_summary(&content_files, &rename_items)?;
        if stats.total_changes() == 0 {
            self.print_success("No changes needed.")?;
            return Ok(());
        }

        // Phase 4.5: Show diff preview for content changes
        if !content_files.is_empty() && self.output_format == OutputFormat::Human {
            self.show_diff_preview(&content_files)?;
        }

        if !self.confirm_changes()? {
            self.print_info("Operation cancelled by user.")?;
            return Ok(());
        }

        // Phase 5: Execute Changes
        self.execute_changes(&content_files, &rename_items)?;

        // Phase 5: Final Report
        self.show_final_report(&stats)?;

        Ok(())
    }

    /// Discover files for content replacement and items for renaming.
    /// Walks the directory tree once. For multi-pair mode, checks all pairs
    /// and computes the final destination path by applying all pairs sequentially
    /// to each path component.
    fn discover_items(&self) -> Result<(Vec<PathBuf>, Vec<RenameItem>)> {
        let mut content_files = Vec::new();
        let mut rename_items = Vec::new();

        if let Some(progress) = &self.progress {
            progress.init_main_progress(0, "Scanning files and directories...");
        }

        let walker = WalkDir::new(&self.config.root_dir)
            .follow_links(self.config.follow_symlinks)
            .max_depth(self.max_depth.unwrap_or(usize::MAX))
            .into_iter()
            .filter_entry(|e| self.should_process_entry(e));

        for entry in walker {
            let entry = entry.with_context(|| "Failed to read directory entry")?;
            let path = entry.path();

            if path == self.config.root_dir {
                continue;
            }

            if !self.matches_patterns(path)? {
                continue;
            }

            // Check for content replacement in files
            if self.should_process_content() && self.should_process_files() && path.is_file() {
                if self.file_needs_content_replacement(path)? {
                    content_files.push(path.to_path_buf());
                }
            }

            // Check for renaming
            if self.should_process_names() {
                if let Some(rename_item) = self.create_rename_item(path)? {
                    rename_items.push(rename_item);
                }
            }

            if let Some(progress) = &self.progress {
                progress.update_main(&format!("Scanned: {}", path.display()));
            }
        }

        // Sort: files first (deepest first), then directories (deepest first).
        // This ensures children are renamed before parents so paths stay valid.
        rename_items.sort_by(|a, b| match (&a.item_type, &b.item_type) {
            (ItemType::File, ItemType::Directory) => std::cmp::Ordering::Less,
            (ItemType::Directory, ItemType::File) => std::cmp::Ordering::Greater,
            (ItemType::File, ItemType::File) => b.depth.cmp(&a.depth),
            (ItemType::Directory, ItemType::Directory) => b.depth.cmp(&a.depth),
        });

        if let Some(progress) = &self.progress {
            progress.finish_main("Discovery complete");
        }

        Ok((content_files, rename_items))
    }

    /// Check if an entry should be processed
    fn should_process_entry(&self, entry: &DirEntry) -> bool {
        let path = entry.path();

        // Don't skip the root directory itself, even if it's hidden
        if path == self.config.root_dir {
            return true;
        }

        // Skip hidden files unless explicitly included
        if let Some(name) = path.file_name() {
            if let Some(name_str) = name.to_str() {
                if name_str.starts_with('.') {
                    // Check if include_hidden flag is set
                    if self.include_hidden {
                        // Include hidden files when flag is set
                    } else {
                        // Original logic: check include patterns
                        let should_include = self
                            .include_patterns
                            .iter()
                            .any(|p| p == ".*" || p.contains("*"));
                        if !should_include {
                            return false;
                        }
                    }
                }
            }
        }

        // Check file type restrictions
        match self.mode {
            Mode::FilesOnly => path.is_file(),
            Mode::DirsOnly => path.is_dir(),
            _ => true,
        }
    }

    /// Check if a path matches include/exclude patterns
    fn matches_patterns(&self, path: &Path) -> Result<bool> {
        // If there are include patterns, the file must match at least one
        if !self.include_patterns.is_empty() {
            let matches = self
                .include_patterns
                .iter()
                .any(|pattern| self.path_matches_pattern(path, pattern));
            if !matches {
                return Ok(false);
            }
        }

        // If there are exclude patterns, the file must not match any
        if !self.exclude_patterns.is_empty() {
            let excluded = self
                .exclude_patterns
                .iter()
                .any(|pattern| self.path_matches_pattern(path, pattern));
            if excluded {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Check if a path matches a glob pattern
    fn path_matches_pattern(&self, path: &Path, pattern: &str) -> bool {
        // Simple glob matching - could be enhanced with a proper glob library
        let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
        let pattern_str = if self.ignore_case {
            pattern.to_lowercase()
        } else {
            pattern.to_string()
        };
        let compare_str = if self.ignore_case {
            file_name.to_lowercase()
        } else {
            file_name.to_string()
        };

        if self.use_regex {
            // Use regex matching
            if let Ok(regex) = regex::Regex::new(&pattern_str) {
                return regex.is_match(&compare_str);
            }
        }

        // Special case for ".*" pattern to match hidden files
        if pattern_str == ".*" {
            return compare_str.starts_with('.');
        }

        // Simple glob-style matching
        if pattern_str.contains('*') {
            let parts: Vec<&str> = pattern_str.split('*').collect();
            if parts.len() == 2 {
                return compare_str.starts_with(parts[0]) && compare_str.ends_with(parts[1]);
            }
        }

        compare_str.contains(&pattern_str)
    }

    /// Check if a file needs content replacement by any of the pairs.
    /// We check whether the file contains ANY pair's pattern. Note that a later pair's
    /// pattern might only appear after an earlier pair's substitution transforms the content,
    /// but we can't know that without actually doing the replacement. So we also include
    /// files that contain any pair's substitute when there are subsequent pairs, since
    /// an earlier pair could produce text that a later pair matches.
    ///
    /// For correctness without over-reading, we check if the file contains any pattern
    /// from any pair. If pair 1 produces text that pair 2 matches, pair 2's pattern won't
    /// be in the original file — but pair 1's pattern WILL be. So the file gets picked up
    /// for content processing. During execution, replace_content_multi applies all pairs
    /// sequentially and handles the cascade.
    fn file_needs_content_replacement(&self, path: &Path) -> Result<bool> {
        if !self.file_ops.is_text_file(path)? {
            return Ok(false);
        }

        let search_strings: Vec<&str> = self
            .pairs
            .iter()
            .map(|p| {
                if self.ignore_case {
                    // This is a simplification — proper case-insensitive needs regex
                    p.pattern.as_str()
                } else {
                    p.pattern.as_str()
                }
            })
            .collect();

        self.file_ops
            .file_contains_any_string(path, &search_strings)
    }

    /// Apply all pattern pairs sequentially to a name string, returning the final name.
    fn apply_pairs_to_name(&self, name: &str) -> String {
        let mut result = name.to_string();
        for pair in &self.pairs {
            if self.ignore_case {
                // Case-insensitive: match against lowercased, replace in the lowercased string
                result = result
                    .to_lowercase()
                    .replace(&pair.pattern.to_lowercase(), &pair.substitute);
            } else {
                result = result.replace(&pair.pattern, &pair.substitute);
            }
        }
        result
    }

    /// Create a rename item if the path needs renaming after applying all pairs.
    fn create_rename_item(&self, path: &Path) -> Result<Option<RenameItem>> {
        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| anyhow::anyhow!("Invalid file name: {}", path.display()))?;

        // Apply all pairs to this entry's own name. If the name doesn't change,
        // this entry doesn't need a rename item (parent renames are separate items).
        let final_name = self.apply_pairs_to_name(file_name);

        if final_name == file_name {
            return Ok(None);
        }

        // Check binary file handling for files
        if path.is_file() {
            match self.file_ops.is_text_file(path) {
                Ok(false) => {
                    if !self.binary_names {
                        return Ok(None);
                    }
                }
                Err(_) => {
                    if !self.binary_names {
                        return Ok(None);
                    }
                }
                Ok(true) => {}
            }
        }

        // Apply type restrictions
        let item_type = if path.is_file() {
            if !self.should_process_files() {
                return Ok(None);
            }
            ItemType::File
        } else {
            if !self.should_process_dirs() {
                return Ok(None);
            }
            ItemType::Directory
        };

        let depth = utils::calculate_depth(path, &self.config.root_dir);

        // For the rename item, the new_path is the final computed path.
        // But we only rename this entry's own name, not its parents (parents get their
        // own rename items). So new_path should only change THIS entry's name component,
        // keeping the original parent path — the parent's rename item handles the parent.
        let new_path = path.with_file_name(&final_name);

        Ok(Some(RenameItem {
            original_path: path.to_path_buf(),
            new_path,
            item_type,
            depth,
        }))
    }

    /// Check for collisions in the rename operations
    fn check_collisions(&self, rename_items: &[RenameItem]) -> Result<()> {
        if rename_items.is_empty() {
            return Ok(());
        }

        let mut detector = CollisionDetector::new();

        // Scan existing paths
        detector.scan_existing_paths(&self.config.root_dir)?;

        // Add rename operations
        detector.add_renames(rename_items);

        // Detect collisions
        let collisions = detector.detect_collisions()?;

        if !collisions.is_empty() {
            self.print_error("Naming collisions detected!")?;

            for collision in &collisions {
                match collision.collision_type {
                    CollisionType::SourceEqualsTarget => {
                        // Skip no-op renames
                        continue;
                    }
                    _ => {
                        self.print_error(&collision.description)?;
                    }
                }
            }

            let serious_collisions: Vec<_> = collisions
                .iter()
                .filter(|c| c.collision_type != CollisionType::SourceEqualsTarget)
                .collect();

            if !serious_collisions.is_empty() {
                anyhow::bail!(
                    "Cannot proceed due to {} naming collision(s)",
                    serious_collisions.len()
                );
            }
        }

        Ok(())
    }

    /// Generate detailed report of all changes organized by file/directory
    fn generate_detailed_report(
        &self,
        content_files: &[PathBuf],
        rename_items: &[RenameItem],
    ) -> Result<DetailedChangeReport> {
        use std::collections::HashMap;

        let mut file_changes_map: HashMap<PathBuf, FileChangeReport> = HashMap::new();
        let mut stats = RenameStats::default();

        // Process content changes
        for file_path in content_files {
            // Count total occurrences across all pairs by simulating the sequential replacement
            let content_count = match std::fs::read_to_string(file_path) {
                Ok(content) => {
                    let mut total = 0;
                    let mut current = content;
                    for pair in &self.pairs {
                        let count = current.matches(&pair.pattern).count();
                        total += count;
                        if count > 0 {
                            current = current.replace(&pair.pattern, &pair.substitute);
                        }
                    }
                    total
                }
                Err(_) => 0,
            };

            file_changes_map.insert(
                file_path.clone(),
                FileChangeReport {
                    path: file_path.clone(),
                    content_changes: Some(content_count),
                    rename_target: None,
                    item_type: ItemType::File,
                },
            );
            stats.files_with_content_changes += 1;
        }

        // Process rename operations
        for item in rename_items {
            let entry = file_changes_map
                .entry(item.original_path.clone())
                .or_insert_with(|| FileChangeReport {
                    path: item.original_path.clone(),
                    content_changes: None,
                    rename_target: None,
                    item_type: item.item_type.clone(),
                });

            entry.rename_target = Some(item.new_path.clone());
            entry.item_type = item.item_type.clone();

            match item.item_type {
                ItemType::File => stats.files_renamed += 1,
                ItemType::Directory => stats.directories_renamed += 1,
            }
        }

        // Convert to sorted vector (by path for consistent ordering)
        let mut file_changes: Vec<FileChangeReport> = file_changes_map.into_values().collect();
        file_changes.sort_by(|a, b| a.path.cmp(&b.path));

        Ok(DetailedChangeReport {
            file_changes,
            total_stats: stats,
        })
    }

    /// Show detailed summary of changes organized by file/directory
    fn show_summary(
        &self,
        content_files: &[PathBuf],
        rename_items: &[RenameItem],
    ) -> Result<RenameStats> {
        let report = self.generate_detailed_report(content_files, rename_items)?;

        match self.output_format {
            OutputFormat::Json => {
                let json_report = serde_json::json!({
                    "summary": {
                        "content_changes": report.total_stats.files_with_content_changes,
                        "file_renames": report.total_stats.files_renamed,
                        "directory_renames": report.total_stats.directories_renamed,
                        "total_changes": report.total_stats.total_changes()
                    },
                    "file_changes": report.file_changes.iter().map(|fc| {
                        serde_json::json!({
                            "path": fc.path,
                            "content_changes": fc.content_changes,
                            "rename_target": fc.rename_target,
                            "item_type": format!("{:?}", fc.item_type)
                        })
                    }).collect::<Vec<_>>()
                });
                println!("{}", serde_json::to_string_pretty(&json_report)?);
            }
            OutputFormat::Plain => {
                println!(
                    "Content changes: {}",
                    report.total_stats.files_with_content_changes
                );
                println!("File renames: {}", report.total_stats.files_renamed);
                println!(
                    "Directory renames: {}",
                    report.total_stats.directories_renamed
                );
                println!("Total changes: {}", report.total_stats.total_changes());
            }
            OutputFormat::Human => {
                self.print_info("=== PLANNED CHANGES ===")?;
                self.print_info(&format!(
                    "Total files/directories affected: {}",
                    report.file_changes.len()
                ))?;
                self.print_info(&format!(
                    "Content modifications: {} file(s)",
                    report.total_stats.files_with_content_changes
                ))?;
                self.print_info(&format!(
                    "File renames:         {} file(s)",
                    report.total_stats.files_renamed
                ))?;
                self.print_info(&format!(
                    "Directory renames:    {} directory(ies)",
                    report.total_stats.directories_renamed
                ))?;
                self.print_info("")?;

                if !report.file_changes.is_empty() {
                    self.print_info("=== DETAILED CHANGES BY LOCATION ===")?;

                    for change in &report.file_changes {
                        let relative_path = change
                            .path
                            .strip_prefix(&self.config.root_dir)
                            .unwrap_or(&change.path);

                        self.print_info(&format!("📁 {}", relative_path.display()))?;

                        // Show content changes
                        if let Some(count) = change.content_changes {
                            if self.pairs.len() == 1 {
                                self.print_verbose(&format!(
                                    "   Content: {} occurrence(s) of '{}' → '{}'",
                                    count, self.pairs[0].pattern, self.pairs[0].substitute
                                ))?;
                            } else {
                                self.print_verbose(&format!(
                                    "   Content: {} total replacement(s) across {} pairs",
                                    count,
                                    self.pairs.len()
                                ))?;
                            }
                        }

                        // Show rename operation
                        if let Some(target) = &change.rename_target {
                            let relative_target =
                                target.strip_prefix(&self.config.root_dir).unwrap_or(target);
                            self.print_verbose(&format!(
                                "   Rename:  {} → {}",
                                relative_path.display(),
                                relative_target.display()
                            ))?;
                        }
                    }
                }
            }
        }

        Ok(report.total_stats)
    }

    /// Show diff preview for content changes with colored +/- lines
    fn show_diff_preview(&self, content_files: &[PathBuf]) -> Result<()> {
        self.print_info("=== DIFF PREVIEW ===")?;

        for (i, file_path) in content_files.iter().enumerate() {
            if i >= 5 {
                // Limit preview to first 5 files to avoid overwhelming output
                self.print_info(&format!("... and {} more files", content_files.len() - i))?;
                break;
            }

            let relative_path = file_path
                .strip_prefix(&self.config.root_dir)
                .unwrap_or(file_path);

            // Read file content
            let content = match std::fs::read_to_string(file_path) {
                Ok(content) => content,
                Err(_) => {
                    self.print_warning(&format!(
                        "⚠️  Cannot preview {}: unable to read file",
                        relative_path.display()
                    ))?;
                    continue;
                }
            };

            self.print_info(&format!("\n⏺ Update({})", relative_path.display()))?;

            // Count replacements across all pairs
            let mut total_replacements = 0;
            let mut simulated = content.clone();
            for pair in &self.pairs {
                let count = simulated.matches(&pair.pattern).count();
                total_replacements += count;
                if count > 0 {
                    simulated = simulated.replace(&pair.pattern, &pair.substitute);
                }
            }

            self.print_verbose(&format!(
                "  ⎿  Updated {} with {} replacement(s)",
                relative_path.display(),
                total_replacements
            ))?;

            // Show context around changes
            self.show_diff_context(&content, file_path)?;
        }

        self.print_info("")?; // Empty line for spacing
        Ok(())
    }

    /// Show diff context with colored +/- lines for a specific file.
    /// Applies all pairs sequentially to each changed line.
    fn show_diff_context(&self, content: &str, _file_path: &Path) -> Result<()> {
        use colored::*;

        let lines: Vec<&str> = content.lines().collect();
        let mut changes_shown = 0;
        const MAX_CHANGES_TO_SHOW: usize = 3;

        for (i, line) in lines.iter().enumerate() {
            if changes_shown >= MAX_CHANGES_TO_SHOW {
                break;
            }

            // Check if any pair's pattern matches this line
            let line_matches = self.pairs.iter().any(|p| line.contains(&p.pattern));
            if !line_matches {
                continue;
            }

            let start_context = i.saturating_sub(2);
            let end_context = std::cmp::min(i + 3, lines.len());

            for j in start_context..i {
                let line_num = j + 1;
                println!(
                    "      {}        {}",
                    line_num.to_string().dimmed(),
                    lines[j]
                );
            }

            let line_num = i + 1;
            println!(
                "      {} {}      {}",
                line_num.to_string().dimmed(),
                "-".red().bold(),
                line.white().on_bright_red()
            );

            // Apply all pairs sequentially to get the final line
            let mut new_line = line.to_string();
            for pair in &self.pairs {
                new_line = new_line.replace(&pair.pattern, &pair.substitute);
            }

            println!(
                "      {} {}      {}",
                line_num.to_string().dimmed(),
                "+".green().bold(),
                new_line.white().on_bright_green()
            );

            for j in (i + 1)..end_context {
                let line_num = j + 1;
                println!(
                    "      {}        {}",
                    line_num.to_string().dimmed(),
                    lines[j]
                );
            }

            changes_shown += 1;

            if changes_shown < MAX_CHANGES_TO_SHOW && i + 3 < lines.len() {
                println!("      ...");
            }
        }

        Ok(())
    }

    /// Confirm changes with the user
    fn confirm_changes(&self) -> Result<bool> {
        if self.config.assume_yes {
            return Ok(true);
        }

        match self.output_format {
            OutputFormat::Json => Ok(true), // No confirmation in JSON mode
            OutputFormat::Plain | OutputFormat::Human => {
                self.print_warning("This operation will modify your files and directories.")?;

                let confirmation = if let Some(progress) = &self.progress {
                    progress.suspend(|| {
                        dialoguer::Confirm::new()
                            .with_prompt("Do you want to proceed?")
                            .default(false)
                            .interact()
                    })
                } else {
                    dialoguer::Confirm::new()
                        .with_prompt("Do you want to proceed?")
                        .default(false)
                        .interact()
                };

                confirmation.with_context(|| "Failed to get user confirmation")
            }
        }
    }

    /// Execute the actual changes
    fn execute_changes(
        &self,
        content_files: &[PathBuf],
        rename_items: &[RenameItem],
    ) -> Result<()> {
        // Phase 1: Content replacement
        if !content_files.is_empty() && self.should_process_content() {
            self.execute_content_changes(content_files)?;
        }

        // Phase 2: Rename items (directories first, then files)
        if !rename_items.is_empty() && self.should_process_names() {
            self.execute_renames(rename_items)?;
        }

        Ok(())
    }

    /// Execute content changes — applies all pairs sequentially per file, reading and writing once.
    fn execute_content_changes(&self, content_files: &[PathBuf]) -> Result<()> {
        self.print_info("Replacing content in files...")?;

        if let Some(progress) = &self.progress {
            progress.init_content_progress(content_files.len() as u64);
        }

        let errors = Arc::new(Mutex::new(Vec::new()));
        let file_ops_ref = &self.file_ops;
        let config_ref = &self.config;
        let pairs_tuples: Vec<(String, String)> = self
            .pairs
            .iter()
            .map(|p| (p.pattern.clone(), p.substitute.clone()))
            .collect();
        let errors_ref = Arc::clone(&errors);

        if self.thread_count > 1 {
            let pairs_ref = &pairs_tuples;
            content_files.par_iter().for_each(|file_path| {
                if !file_path.exists() {
                    errors_ref
                        .lock()
                        .unwrap()
                        .push(format!("File no longer exists: {}", file_path.display()));
                    return;
                }

                let result = file_ops_ref.replace_content_multi(file_path, pairs_ref);

                match result {
                    Ok(_) => {}
                    Err(e) => {
                        errors_ref.lock().unwrap().push(format!(
                            "Failed to modify {}: {}",
                            file_path.display(),
                            e
                        ));
                    }
                }
            });
        } else {
            for file_path in content_files {
                if !file_path.exists() {
                    self.print_error(&format!("File no longer exists: {}", file_path.display()))?;
                    if let Some(progress) = &self.progress {
                        progress.update_content(&file_path.display().to_string());
                    }
                    continue;
                }

                let result = file_ops_ref.replace_content_multi(file_path, &pairs_tuples);

                match result {
                    Ok(modified) => {
                        if modified && config_ref.verbose {
                            self.print_verbose(&format!("Modified: {}", file_path.display()))?;
                        }
                    }
                    Err(e) => {
                        self.print_error(&format!(
                            "Failed to modify {}: {}",
                            file_path.display(),
                            e
                        ))?;
                    }
                }

                if let Some(progress) = &self.progress {
                    progress.update_content(&file_path.display().to_string());
                }
            }
        }

        let errors = errors.lock().unwrap();
        for error in errors.iter() {
            self.print_error(error)?;
        }

        if let Some(progress) = &self.progress {
            progress.finish_content(&format!(
                "Content replacement complete ({} files)",
                content_files.len()
            ));
        }

        Ok(())
    }

    /// Execute rename operations with proper ordering and error handling
    fn execute_renames(&self, rename_items: &[RenameItem]) -> Result<()> {
        self.print_info("Renaming files and directories...")?;

        if let Some(progress) = &self.progress {
            progress.init_rename_progress(rename_items.len() as u64);
        }

        let mut errors = Vec::new();
        let mut successful_renames = Vec::new();

        // Process renames sequentially to maintain ordering (files before directories)
        for item in rename_items {
            // Skip no-op renames
            if item.original_path == item.new_path {
                if let Some(progress) = &self.progress {
                    progress.update_rename(&item.original_path.display().to_string());
                }
                continue;
            }

            // Validate that source still exists (in case of race conditions, including broken symlinks)
            let source_exists =
                item.original_path.exists() || item.original_path.symlink_metadata().is_ok();
            if !source_exists {
                errors.push(format!(
                    "Source path no longer exists: {}",
                    item.original_path.display()
                ));
                if let Some(progress) = &self.progress {
                    progress.update_rename(&item.original_path.display().to_string());
                }
                continue;
            }

            // Ensure target directory exists
            if let Some(parent) = item.new_path.parent() {
                if let Err(e) = self.file_ops.create_dir_all(parent) {
                    errors.push(format!(
                        "Failed to create parent directory for {}: {}",
                        item.new_path.display(),
                        e
                    ));
                    if let Some(progress) = &self.progress {
                        progress.update_rename(&item.original_path.display().to_string());
                    }
                    continue;
                }
            }

            let result = self.file_ops.move_item(&item.original_path, &item.new_path);

            match result {
                Ok(()) => {
                    successful_renames.push((item.original_path.clone(), item.new_path.clone()));
                    if self.config.verbose {
                        self.print_verbose(&format!(
                            "Renamed: {} → {}",
                            item.original_path.display(),
                            item.new_path.display()
                        ))?;
                    }
                }
                Err(e) => {
                    errors.push(format!(
                        "Failed to rename {} to {}: {}",
                        item.original_path.display(),
                        item.new_path.display(),
                        e
                    ));
                }
            }

            if let Some(progress) = &self.progress {
                progress.update_rename(&item.original_path.display().to_string());
            }
        }

        // Report errors
        for error in &errors {
            self.print_error(error)?;
        }

        if !errors.is_empty() {
            self.print_warning(&format!(
                "{} rename operation(s) failed out of {}",
                errors.len(),
                rename_items.len()
            ))?;
        }

        if let Some(progress) = &self.progress {
            progress.finish_rename(&format!(
                "Rename complete ({} successful, {} failed)",
                successful_renames.len(),
                errors.len()
            ));
        }

        Ok(())
    }

    /// Validate all operations before execution (mandatory validation phase)
    /// This catches all potential issues before making any changes
    fn validate_all_operations(
        &self,
        content_files: &[PathBuf],
        rename_items: &[RenameItem],
    ) -> Result<()> {
        let mut validation_errors = Vec::new();

        // Validate content replacement operations
        for file_path in content_files {
            self.validate_content_file(file_path, &mut validation_errors);
        }

        // Validate rename operations
        for item in rename_items {
            self.validate_rename_item(item, &mut validation_errors);
        }

        // Validate that operation will not leave empty directories
        self.validate_no_empty_directories_remain(rename_items, &mut validation_errors)?;

        // Report all validation errors with enhanced formatting
        if !validation_errors.is_empty() {
            self.report_validation_errors(&validation_errors)?;

            // Create a more descriptive error message that includes error types
            let error_types: std::collections::HashSet<&str> = validation_errors
                .iter()
                .map(|e| match e.error_type {
                    ValidationErrorType::FileNotFound => "missing files",
                    ValidationErrorType::PermissionDenied => "permission issues",
                    ValidationErrorType::EncodingError => "encoding issues",
                    ValidationErrorType::ReadOnlyFile => "read-only files",
                    ValidationErrorType::TargetExists => "target conflicts",
                    ValidationErrorType::ParentDirectoryError => "directory issues",
                    ValidationErrorType::ContentNotFound => "content issues",
                    ValidationErrorType::EmptyDirectoryIssue => "directory structure issues",
                    _ => "other issues",
                })
                .collect();

            let error_summary = error_types.into_iter().collect::<Vec<_>>().join(", ");
            anyhow::bail!(
                "Operation cannot proceed due to {} validation error(s): {}",
                validation_errors.len(),
                error_summary
            );
        }

        self.print_info("Validation passed: All operations can be performed safely.")?;
        Ok(())
    }

    /// Validate a single content file for replacement operations
    fn validate_content_file(
        &self,
        file_path: &PathBuf,
        validation_errors: &mut Vec<ValidationError>,
    ) {
        let relative_path = file_path
            .strip_prefix(&self.config.root_dir)
            .unwrap_or(file_path);

        if !file_path.exists() {
            validation_errors.push(ValidationError {
                location: file_path.clone(),
                error_type: ValidationErrorType::FileNotFound,
                message: format!("Content file does not exist: {}", relative_path.display()),
                suggestion: Some("Check if the file was moved or deleted".to_string()),
            });
            return;
        }

        if !file_path.is_file() {
            validation_errors.push(ValidationError {
                location: file_path.clone(),
                error_type: ValidationErrorType::NotAFile,
                message: format!("Content target is not a file: {}", relative_path.display()),
                suggestion: Some(
                    "Content replacement only works on files, not directories".to_string(),
                ),
            });
            return;
        }

        // Check if file is readable and writable
        if let Err(e) = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(file_path)
        {
            let error_type = if e.kind() == std::io::ErrorKind::PermissionDenied {
                ValidationErrorType::PermissionDenied
            } else {
                ValidationErrorType::PermissionDenied
            };

            validation_errors.push(ValidationError {
                location: file_path.clone(),
                error_type,
                message: format!("Cannot access file {}: {}", relative_path.display(), e),
                suggestion: Some(
                    "Check file permissions or if file is locked by another process".to_string(),
                ),
            });
            return;
        }

        // Check if file is binary before attempting to read as text
        match self.file_ops.is_text_file(file_path) {
            Ok(false) => {
                // Binary file - skip validation (should not have been included in content_files)
                if self.config.verbose {
                    eprintln!("WARNING: Binary file {} was included in content validation - this may indicate a discovery phase issue", relative_path.display());
                }
                return; // Binary files are skipped during content processing
            }
            Err(e) => {
                validation_errors.push(ValidationError {
                    location: file_path.clone(),
                    error_type: ValidationErrorType::EncodingError,
                    message: format!(
                        "Cannot determine if file {} is binary or text: {}",
                        relative_path.display(),
                        e
                    ),
                    suggestion: Some(
                        "Use --exclude patterns to exclude problematic files".to_string(),
                    ),
                });
                return;
            }
            Ok(true) => {
                // File is text, continue with validation
            }
        }

        // Validate that file can be read and contains at least one pair's pattern
        let search_strings: Vec<&str> = self.pairs.iter().map(|p| p.pattern.as_str()).collect();
        match self
            .file_ops
            .file_contains_any_string(file_path, &search_strings)
        {
            Ok(contains_any) => {
                if !contains_any {
                    validation_errors.push(ValidationError {
                        location: file_path.clone(),
                        error_type: ValidationErrorType::ContentNotFound,
                        message: format!(
                            "File {} does not contain any target pattern",
                            relative_path.display()
                        ),
                        suggestion: Some(
                            "File may have been modified since discovery phase".to_string(),
                        ),
                    });
                }
            }
            Err(e) => {
                validation_errors.push(ValidationError {
                    location: file_path.clone(),
                    error_type: ValidationErrorType::EncodingError,
                    message: format!(
                        "Cannot read file {} with detected encoding: {}",
                        relative_path.display(),
                        e
                    ),
                    suggestion: Some("Use --exclude patterns to exclude this file".to_string()),
                });
            }
        }
    }

    /// Validate a single rename operation
    fn validate_rename_item(
        &self,
        item: &RenameItem,
        validation_errors: &mut Vec<ValidationError>,
    ) {
        let relative_source = item
            .original_path
            .strip_prefix(&self.config.root_dir)
            .unwrap_or(&item.original_path);
        let relative_target = item
            .new_path
            .strip_prefix(&self.config.root_dir)
            .unwrap_or(&item.new_path);

        // Skip no-op renames
        if item.original_path == item.new_path {
            return;
        }

        // Check source exists (including broken symlinks)
        let source_exists =
            item.original_path.exists() || item.original_path.symlink_metadata().is_ok();
        if !source_exists {
            validation_errors.push(ValidationError {
                location: item.original_path.clone(),
                error_type: ValidationErrorType::FileNotFound,
                message: format!(
                    "Rename source does not exist: {}",
                    relative_source.display()
                ),
                suggestion: Some(
                    "Source may have been moved or deleted since discovery".to_string(),
                ),
            });
            return;
        }

        // Check target doesn't already exist (unless it's the same as source)
        if item.new_path.exists() && item.new_path != item.original_path {
            validation_errors.push(ValidationError {
                location: item.new_path.clone(),
                error_type: ValidationErrorType::TargetExists,
                message: format!(
                    "Rename target already exists: {}",
                    relative_target.display()
                ),
                suggestion: Some(
                    "Target was created since discovery phase, or there's a naming collision"
                        .to_string(),
                ),
            });
            return;
        }

        // Check parent directory exists or can be created
        if let Some(parent) = item.new_path.parent() {
            if !parent.exists() {
                match std::fs::create_dir_all(parent) {
                    Ok(_) => {
                        // Remove the directory we just created for validation
                        let _ = std::fs::remove_dir_all(parent);
                    }
                    Err(e) => {
                        validation_errors.push(ValidationError {
                            location: parent.to_path_buf(),
                            error_type: ValidationErrorType::ParentDirectoryError,
                            message: format!(
                                "Cannot create parent directory for {}: {}",
                                relative_target.display(),
                                e
                            ),
                            suggestion: Some("Check permissions on parent directories".to_string()),
                        });
                        return;
                    }
                }
            }
        }

        // Check permissions on source (use symlink_metadata to handle broken symlinks)
        match item.original_path.symlink_metadata() {
            Ok(metadata) => {
                if metadata.permissions().readonly() {
                    validation_errors.push(ValidationError {
                        location: item.original_path.clone(),
                        error_type: ValidationErrorType::ReadOnlyFile,
                        message: format!("Source is read-only: {}", relative_source.display()),
                        suggestion: Some(
                            "Change file permissions or exclude read-only files".to_string(),
                        ),
                    });
                }
            }
            Err(e) => {
                validation_errors.push(ValidationError {
                    location: item.original_path.clone(),
                    error_type: ValidationErrorType::PermissionDenied,
                    message: format!(
                        "Cannot read metadata for {}: {}",
                        relative_source.display(),
                        e
                    ),
                    suggestion: Some("Check file permissions and access rights".to_string()),
                });
            }
        }
    }

    /// Report validation errors with enhanced formatting and organization
    fn report_validation_errors(&self, validation_errors: &[ValidationError]) -> Result<()> {
        self.print_error("=== VALIDATION FAILED ===")?;
        self.print_error(&format!(
            "Found {} issue(s) that prevent safe execution:",
            validation_errors.len()
        ))?;
        self.print_error("")?;

        // Group errors by type for better organization
        use std::collections::HashMap;
        let mut errors_by_type: HashMap<String, Vec<&ValidationError>> = HashMap::new();

        for error in validation_errors {
            let type_name = match error.error_type {
                ValidationErrorType::FileNotFound => "Missing Files/Directories",
                ValidationErrorType::PermissionDenied => "Permission Issues",
                ValidationErrorType::EncodingError => "Encoding/Binary File Issues",
                ValidationErrorType::NotAFile => "File Type Issues",
                ValidationErrorType::ReadOnlyFile => "Read-Only Files",
                ValidationErrorType::TargetExists => "Target Conflicts",
                ValidationErrorType::ParentDirectoryError => "Directory Creation Issues",
                ValidationErrorType::ContentNotFound => "Content Issues",
                ValidationErrorType::EmptyDirectoryIssue => "Directory Structure Issues",
                _ => "Other Issues",
            };

            errors_by_type
                .entry(type_name.to_string())
                .or_insert_with(Vec::new)
                .push(error);
        }

        // Report errors grouped by type
        for (error_type, errors) in errors_by_type {
            self.print_error(&format!("📋 {}: ({} issue(s))", error_type, errors.len()))?;

            for error in errors {
                let relative_path = error
                    .location
                    .strip_prefix(&self.config.root_dir)
                    .unwrap_or(&error.location);

                self.print_error(&format!("   📍 Location: {}", relative_path.display()))?;
                self.print_error(&format!("      Problem: {}", error.message))?;

                if let Some(suggestion) = &error.suggestion {
                    self.print_error(&format!("      Suggestion: {}", suggestion))?;
                }
                self.print_error("")?;
            }
        }

        self.print_error("❌ Cannot proceed until these issues are resolved.")?;
        Ok(())
    }

    /// Validate that the rename operations will not leave empty directories
    /// This is a critical test - if it fails, our operation ordering is wrong
    fn validate_no_empty_directories_remain(
        &self,
        rename_items: &[RenameItem],
        validation_errors: &mut Vec<ValidationError>,
    ) -> Result<()> {
        use std::collections::{HashMap, HashSet};

        // Build a map of all directories and what they contain
        let mut directory_contents: HashMap<PathBuf, HashSet<PathBuf>> = HashMap::new();

        // Scan the existing directory structure
        for entry in walkdir::WalkDir::new(&self.config.root_dir) {
            let entry = entry?;
            let path = entry.path();

            if let Some(parent) = path.parent() {
                directory_contents
                    .entry(parent.to_path_buf())
                    .or_insert_with(HashSet::new)
                    .insert(path.to_path_buf());
            }
        }

        // Simulate the rename operations
        for item in rename_items {
            if item.original_path == item.new_path {
                continue; // No-op
            }

            // Remove from old parent
            if let Some(old_parent) = item.original_path.parent() {
                if let Some(contents) = directory_contents.get_mut(old_parent) {
                    contents.remove(&item.original_path);
                }
            }

            // Add to new parent
            if let Some(new_parent) = item.new_path.parent() {
                directory_contents
                    .entry(new_parent.to_path_buf())
                    .or_insert_with(HashSet::new)
                    .insert(item.new_path.clone());
            }
        }

        // Check for directories that would become empty (excluding directories being renamed themselves)
        let renamed_dirs: HashSet<PathBuf> = rename_items
            .iter()
            .filter(|item| item.item_type == crate::ItemType::Directory)
            .map(|item| item.original_path.clone())
            .collect();

        for (dir_path, contents) in &directory_contents {
            // Skip root directory
            if dir_path == &self.config.root_dir {
                continue;
            }

            // Skip directories that are being renamed (they should become empty)
            if renamed_dirs.contains(dir_path) {
                continue;
            }

            // Check if directory would become empty
            if contents.is_empty() {
                let relative_path = dir_path
                    .strip_prefix(&self.config.root_dir)
                    .unwrap_or(dir_path);

                validation_errors.push(ValidationError {
                    location: dir_path.clone(),
                    error_type: ValidationErrorType::EmptyDirectoryIssue,
                    message: format!("CRITICAL: Directory would become empty after operation: {}. This indicates incorrect operation ordering.", 
                                   relative_path.display()),
                    suggestion: Some("This is a logic error in operation ordering - files should be processed before directories".to_string()),
                });
            }
        }

        Ok(())
    }

    /// Show final report
    fn show_final_report(&self, stats: &RenameStats) -> Result<()> {
        match self.output_format {
            OutputFormat::Json => {
                let report = serde_json::json!({
                    "result": "success",
                    "stats": {
                        "content_changes": stats.files_with_content_changes,
                        "file_renames": stats.files_renamed,
                        "directory_renames": stats.directories_renamed,
                        "total_changes": stats.total_changes(),
                        "errors": stats.errors.len()
                    },
                });
                println!("{}", serde_json::to_string_pretty(&report)?);
            }
            OutputFormat::Plain => {
                println!("Operation completed successfully.");
                println!("Total changes: {}", stats.total_changes());
            }
            OutputFormat::Human => {
                self.print_success("=== OPERATION COMPLETE ===")?;
                self.print_success("Operation completed successfully!")?;
                self.print_info(&format!("Total changes applied: {}", stats.total_changes()))?;

                if !stats.errors.is_empty() {
                    self.print_warning(&format!("{} error(s) occurred:", stats.errors.len()))?;
                    for error in &stats.errors {
                        self.print_error(error)?;
                    }
                }
            }
        }

        Ok(())
    }

    /// Print header information
    fn print_header(&self) -> Result<()> {
        if self.output_format != OutputFormat::Human {
            return Ok(());
        }

        if self.pairs.len() == 1 {
            self.print_success("=== WORKSPACE REFAC TOOL ===")?;
            self.print_info(&format!("Pattern: '{}'", self.pairs[0].pattern))?;
            self.print_info(&format!("Substitute: '{}'", self.pairs[0].substitute))?;
        } else {
            self.print_success(&format!(
                "=== WORKSPACE REFAC TOOL ({} pairs) ===",
                self.pairs.len()
            ))?;
            for (i, pair) in self.pairs.iter().enumerate() {
                self.print_info(&format!(
                    "  Pair {}: '{}' → '{}'",
                    i + 1,
                    pair.pattern,
                    pair.substitute
                ))?;
            }
        }
        self.print_info(&format!(
            "Root directory: {}",
            self.config.root_dir.display()
        ))?;
        self.print_info(&format!("Mode: {:?}", self.mode))?;

        if self.config.backup {
            self.print_info("Backup mode: Enabled")?;
        }

        Ok(())
    }

    // Utility methods for printing
    fn print_info(&self, message: &str) -> Result<()> {
        if let Some(progress) = &self.progress {
            progress.print_info(message);
        } else if let Some(output) = &self.simple_output {
            output.print_info(message);
        }
        Ok(())
    }

    fn print_error(&self, message: &str) -> Result<()> {
        if let Some(progress) = &self.progress {
            progress.print_error(message);
        } else if let Some(output) = &self.simple_output {
            output.print_error(message);
        }
        Ok(())
    }

    fn print_warning(&self, message: &str) -> Result<()> {
        if let Some(progress) = &self.progress {
            progress.print_warning(message);
        } else if let Some(output) = &self.simple_output {
            output.print_warning(message);
        }
        Ok(())
    }

    fn print_success(&self, message: &str) -> Result<()> {
        if let Some(progress) = &self.progress {
            progress.print_success(message);
        } else if let Some(output) = &self.simple_output {
            output.print_success(message);
        }
        Ok(())
    }

    fn print_verbose(&self, message: &str) -> Result<()> {
        if let Some(progress) = &self.progress {
            progress.print_verbose(message);
        } else if let Some(output) = &self.simple_output {
            output.print_verbose(message);
        }
        Ok(())
    }

    // Mode checking methods
    fn should_process_files(&self) -> bool {
        self.mode.should_process_files()
    }

    fn should_process_dirs(&self) -> bool {
        self.mode.should_process_dirs()
    }

    fn should_process_content(&self) -> bool {
        !matches!(self.mode, Mode::NamesOnly)
    }

    fn should_process_names(&self) -> bool {
        !matches!(self.mode, Mode::ContentOnly)
    }
}

// Extension traits to add methods to the Mode and Config types
trait ModeExt {
    fn should_process_files(&self) -> bool;
    fn should_process_dirs(&self) -> bool;
}

impl ModeExt for Mode {
    fn should_process_files(&self) -> bool {
        matches!(
            self,
            Mode::Full | Mode::FilesOnly | Mode::ContentOnly | Mode::NamesOnly
        )
    }

    fn should_process_dirs(&self) -> bool {
        matches!(self, Mode::Full | Mode::DirsOnly | Mode::NamesOnly)
    }
}