reformat-core 0.1.6

Core library for text and file reformatting
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
//! File renaming transformer

use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

/// Case transformation options
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CaseTransform {
    /// Convert to lowercase
    Lowercase,
    /// Convert to UPPERCASE
    Uppercase,
    /// Capitalize first letter only
    Capitalize,
    /// No case transformation
    None,
}

/// Space replacement options
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SpaceReplace {
    /// Replace spaces with underscores
    Underscore,
    /// Replace spaces with hyphens
    Hyphen,
    /// No space replacement
    None,
}

/// Timestamp format options
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TimestampFormat {
    /// YYYYMMDD format (e.g., 20250915)
    Long,
    /// YYMMDD format (e.g., 250915)
    Short,
    /// No timestamp
    None,
}

/// Options for file renaming
#[derive(Debug, Clone)]
pub struct RenameOptions {
    /// Case transformation to apply
    pub case_transform: CaseTransform,
    /// Space replacement to apply
    pub space_replace: SpaceReplace,
    /// Prefix to add
    pub add_prefix: Option<String>,
    /// Prefix to remove
    pub remove_prefix: Option<String>,
    /// Suffix to add (before extension)
    pub add_suffix: Option<String>,
    /// Suffix to remove (before extension)
    pub remove_suffix: Option<String>,
    /// Replace prefix (old, new)
    pub replace_prefix: Option<(String, String)>,
    /// Replace suffix (old, new)
    pub replace_suffix: Option<(String, String)>,
    /// Timestamp format for prefix (based on file creation time)
    pub timestamp_format: TimestampFormat,
    /// Process directories recursively
    pub recursive: bool,
    /// Dry run mode (don't rename files)
    pub dry_run: bool,
    /// Include symbolic links in processing
    pub include_symlinks: bool,
}

impl Default for RenameOptions {
    fn default() -> Self {
        RenameOptions {
            case_transform: CaseTransform::None,
            space_replace: SpaceReplace::None,
            add_prefix: None,
            remove_prefix: None,
            add_suffix: None,
            remove_suffix: None,
            replace_prefix: None,
            replace_suffix: None,
            timestamp_format: TimestampFormat::None,
            recursive: true,
            dry_run: false,
            include_symlinks: false,
        }
    }
}

/// File renamer for transforming file names
pub struct FileRenamer {
    options: RenameOptions,
}

impl FileRenamer {
    /// Creates a new file renamer with the given options
    pub fn new(options: RenameOptions) -> Self {
        FileRenamer { options }
    }

    /// Creates a renamer with default options
    pub fn with_defaults() -> Self {
        FileRenamer {
            options: RenameOptions::default(),
        }
    }

    /// Checks if a path should be processed
    fn should_process(&self, path: &Path, is_symlink: bool) -> bool {
        // Skip symlinks unless include_symlinks is enabled
        if is_symlink && !self.options.include_symlinks {
            return false;
        }

        // For symlinks, check if it's a symlink (not a directory symlink)
        // For regular files, check is_file()
        if !is_symlink && !path.is_file() {
            return false;
        }

        // Skip hidden files
        if let Some(name) = path.file_name() {
            if name.to_str().map(|s| s.starts_with('.')).unwrap_or(false) {
                return false;
            }
        }

        true
    }

    /// Detects the separator style used in a filename
    /// Returns '-' for hyphenated or space-separated, '_' for underscored, or '-' as default
    fn detect_separator(name: &str) -> char {
        let hyphen_count = name.chars().filter(|&c| c == '-').count();
        let underscore_count = name.chars().filter(|&c| c == '_').count();
        let space_count = name.chars().filter(|&c| c == ' ').count();

        // If spaces are present, default to hyphen (unless overridden by user transformations)
        if space_count > 0 {
            return '-';
        }

        // If hyphens are more common, use hyphen
        if hyphen_count > underscore_count {
            '-'
        } else if underscore_count > hyphen_count {
            '_'
        } else {
            // When equal or no separators, default to hyphen
            '-'
        }
    }

    /// Formats a timestamp based on file creation time
    fn format_timestamp(&self, path: &Path, separator: char) -> Option<String> {
        use std::time::SystemTime;

        match self.options.timestamp_format {
            TimestampFormat::None => None,
            TimestampFormat::Long | TimestampFormat::Short => {
                // Get file metadata
                let metadata = fs::metadata(path).ok()?;

                // Try to get creation time, fall back to modified time
                let created = metadata.created().or_else(|_| metadata.modified()).ok()?;

                // Convert to duration since epoch
                let duration = created.duration_since(SystemTime::UNIX_EPOCH).ok()?;
                let secs = duration.as_secs();

                // Calculate date components (simplified UTC conversion)
                // Days since Unix epoch
                let days = secs / 86400;

                // Calculate year, month, day
                let mut year = 1970;
                let mut remaining_days = days;

                loop {
                    let days_in_year = if Self::is_leap_year(year) { 366 } else { 365 };
                    if remaining_days < days_in_year {
                        break;
                    }
                    remaining_days -= days_in_year;
                    year += 1;
                }

                let days_in_months = if Self::is_leap_year(year) {
                    [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
                } else {
                    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
                };

                let mut month = 1;
                let mut day_of_month = remaining_days + 1;

                for days_in_month in days_in_months.iter() {
                    if day_of_month <= *days_in_month as u64 {
                        break;
                    }
                    day_of_month -= *days_in_month as u64;
                    month += 1;
                }

                // Format based on timestamp format with detected separator
                match self.options.timestamp_format {
                    TimestampFormat::Long => Some(format!(
                        "{:04}{:02}{:02}{}",
                        year, month, day_of_month, separator
                    )),
                    TimestampFormat::Short => Some(format!(
                        "{:02}{:02}{:02}{}",
                        year % 100,
                        month,
                        day_of_month,
                        separator
                    )),
                    TimestampFormat::None => None,
                }
            }
        }
    }

    /// Checks if a year is a leap year
    fn is_leap_year(year: u64) -> bool {
        year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400))
    }

    /// Applies all transformations to a filename
    fn transform_name(
        &self,
        name: &str,
        extension: Option<&str>,
        timestamp: Option<String>,
    ) -> String {
        let mut result = name.to_string();

        // 1. Remove prefix
        if let Some(prefix) = &self.options.remove_prefix {
            if result.starts_with(prefix) {
                result = result[prefix.len()..].to_string();
            }
        }

        // 2. Remove suffix (before extension)
        if let Some(suffix) = &self.options.remove_suffix {
            if result.ends_with(suffix) {
                result = result[..result.len() - suffix.len()].to_string();
            }
        }

        // 3. Replace prefix
        if let Some((old_prefix, new_prefix)) = &self.options.replace_prefix {
            if result.starts_with(old_prefix) {
                result = format!("{}{}", new_prefix, &result[old_prefix.len()..]);
            }
        }

        // 4. Replace suffix
        if let Some((old_suffix, new_suffix)) = &self.options.replace_suffix {
            if result.ends_with(old_suffix) {
                result = format!(
                    "{}{}",
                    &result[..result.len() - old_suffix.len()],
                    new_suffix
                );
            }
        }

        // 5. Separator replacement (replace spaces, hyphens, underscores with desired separator)
        match self.options.space_replace {
            SpaceReplace::Underscore => {
                // Replace all separators (spaces, hyphens) with underscores
                result = result.replace([' ', '-'], "_");
            }
            SpaceReplace::Hyphen => {
                // Replace all separators (spaces, underscores) with hyphens
                result = result.replace([' ', '_'], "-");
            }
            SpaceReplace::None => {}
        }

        // 6. Case transformation
        match self.options.case_transform {
            CaseTransform::Lowercase => {
                result = result.to_lowercase();
            }
            CaseTransform::Uppercase => {
                result = result.to_uppercase();
            }
            CaseTransform::Capitalize => {
                if !result.is_empty() {
                    let mut chars = result.chars();
                    if let Some(first) = chars.next() {
                        result = first.to_uppercase().collect::<String>()
                            + &chars.as_str().to_lowercase();
                    }
                }
            }
            CaseTransform::None => {}
        }

        // 7. Add timestamp prefix (if specified)
        if let Some(ts) = timestamp {
            result = format!("{}{}", ts, result);
        }

        // 8. Add prefix
        if let Some(prefix) = &self.options.add_prefix {
            result = format!("{}{}", prefix, result);
        }

        // 9. Add suffix (before extension)
        if let Some(suffix) = &self.options.add_suffix {
            result = format!("{}{}", result, suffix);
        }

        // 10. Add extension back
        if let Some(ext) = extension {
            result = format!("{}.{}", result, ext);
        }

        result
    }

    /// Renames a single file or symlink
    pub fn rename_file(&self, path: &Path, is_symlink: bool) -> crate::Result<bool> {
        if !self.should_process(path, is_symlink) {
            return Ok(false);
        }

        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| anyhow::anyhow!("Invalid filename"))?;

        // Split filename and extension
        let (name, extension) = if let Some(pos) = file_name.rfind('.') {
            let name = &file_name[..pos];
            let ext = &file_name[pos + 1..];
            (name, Some(ext))
        } else {
            (file_name, None)
        };

        // Detect separator style from the filename
        let separator = Self::detect_separator(name);

        // Get timestamp if needed (with detected separator)
        let timestamp = self.format_timestamp(path, separator);

        let new_name = self.transform_name(name, extension, timestamp);

        // If name didn't change, nothing to do
        if new_name == file_name {
            return Ok(false);
        }

        let parent = path
            .parent()
            .ok_or_else(|| anyhow::anyhow!("No parent directory"))?;
        let new_path = parent.join(&new_name);

        // Check if target already exists (but allow case-only renames on case-insensitive filesystems)
        if new_path.exists() {
            // Check if this is the same file (case-insensitive filesystems)
            // Use canonicalize to resolve to the actual path
            let same_file = match (path.canonicalize(), new_path.canonicalize()) {
                (Ok(p1), Ok(p2)) => p1 == p2,
                _ => false,
            };

            if !same_file {
                return Err(anyhow::anyhow!(
                    "Target file already exists: '{}'",
                    new_path.display()
                ));
            }
        }

        if self.options.dry_run {
            println!(
                "Would rename '{}' -> '{}'",
                path.display(),
                new_path.display()
            );
        } else {
            fs::rename(path, &new_path)?;
            println!("Renamed '{}' -> '{}'", path.display(), new_path.display());
        }

        Ok(true)
    }

    /// Processes a directory or file
    pub fn process(&self, path: &Path) -> crate::Result<usize> {
        let mut renamed_count = 0;

        // Check if path itself is a symlink
        let path_is_symlink = path
            .symlink_metadata()
            .map(|m| m.file_type().is_symlink())
            .unwrap_or(false);

        if path.is_file() || path_is_symlink {
            if self.rename_file(path, path_is_symlink)? {
                renamed_count = 1;
            }
        } else if path.is_dir() {
            if self.options.recursive {
                // Collect all files (and optionally symlinks) first to avoid issues with renaming while iterating
                let include_symlinks = self.options.include_symlinks;
                let mut files: Vec<(PathBuf, bool)> = WalkDir::new(path)
                    .into_iter()
                    .filter_map(|e| e.ok())
                    .filter(|e| {
                        let ft = e.file_type();
                        ft.is_file() || (include_symlinks && ft.is_symlink())
                    })
                    .map(|e| {
                        let is_symlink = e.file_type().is_symlink();
                        (e.path().to_path_buf(), is_symlink)
                    })
                    .collect();

                // Sort by depth (deepest first) to avoid parent directory rename issues
                files.sort_by(|a, b| b.0.components().count().cmp(&a.0.components().count()));

                for (file_path, is_symlink) in files {
                    if self.rename_file(&file_path, is_symlink)? {
                        renamed_count += 1;
                    }
                }
            } else {
                let include_symlinks = self.options.include_symlinks;
                let mut files: Vec<(PathBuf, bool)> = fs::read_dir(path)?
                    .filter_map(|e| e.ok())
                    .filter_map(|e| {
                        let path = e.path();
                        let ft = e.file_type().ok()?;
                        let is_symlink = ft.is_symlink();
                        if ft.is_file() || (include_symlinks && is_symlink) {
                            Some((path, is_symlink))
                        } else {
                            None
                        }
                    })
                    .collect();

                // Sort for consistent processing
                files.sort_by(|a, b| a.0.cmp(&b.0));

                for (file_path, is_symlink) in files {
                    if self.rename_file(&file_path, is_symlink)? {
                        renamed_count += 1;
                    }
                }
            }
        }

        Ok(renamed_count)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn test_lowercase_transform() {
        let test_dir = std::env::temp_dir().join("reformat_rename_lowercase");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("TestFile.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Lowercase;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        let new_file = test_dir.join("testfile.txt");
        assert!(new_file.exists());
        assert_eq!(fs::read_to_string(&new_file).unwrap(), "content");

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_uppercase_transform() {
        let test_dir = std::env::temp_dir().join("reformat_rename_uppercase");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("testfile.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Uppercase;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        let new_file = test_dir.join("TESTFILE.txt");
        assert!(new_file.exists());
        assert_eq!(fs::read_to_string(&new_file).unwrap(), "content");

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_capitalize_transform() {
        let test_dir = std::env::temp_dir().join("reformat_rename_capitalize");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("testFile.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Capitalize;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        let new_file = test_dir.join("Testfile.txt");
        assert!(new_file.exists());
        assert_eq!(fs::read_to_string(&new_file).unwrap(), "content");

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_separators_to_underscore() {
        let test_dir = std::env::temp_dir().join("reformat_rename_underscore");
        fs::create_dir_all(&test_dir).unwrap();

        // Test space to underscore
        let test_file1 = test_dir.join("test file.txt");
        fs::write(&test_file1, "content").unwrap();

        // Test hyphen to underscore
        let test_file2 = test_dir.join("test-file2.txt");
        fs::write(&test_file2, "content").unwrap();

        // Test mixed separators to underscore
        let test_file3 = test_dir.join("test-file 3.txt");
        fs::write(&test_file3, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.space_replace = SpaceReplace::Underscore;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_dir).unwrap();

        assert_eq!(count, 3);
        assert!(test_dir.join("test_file.txt").exists());
        assert!(test_dir.join("test_file2.txt").exists());
        assert!(test_dir.join("test_file_3.txt").exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_separators_to_hyphen() {
        let test_dir = std::env::temp_dir().join("reformat_rename_hyphen");
        fs::create_dir_all(&test_dir).unwrap();

        // Test space to hyphen
        let test_file1 = test_dir.join("test file.txt");
        fs::write(&test_file1, "content").unwrap();

        // Test underscore to hyphen
        let test_file2 = test_dir.join("test_file2.txt");
        fs::write(&test_file2, "content").unwrap();

        // Test mixed separators to hyphen
        let test_file3 = test_dir.join("test_file 3.txt");
        fs::write(&test_file3, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.space_replace = SpaceReplace::Hyphen;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_dir).unwrap();

        assert_eq!(count, 3);
        assert!(test_dir.join("test-file.txt").exists());
        assert!(test_dir.join("test-file2.txt").exists());
        assert!(test_dir.join("test-file-3.txt").exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_add_prefix() {
        let test_dir = std::env::temp_dir().join("reformat_rename_add_prefix");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("file.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.add_prefix = Some("new_".to_string());

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        assert!(test_dir.join("new_file.txt").exists());
        assert!(!test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_remove_prefix() {
        let test_dir = std::env::temp_dir().join("reformat_rename_rm_prefix");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("old_file.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.remove_prefix = Some("old_".to_string());

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        assert!(test_dir.join("file.txt").exists());
        assert!(!test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_add_suffix() {
        let test_dir = std::env::temp_dir().join("reformat_rename_add_suffix");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("file.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.add_suffix = Some("_backup".to_string());

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        assert!(test_dir.join("file_backup.txt").exists());
        assert!(!test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_remove_suffix() {
        let test_dir = std::env::temp_dir().join("reformat_rename_rm_suffix");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("file_old.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.remove_suffix = Some("_old".to_string());

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        assert!(test_dir.join("file.txt").exists());
        assert!(!test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_combined_transforms() {
        let test_dir = std::env::temp_dir().join("reformat_rename_combined");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("old_Test File.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.remove_prefix = Some("old_".to_string());
        opts.space_replace = SpaceReplace::Underscore;
        opts.case_transform = CaseTransform::Lowercase;
        opts.add_suffix = Some("_new".to_string());

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        assert!(test_dir.join("test_file_new.txt").exists());
        assert!(!test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_dry_run_mode() {
        let test_dir = std::env::temp_dir().join("reformat_rename_dry");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("TestFile.txt");
        let original_content = "content";
        fs::write(&test_file, original_content).unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Lowercase;
        opts.dry_run = true;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        // File should still exist and be unchanged in dry run
        assert!(test_file.exists());
        assert_eq!(fs::read_to_string(&test_file).unwrap(), original_content);

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_skip_hidden_files() {
        let test_dir = std::env::temp_dir().join("reformat_rename_hidden");
        fs::create_dir_all(&test_dir).unwrap();

        let hidden_file = test_dir.join(".hidden.txt");
        fs::write(&hidden_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Uppercase;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&hidden_file).unwrap();

        // Hidden file should be skipped
        assert_eq!(count, 0);
        assert!(hidden_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_recursive_processing() {
        let test_dir = std::env::temp_dir().join("reformat_rename_recursive");
        fs::create_dir_all(&test_dir).unwrap();

        let sub_dir = test_dir.join("subdir");
        fs::create_dir_all(&sub_dir).unwrap();

        let file1 = test_dir.join("File1.txt");
        let file2 = sub_dir.join("File2.txt");

        fs::write(&file1, "content1").unwrap();
        fs::write(&file2, "content2").unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Lowercase;
        opts.recursive = true;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_dir).unwrap();

        assert_eq!(count, 2);
        assert!(test_dir.join("file1.txt").exists());
        assert!(sub_dir.join("file2.txt").exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_no_extension_file() {
        let test_dir = std::env::temp_dir().join("reformat_rename_no_ext");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("TestFile");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Lowercase;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        let new_file = test_dir.join("testfile");
        assert!(new_file.exists());
        assert_eq!(fs::read_to_string(&new_file).unwrap(), "content");

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_timestamp_long_format() {
        let test_dir = std::env::temp_dir().join("reformat_rename_timestamp_long");
        let _ = fs::remove_dir_all(&test_dir); // Clean up first
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("document.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.timestamp_format = TimestampFormat::Long;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);

        // Check that a file with timestamp prefix exists
        // The name should be like: YYYYMMDD-document.txt (hyphen as default)
        let entries: Vec<_> = fs::read_dir(&test_dir).unwrap().collect();
        assert_eq!(entries.len(), 1);

        let renamed_file = entries[0].as_ref().unwrap().path();
        let file_name = renamed_file.file_name().unwrap().to_str().unwrap();

        // Verify format: should start with 8 digits followed by hyphen (default separator)
        assert!(
            file_name.len() >= 9,
            "Filename should have at least 9 characters (YYYYMMDD-)"
        );
        assert!(
            file_name.starts_with(|c: char| c.is_ascii_digit()),
            "Should start with digit"
        );
        assert_eq!(
            &file_name[8..9],
            "-",
            "Should have hyphen after date (default separator)"
        );
        assert!(
            file_name.ends_with("document.txt"),
            "Should end with original name"
        );

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_timestamp_short_format() {
        let test_dir = std::env::temp_dir().join("reformat_rename_timestamp_short");
        let _ = fs::remove_dir_all(&test_dir); // Clean up first
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("notes.md");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.timestamp_format = TimestampFormat::Short;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);

        // Check that a file with timestamp prefix exists
        // The name should be like: YYMMDD-notes.md (hyphen as default)
        let entries: Vec<_> = fs::read_dir(&test_dir).unwrap().collect();
        assert_eq!(entries.len(), 1);

        let renamed_file = entries[0].as_ref().unwrap().path();
        let file_name = renamed_file.file_name().unwrap().to_str().unwrap();

        // Verify format: should start with 6 digits followed by hyphen (default separator)
        assert!(
            file_name.len() >= 7,
            "Filename should have at least 7 characters (YYMMDD-)"
        );
        assert!(
            file_name.starts_with(|c: char| c.is_ascii_digit()),
            "Should start with digit"
        );
        assert_eq!(
            &file_name[6..7],
            "-",
            "Should have hyphen after date (default separator)"
        );
        assert!(
            file_name.ends_with("notes.md"),
            "Should end with original name"
        );

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_timestamp_with_other_transforms() {
        let test_dir = std::env::temp_dir().join("reformat_rename_timestamp_combined");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("My Document.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.timestamp_format = TimestampFormat::Long;
        opts.space_replace = SpaceReplace::Underscore;
        opts.case_transform = CaseTransform::Lowercase;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);

        // The file should be renamed with timestamp, spaces replaced, and lowercase
        let entries: Vec<_> = fs::read_dir(&test_dir).unwrap().collect();
        assert_eq!(entries.len(), 1);

        let renamed_file = entries[0].as_ref().unwrap().path();
        let file_name = renamed_file.file_name().unwrap().to_str().unwrap();

        // Should have format: YYYYMMDD_my_document.txt
        assert!(file_name.starts_with(|c: char| c.is_ascii_digit()));
        assert!(file_name.contains("my_document.txt"));
        assert!(!file_name.contains(" "));
        assert!(!file_name.contains("My"));

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_timestamp_separator_detection_hyphen() {
        let test_dir = std::env::temp_dir().join("reformat_rename_timestamp_hyphen");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("my-document-file.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.timestamp_format = TimestampFormat::Long;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);

        let entries: Vec<_> = fs::read_dir(&test_dir).unwrap().collect();
        assert_eq!(entries.len(), 1);

        let renamed_file = entries[0].as_ref().unwrap().path();
        let file_name = renamed_file.file_name().unwrap().to_str().unwrap();

        // Should use hyphen as separator: YYYYMMDD-my-document-file.txt
        assert!(file_name.starts_with(|c: char| c.is_ascii_digit()));
        assert_eq!(
            &file_name[8..9],
            "-",
            "Timestamp should use hyphen separator"
        );
        assert!(file_name.ends_with("my-document-file.txt"));

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_timestamp_separator_detection_underscore() {
        let test_dir = std::env::temp_dir().join("reformat_rename_timestamp_underscore");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("my_document_file.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.timestamp_format = TimestampFormat::Short;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);

        let entries: Vec<_> = fs::read_dir(&test_dir).unwrap().collect();
        assert_eq!(entries.len(), 1);

        let renamed_file = entries[0].as_ref().unwrap().path();
        let file_name = renamed_file.file_name().unwrap().to_str().unwrap();

        // Should use underscore as separator: YYMMDD_my_document_file.txt
        assert!(file_name.starts_with(|c: char| c.is_ascii_digit()));
        assert_eq!(
            &file_name[6..7],
            "_",
            "Timestamp should use underscore separator"
        );
        assert!(file_name.ends_with("my_document_file.txt"));

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_timestamp_separator_detection_mixed() {
        let test_dir = std::env::temp_dir().join("reformat_rename_timestamp_mixed");
        let _ = fs::remove_dir_all(&test_dir); // Clean up first
        fs::create_dir_all(&test_dir).unwrap();

        // More hyphens than underscores (2 hyphens vs 1 underscore)
        let test_file1 = test_dir.join("my-document-file_v2.txt");
        fs::write(&test_file1, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.timestamp_format = TimestampFormat::Long;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file1).unwrap();

        assert_eq!(count, 1);

        let entries: Vec<_> = fs::read_dir(&test_dir).unwrap().collect();
        assert_eq!(entries.len(), 1);

        let renamed_file = entries[0].as_ref().unwrap().path();
        let file_name = renamed_file.file_name().unwrap().to_str().unwrap();

        // Should use hyphen (more hyphens than underscores)
        assert_eq!(
            &file_name[8..9],
            "-",
            "Should use hyphen for mixed with more hyphens"
        );

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_timestamp_separator_detection_no_separator() {
        let test_dir = std::env::temp_dir().join("reformat_rename_timestamp_nosep");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("mydocument.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.timestamp_format = TimestampFormat::Long;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);

        let entries: Vec<_> = fs::read_dir(&test_dir).unwrap().collect();
        assert_eq!(entries.len(), 1);

        let renamed_file = entries[0].as_ref().unwrap().path();
        let file_name = renamed_file.file_name().unwrap().to_str().unwrap();

        // Should default to hyphen when no separators
        assert_eq!(&file_name[8..9], "-", "Should default to hyphen");
        assert!(file_name.ends_with("mydocument.txt"));

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_timestamp_separator_detection_spaces() {
        let test_dir = std::env::temp_dir().join("reformat_rename_timestamp_spaces");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("my document file.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.timestamp_format = TimestampFormat::Long;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);

        let entries: Vec<_> = fs::read_dir(&test_dir).unwrap().collect();
        assert_eq!(entries.len(), 1);

        let renamed_file = entries[0].as_ref().unwrap().path();
        let file_name = renamed_file.file_name().unwrap().to_str().unwrap();

        // Should use hyphen for space-separated files
        assert_eq!(
            &file_name[8..9],
            "-",
            "Should use hyphen for space-separated files"
        );
        assert!(file_name.ends_with("my document file.txt"));

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_replace_prefix() {
        let test_dir = std::env::temp_dir().join("reformat_rename_replace_prefix");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("old_file.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.replace_prefix = Some(("old_".to_string(), "new_".to_string()));

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        assert!(test_dir.join("new_file.txt").exists());
        assert!(!test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_replace_prefix_no_match() {
        let test_dir = std::env::temp_dir().join("reformat_rename_replace_prefix_nomatch");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("other_file.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.replace_prefix = Some(("old_".to_string(), "new_".to_string()));

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        // File should not be renamed since prefix doesn't match
        assert_eq!(count, 0);
        assert!(test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_replace_suffix() {
        let test_dir = std::env::temp_dir().join("reformat_rename_replace_suffix");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("file_old.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.replace_suffix = Some(("_old".to_string(), "_new".to_string()));

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        assert!(test_dir.join("file_new.txt").exists());
        assert!(!test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_replace_suffix_no_match() {
        let test_dir = std::env::temp_dir().join("reformat_rename_replace_suffix_nomatch");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("file_other.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.replace_suffix = Some(("_old".to_string(), "_new".to_string()));

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        // File should not be renamed since suffix doesn't match
        assert_eq!(count, 0);
        assert!(test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[test]
    fn test_replace_prefix_and_suffix_combined() {
        let test_dir = std::env::temp_dir().join("reformat_rename_replace_both");
        fs::create_dir_all(&test_dir).unwrap();

        let test_file = test_dir.join("old_file_v1.txt");
        fs::write(&test_file, "content").unwrap();

        let mut opts = RenameOptions::default();
        opts.replace_prefix = Some(("old_".to_string(), "new_".to_string()));
        opts.replace_suffix = Some(("_v1".to_string(), "_v2".to_string()));

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_file).unwrap();

        assert_eq!(count, 1);
        assert!(test_dir.join("new_file_v2.txt").exists());
        assert!(!test_file.exists());

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn test_symlinks_skipped_by_default() {
        use std::os::unix::fs::symlink;

        let test_dir = std::env::temp_dir().join("reformat_rename_symlink_skip");
        let _ = fs::remove_dir_all(&test_dir);
        fs::create_dir_all(&test_dir).unwrap();

        // Create a regular file with uppercase name
        let target_file = test_dir.join("Target.txt");
        fs::write(&target_file, "content").unwrap();

        // Create a symlink to the file
        let symlink_file = test_dir.join("SymLink.txt");
        symlink(&target_file, &symlink_file).unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Lowercase;
        opts.include_symlinks = false; // default

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_dir).unwrap();

        // Only the target file should be renamed, symlink should be skipped
        assert_eq!(count, 1);
        assert!(test_dir.join("target.txt").exists());

        // Check that symlink still has uppercase name by listing directory
        let entries: Vec<_> = fs::read_dir(&test_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().to_string())
            .collect();
        assert!(
            entries.iter().any(|n| n == "SymLink.txt"),
            "Symlink should retain original uppercase name"
        );

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn test_symlinks_included_when_enabled() {
        use std::os::unix::fs::symlink;

        let test_dir = std::env::temp_dir().join("reformat_rename_symlink_include");
        let _ = fs::remove_dir_all(&test_dir);
        fs::create_dir_all(&test_dir).unwrap();

        // Create a regular file (already lowercase)
        let target_file = test_dir.join("target.txt");
        fs::write(&target_file, "content").unwrap();

        // Create a symlink to the file with uppercase name
        let symlink_file = test_dir.join("SymLink.txt");
        symlink(&target_file, &symlink_file).unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Lowercase;
        opts.include_symlinks = true;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_dir).unwrap();

        // Only symlink should be renamed (target is already lowercase)
        assert_eq!(count, 1);
        assert!(test_dir.join("target.txt").exists());

        // Check that symlink was renamed to lowercase by listing directory
        let entries: Vec<_> = fs::read_dir(&test_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().to_string())
            .collect();
        assert!(
            entries.iter().any(|n| n == "symlink.txt"),
            "Symlink should be renamed to lowercase"
        );
        assert!(
            !entries.iter().any(|n| n == "SymLink.txt"),
            "Original uppercase symlink name should be gone"
        );

        fs::remove_dir_all(&test_dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn test_symlink_with_uppercase_target() {
        use std::os::unix::fs::symlink;

        let test_dir = std::env::temp_dir().join("reformat_rename_symlink_both");
        let _ = fs::remove_dir_all(&test_dir);
        fs::create_dir_all(&test_dir).unwrap();

        // Create a regular file with uppercase
        let target_file = test_dir.join("Target.txt");
        fs::write(&target_file, "content").unwrap();

        // Create a symlink to the file
        let symlink_file = test_dir.join("SymLink.txt");
        symlink(&target_file, &symlink_file).unwrap();

        let mut opts = RenameOptions::default();
        opts.case_transform = CaseTransform::Lowercase;
        opts.include_symlinks = true;

        let renamer = FileRenamer::new(opts);
        let count = renamer.process(&test_dir).unwrap();

        // Both should be renamed
        assert_eq!(count, 2);

        // Check files by listing directory (handles case-insensitive filesystems)
        let entries: Vec<_> = fs::read_dir(&test_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().to_string())
            .collect();
        assert!(
            entries.iter().any(|n| n == "target.txt"),
            "Target file should be renamed to lowercase"
        );
        assert!(
            entries.iter().any(|n| n == "symlink.txt"),
            "Symlink should be renamed to lowercase"
        );

        fs::remove_dir_all(&test_dir).unwrap();
    }
}