sedx 1.2.0

A safe, modern replacement for GNU sed with automatic backups, preview mode, and rollback
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
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use flate2::Compression;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use serde::{Deserialize, Serialize};
use std::ffi::OsString;
use std::fs;
use std::io::{BufReader, BufWriter, copy as io_copy};
use std::path::{Path, PathBuf};
use uuid::Uuid;

const MAX_BACKUPS: usize = 50;
const GZ_EXT: &str = ".gz";

/// Append a `.gz` suffix to `path`, keeping the existing extension intact.
/// `Path::with_extension` would replace the extension (`file.txt` -> `file.gz`),
/// which loses information the restore path relies on — we want
/// `file.txt.gz` so the original filename is recoverable.
fn append_gz_extension(path: &Path) -> PathBuf {
    let mut s: OsString = path.into();
    s.push(GZ_EXT);
    PathBuf::from(s)
}

/// True if `path`'s final extension is `.gz`.
fn is_gzipped(path: &Path) -> bool {
    path.extension().is_some_and(|ext| ext == "gz")
}

/// Gzip-copy `src` to `dst` using streaming I/O so memory stays flat for
/// large files. The destination gets the full gzip container (magic bytes +
/// header + deflate stream + trailer), suitable for standard `gunzip`.
fn gzip_copy(src: &Path, dst: &Path) -> Result<()> {
    let source =
        fs::File::open(src).with_context(|| format!("Failed to open source: {}", src.display()))?;
    let mut reader = BufReader::new(source);

    let dest = fs::File::create(dst)
        .with_context(|| format!("Failed to create backup: {}", dst.display()))?;
    let mut encoder = GzEncoder::new(BufWriter::new(dest), Compression::default());

    io_copy(&mut reader, &mut encoder)
        .with_context(|| format!("Failed to gzip-copy to: {}", dst.display()))?;
    encoder
        .finish()
        .with_context(|| format!("Failed to finalize gzip stream: {}", dst.display()))?;
    Ok(())
}

/// Restore a backup file into place. If `src` is gzipped (`.gz` suffix), it
/// is streamed through GzDecoder on the way out; otherwise it's a plain
/// byte-for-byte copy so that legacy (pre-v1.1) uncompressed backups keep
/// working.
fn restore_file(src: &Path, dst: &Path) -> Result<()> {
    if is_gzipped(src) {
        let source = fs::File::open(src)
            .with_context(|| format!("Failed to open backup: {}", src.display()))?;
        let mut decoder = GzDecoder::new(BufReader::new(source));
        let dest = fs::File::create(dst)
            .with_context(|| format!("Failed to create restore target: {}", dst.display()))?;
        let mut writer = BufWriter::new(dest);
        io_copy(&mut decoder, &mut writer)
            .with_context(|| format!("Failed to decompress into: {}", dst.display()))?;
    } else {
        fs::copy(src, dst).with_context(|| format!("Failed to restore file: {}", dst.display()))?;
    }
    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupMetadata {
    pub id: String,
    pub timestamp: DateTime<Utc>,
    pub expression: String,
    pub files: Vec<FileBackup>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileBackup {
    pub original_path: PathBuf,
    pub backup_path: PathBuf,
}

pub struct BackupManager {
    backups_dir: PathBuf,
}

/// Resolve sedx's state directory root.
///
/// Honors the `SEDX_HOME` env var if set (useful for tests that need to
/// isolate `~/.sedx/` on every platform — `dirs::home_dir()` on Windows
/// reads the shell API, not `HOME`/`USERPROFILE`, so an env-based override
/// is the only portable way to redirect it). Falls back to
/// `dirs::home_dir()` for normal use.
pub fn sedx_home() -> Result<PathBuf> {
    if let Ok(custom) = std::env::var("SEDX_HOME") {
        if !custom.is_empty() {
            return Ok(PathBuf::from(custom));
        }
    }
    dirs::home_dir().ok_or_else(|| anyhow::anyhow!("Cannot determine home directory"))
}

impl BackupManager {
    pub fn new() -> Result<Self> {
        let home_dir = sedx_home()?;
        let backups_dir = home_dir.join(".sedx").join("backups");

        // Create backups directory if it doesn't exist
        fs::create_dir_all(&backups_dir).with_context(|| {
            format!(
                "Failed to create backups directory: {}",
                backups_dir.display()
            )
        })?;

        Ok(Self { backups_dir })
    }

    /// Create a BackupManager with a custom backup directory
    pub fn with_directory(dir: String) -> Result<Self> {
        let backups_dir = PathBuf::from(dir);

        // Create backups directory if it doesn't exist
        fs::create_dir_all(&backups_dir).with_context(|| {
            format!(
                "Failed to create backups directory: {}",
                backups_dir.display()
            )
        })?;

        Ok(Self { backups_dir })
    }

    /// Get the backup directory path
    pub fn backups_dir(&self) -> &Path {
        &self.backups_dir
    }

    pub fn create_backup(&mut self, expression: &str, files: &[PathBuf]) -> Result<String> {
        // Calculate total backup size and check disk space
        let mut total_size = 0u64;
        for file_path in files {
            if file_path.exists() {
                total_size += file_path
                    .metadata()
                    .with_context(|| {
                        format!("Failed to get file metadata: {}", file_path.display())
                    })?
                    .len();
            }
        }

        // Check disk space before creating backup
        // Default: warn if backup > 2GB or > 40% of free space
        // Error if backup > 60% of free space
        const MAX_BACKUP_SIZE_GB: u64 = 2;
        const ERROR_PERCENT: f64 = 60.0;

        // Warn if backup is very large
        if total_size > MAX_BACKUP_SIZE_GB * 1024 * 1024 * 1024 {
            eprintln!(
                "⚠️  Warning: This operation will create a large backup ({})",
                crate::disk_space::DiskSpaceInfo::bytes_to_human(total_size)
            );
            eprintln!("Consider using --no-backup if you have a recent backup");
        }

        // Check disk space with error threshold
        if let Err(e) = crate::disk_space::check_disk_space_for_backup(
            &self.backups_dir,
            total_size,
            ERROR_PERCENT,
        ) {
            // Provide helpful error message
            return Err(e.context(format!(
                "Cannot create backup. Files size: {}",
                crate::disk_space::DiskSpaceInfo::bytes_to_human(total_size)
            )));
        }

        // Generate unique backup ID with millisecond precision for deterministic sorting
        let id = format!(
            "{}-{}",
            Utc::now().format("%Y%m%d-%H%M%S%3f"),
            Uuid::new_v4().to_string().split_at(8).0
        );
        let backup_dir = self.backups_dir.join(&id);

        fs::create_dir_all(&backup_dir).with_context(|| {
            format!(
                "Failed to create backup directory: {}",
                backup_dir.display()
            )
        })?;

        let mut file_backups = Vec::new();

        for file_path in files {
            if !file_path.exists() {
                continue;
            }

            let file_name = file_path
                .file_name()
                .ok_or_else(|| anyhow::anyhow!("Invalid file name: {}", file_path.display()))?;

            let backup_path = append_gz_extension(&backup_dir.join(file_name));

            gzip_copy(file_path, &backup_path)
                .with_context(|| format!("Failed to backup file: {}", file_path.display()))?;

            file_backups.push(FileBackup {
                original_path: file_path.clone(),
                backup_path,
            });
        }

        // Save metadata
        let metadata = BackupMetadata {
            id: id.clone(),
            timestamp: Utc::now(),
            expression: expression.to_string(),
            files: file_backups,
        };

        let metadata_path = backup_dir.join("operation.json");
        let metadata_json =
            serde_json::to_string_pretty(&metadata).context("Failed to serialize metadata")?;

        fs::write(&metadata_path, metadata_json)
            .with_context(|| format!("Failed to write metadata: {}", metadata_path.display()))?;

        // Cleanup old backups
        self.cleanup_old_backups()?;

        Ok(id)
    }

    pub fn restore_backup(&self, id: &str) -> Result<()> {
        let backup_dir = self.backups_dir.join(id);
        let metadata_path = backup_dir.join("operation.json");

        if !backup_dir.exists() {
            anyhow::bail!("Backup not found: {}", id);
        }

        let metadata_json = fs::read_to_string(&metadata_path)
            .with_context(|| format!("Failed to read metadata: {}", metadata_path.display()))?;

        let metadata: BackupMetadata =
            serde_json::from_str(&metadata_json).context("Failed to parse metadata")?;

        for file_backup in &metadata.files {
            if !file_backup.backup_path.exists() {
                eprintln!(
                    "Warning: Backup file missing: {}",
                    file_backup.backup_path.display()
                );
                continue;
            }

            restore_file(&file_backup.backup_path, &file_backup.original_path).with_context(
                || {
                    format!(
                        "Failed to restore file: {}",
                        file_backup.original_path.display()
                    )
                },
            )?;

            println!("Restored: {}", file_backup.original_path.display());
        }

        // Remove backup after successful restore
        fs::remove_dir_all(&backup_dir).with_context(|| {
            format!(
                "Failed to remove backup directory: {}",
                backup_dir.display()
            )
        })?;

        println!("Backup {} removed after restore", id);

        Ok(())
    }

    pub fn get_last_backup_id(&self) -> Result<Option<String>> {
        let mut backups = self.list_backups()?;
        backups.sort_by_key(|b| b.timestamp);
        Ok(backups.last().map(|b| b.id.clone()))
    }

    pub fn list_backups(&self) -> Result<Vec<BackupMetadata>> {
        let mut backups = Vec::new();

        for entry in fs::read_dir(&self.backups_dir).with_context(|| {
            format!(
                "Failed to read backups directory: {}",
                self.backups_dir.display()
            )
        })? {
            let entry = entry?;
            let metadata_path = entry.path().join("operation.json");

            if !metadata_path.exists() {
                continue;
            }

            let metadata_json = fs::read_to_string(&metadata_path)?;
            if let Ok(metadata) = serde_json::from_str::<BackupMetadata>(&metadata_json) {
                backups.push(metadata);
            }
        }

        // Sort by timestamp to ensure chronological order
        // When timestamps are equal (rare), use ID as tiebreaker for consistency
        backups.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then_with(|| a.id.cmp(&b.id)));
        Ok(backups)
    }

    fn cleanup_old_backups(&self) -> Result<()> {
        let mut backups = self.list_backups()?;
        backups.sort_by_key(|b| b.timestamp);

        if backups.len() > MAX_BACKUPS {
            for backup in backups.iter().take(backups.len() - MAX_BACKUPS) {
                let backup_dir = self.backups_dir.join(&backup.id);
                fs::remove_dir_all(&backup_dir).with_context(|| {
                    format!("Failed to remove old backup: {}", backup_dir.display())
                })?;
            }
        }

        Ok(())
    }

    /// Remove a backup by its ID (used for cleanup when no changes are made)
    #[allow(dead_code)] // Part of the public BackupManager API — lets library consumers remove backups programmatically.
    pub fn remove_backup_by_id(&self, backup_id: &str) -> Result<()> {
        let backup_dir = self.backups_dir.join(backup_id);
        fs::remove_dir_all(&backup_dir)
            .with_context(|| format!("Failed to remove backup: {}", backup_dir.display()))?;
        Ok(())
    }

    /// Parse backup metadata from JSON string
    #[allow(dead_code)] // Part of the public BackupManager API — lets library consumers deserialize stored metadata.
    pub fn parse_backup_metadata(json: &str) -> Result<BackupMetadata> {
        let metadata: BackupMetadata =
            serde_json::from_str(json).context("Failed to parse backup metadata")?;
        Ok(metadata)
    }

    /// Prune backups keeping only the N most recent ones
    #[allow(dead_code)] // Part of the public BackupManager API — lets library consumers enforce count-based retention.
    pub fn prune_backups(&self, keep_count: usize) -> Result<usize> {
        let mut backups = self.list_backups()?;
        backups.sort_by_key(|b| b.timestamp);

        if backups.len() <= keep_count {
            return Ok(0);
        }

        let to_remove = backups.len() - keep_count;
        for backup in backups.iter().take(to_remove) {
            let backup_dir = self.backups_dir.join(&backup.id);
            fs::remove_dir_all(&backup_dir)
                .with_context(|| format!("Failed to remove backup: {}", backup_dir.display()))?;
        }

        Ok(to_remove)
    }

    /// Prune backups older than the specified number of days
    #[allow(dead_code)] // Part of the public BackupManager API — lets library consumers enforce time-based retention.
    pub fn prune_backups_older_than(&self, days: i64) -> Result<usize> {
        let cutoff = Utc::now() - chrono::Duration::days(days);
        let mut removed = 0;

        for backup in self.list_backups()? {
            if backup.timestamp < cutoff {
                let backup_dir = self.backups_dir.join(&backup.id);
                fs::remove_dir_all(&backup_dir).with_context(|| {
                    format!("Failed to remove old backup: {}", backup_dir.display())
                })?;
                removed += 1;
            }
        }

        Ok(removed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{self, File};
    use std::io::Write;
    use std::path::PathBuf;
    use tempfile::TempDir;

    /// Helper function to create a test file with content
    fn create_test_file(dir: &Path, name: &str, content: &str) -> PathBuf {
        let file_path = dir.join(name);
        let mut file = File::create(&file_path).unwrap();
        file.write_all(content.as_bytes()).unwrap();
        file_path
    }

    /// Helper function to create a test backup manager with a temp directory
    fn create_test_manager() -> (BackupManager, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let backups_dir = temp_dir.path().join("backups");
        let manager =
            BackupManager::with_directory(backups_dir.to_str().unwrap().to_string()).unwrap();
        (manager, temp_dir)
    }

    // ============================================================================
    // create_backup() tests
    // ============================================================================

    #[test]
    fn test_create_backup_single_file() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "Hello, World!");

        let backup_id = manager
            .create_backup("s/foo/bar/", std::slice::from_ref(&test_file))
            .unwrap();

        // Verify backup directory exists
        let backup_dir = manager.backups_dir().join(&backup_id);
        assert!(backup_dir.exists(), "Backup directory should exist");

        // Verify metadata file exists
        let metadata_path = backup_dir.join("operation.json");
        assert!(metadata_path.exists(), "Metadata file should exist");

        // Verify gzipped backup file exists.
        let backup_file = backup_dir.join("test.txt.gz");
        assert!(backup_file.exists(), "Gzipped backup file should exist");

        // Verify backup round-trips: decompress into a temp file and compare
        // the recovered content to the original.
        let recovered_dir = tempfile::tempdir().unwrap();
        let recovered = recovered_dir.path().join("recovered.txt");
        restore_file(&backup_file, &recovered).unwrap();
        let recovered_content = fs::read_to_string(&recovered).unwrap();
        let original_content = fs::read_to_string(&test_file).unwrap();
        assert_eq!(
            recovered_content, original_content,
            "Backup content should round-trip through gzip"
        );

        // Verify metadata is correct
        let metadata_json = fs::read_to_string(&metadata_path).unwrap();
        let metadata: BackupMetadata = serde_json::from_str(&metadata_json).unwrap();
        assert_eq!(metadata.id, backup_id);
        assert_eq!(metadata.expression, "s/foo/bar/");
        assert_eq!(metadata.files.len(), 1);
        assert_eq!(metadata.files[0].original_path, test_file);
    }

    #[test]
    fn test_create_backup_multiple_files() {
        let (mut manager, temp_dir) = create_test_manager();
        let file1 = create_test_file(temp_dir.path(), "file1.txt", "Content 1");
        let file2 = create_test_file(temp_dir.path(), "file2.txt", "Content 2");
        let file3 = create_test_file(temp_dir.path(), "file3.txt", "Content 3");

        let backup_id = manager
            .create_backup(
                "s/test/prod/",
                &[file1.clone(), file2.clone(), file3.clone()],
            )
            .unwrap();

        let backup_dir = manager.backups_dir().join(&backup_id);
        assert!(backup_dir.exists());

        // Verify all files were backed up (with .gz suffix).
        assert!(backup_dir.join("file1.txt.gz").exists());
        assert!(backup_dir.join("file2.txt.gz").exists());
        assert!(backup_dir.join("file3.txt.gz").exists());

        // Verify metadata
        let metadata_path = backup_dir.join("operation.json");
        let metadata: BackupMetadata =
            serde_json::from_str(&fs::read_to_string(&metadata_path).unwrap()).unwrap();
        assert_eq!(metadata.files.len(), 3);
    }

    #[test]
    fn test_create_backup_large_file() {
        let (mut manager, temp_dir) = create_test_manager();
        let large_content = "x".repeat(1_000_000); // 1MB of data
        let large_file = create_test_file(temp_dir.path(), "large.txt", &large_content);

        let backup_id = manager
            .create_backup("s/x/y/", std::slice::from_ref(&large_file))
            .unwrap();

        let backup_dir = manager.backups_dir().join(&backup_id);
        let backup_file = backup_dir.join("large.txt.gz");
        assert!(backup_file.exists(), "Gzipped backup file should exist");

        // A compressible 1 MB blob of `x` gzips to well under 10 KB —
        // asserting that gives us a meaningful size expectation without
        // being brittle to compression-level tweaks. The exact ratio
        // depends on zlib internals; anywhere under 10% is plenty of
        // signal that compression actually happened.
        let backup_len = fs::metadata(&backup_file).unwrap().len();
        let original_len = fs::metadata(&large_file).unwrap().len();
        assert_eq!(original_len, 1_000_000);
        assert!(
            backup_len < original_len / 10,
            "gzip should shrink a 1MB run of 'x' to <10% of the original, got {backup_len}",
        );

        // Verify content round-trips through gzip.
        let recovered_dir = tempfile::tempdir().unwrap();
        let recovered = recovered_dir.path().join("recovered.txt");
        restore_file(&backup_file, &recovered).unwrap();
        assert_eq!(fs::metadata(&recovered).unwrap().len(), original_len);
    }

    #[test]
    fn test_create_backup_special_characters_in_filename() {
        let (mut manager, temp_dir) = create_test_manager();

        // Test various special characters
        let test_cases = vec![
            ("file with spaces.txt", "content with spaces"),
            ("file-with-dashes.txt", "content with dashes"),
            ("file_with_underscores.txt", "content with underscores"),
            ("file.multiple.dots.txt", "content"),
            ("file123.txt", "numeric content"),
        ];

        let mut files = Vec::new();
        for (name, content) in &test_cases {
            files.push(create_test_file(temp_dir.path(), name, content));
        }

        let backup_id = manager.create_backup("s/a/b/", &files).unwrap();

        let backup_dir = manager.backups_dir().join(&backup_id);

        // Verify all files with special characters were backed up (gzipped).
        for (name, _) in &test_cases {
            let gzipped = append_gz_extension(&backup_dir.join(name));
            assert!(
                gzipped.exists(),
                "File '{}' should exist in backup as {}.gz",
                name,
                name,
            );
        }
    }

    #[test]
    fn test_create_backup_nonexistent_file_skipped() {
        let (mut manager, temp_dir) = create_test_manager();
        let existing_file = create_test_file(temp_dir.path(), "exists.txt", "I exist");
        let nonexistent_file = temp_dir.path().join("does_not_exist.txt");

        let backup_id = manager
            .create_backup("s/test/prod/", &[existing_file.clone(), nonexistent_file])
            .unwrap();

        let backup_dir = manager.backups_dir().join(&backup_id);
        let metadata_path = backup_dir.join("operation.json");
        let metadata: BackupMetadata =
            serde_json::from_str(&fs::read_to_string(&metadata_path).unwrap()).unwrap();

        // Only the existing file should be in the backup
        assert_eq!(metadata.files.len(), 1);
        assert_eq!(metadata.files[0].original_path, existing_file);
    }

    #[test]
    fn test_create_backup_generates_unique_ids() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let id1 = manager
            .create_backup("s/a/b/", std::slice::from_ref(&test_file))
            .unwrap();
        // Small delay to ensure different timestamps
        std::thread::sleep(std::time::Duration::from_millis(10));
        let id2 = manager
            .create_backup("s/c/d/", std::slice::from_ref(&test_file))
            .unwrap();

        assert_ne!(id1, id2, "Backup IDs should be unique");
    }

    // ============================================================================
    // restore_backup() tests
    // ============================================================================

    #[test]
    fn test_restore_backup_success() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "original content");

        // Create backup
        let backup_id = manager
            .create_backup("s/foo/bar/", std::slice::from_ref(&test_file))
            .unwrap();

        // Modify the original file
        fs::write(&test_file, "modified content").unwrap();

        // Restore from backup
        manager.restore_backup(&backup_id).unwrap();

        // Verify content was restored
        let restored_content = fs::read_to_string(&test_file).unwrap();
        assert_eq!(restored_content, "original content");

        // Verify backup directory was removed after restore
        let backup_dir = manager.backups_dir().join(&backup_id);
        assert!(
            !backup_dir.exists(),
            "Backup directory should be removed after restore"
        );
    }

    #[test]
    fn test_restore_backup_nonexistent_id() {
        let (manager, _) = create_test_manager();

        let result = manager.restore_backup("nonexistent-backup-id");
        assert!(
            result.is_err(),
            "Should return error for nonexistent backup"
        );

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Backup not found"),
            "Error should mention backup not found"
        );
    }

    #[test]
    fn test_restore_backup_multiple_files() {
        let (mut manager, temp_dir) = create_test_manager();
        let file1 = create_test_file(temp_dir.path(), "file1.txt", "original 1");
        let file2 = create_test_file(temp_dir.path(), "file2.txt", "original 2");
        let file3 = create_test_file(temp_dir.path(), "file3.txt", "original 3");

        let backup_id = manager
            .create_backup("s/a/b/", &[file1.clone(), file2.clone(), file3.clone()])
            .unwrap();

        // Modify all files
        fs::write(&file1, "modified 1").unwrap();
        fs::write(&file2, "modified 2").unwrap();
        fs::write(&file3, "modified 3").unwrap();

        // Restore
        manager.restore_backup(&backup_id).unwrap();

        // Verify all files restored
        assert_eq!(fs::read_to_string(&file1).unwrap(), "original 1");
        assert_eq!(fs::read_to_string(&file2).unwrap(), "original 2");
        assert_eq!(fs::read_to_string(&file3).unwrap(), "original 3");
    }

    #[test]
    fn test_restore_backup_preserves_file_permissions() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        // Set specific permissions (read-write for owner only)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&test_file).unwrap().permissions();
            perms.set_mode(0o600);
            fs::set_permissions(&test_file, perms).unwrap();
        }

        let backup_id = manager
            .create_backup("s/a/b/", std::slice::from_ref(&test_file))
            .unwrap();

        // Modify and change permissions
        fs::write(&test_file, "modified").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&test_file).unwrap().permissions();
            perms.set_mode(0o644);
            fs::set_permissions(&test_file, perms).unwrap();
        }

        // Restore
        manager.restore_backup(&backup_id).unwrap();

        // Verify content restored
        assert_eq!(fs::read_to_string(&test_file).unwrap(), "content");

        // Note: File permissions after restore will depend on the system's umask
        // The key is that the file is restored and readable
    }

    // ============================================================================
    // get_last_backup_id() tests
    // ============================================================================

    #[test]
    fn test_get_last_backup_id_no_backups() {
        let (manager, _temp_dir) = create_test_manager();

        let last_id = manager.get_last_backup_id().unwrap();
        assert!(
            last_id.is_none(),
            "Should return None when no backups exist"
        );
    }

    #[test]
    fn test_get_last_backup_id_single_backup() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let backup_id = manager.create_backup("s/a/b/", &[test_file]).unwrap();

        let last_id = manager.get_last_backup_id().unwrap();
        assert_eq!(last_id.as_ref().unwrap(), &backup_id);
    }

    #[test]
    fn test_get_last_backup_id_multiple_backups() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let id1 = manager
            .create_backup("s/a/b/", std::slice::from_ref(&test_file))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let id2 = manager
            .create_backup("s/c/d/", std::slice::from_ref(&test_file))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let id3 = manager.create_backup("s/e/f/", &[test_file]).unwrap();

        let last_id = manager.get_last_backup_id().unwrap();
        // Should return the most recent backup (id3)
        assert_eq!(last_id.as_ref().unwrap(), &id3);
        assert_ne!(last_id.as_ref().unwrap(), &id1);
        assert_ne!(last_id.as_ref().unwrap(), &id2);
    }

    // ============================================================================
    // list_backups() tests
    // ============================================================================

    #[test]
    fn test_list_backups_empty() {
        let (manager, _temp_dir) = create_test_manager();

        let backups = manager.list_backups().unwrap();
        assert_eq!(
            backups.len(),
            0,
            "Should return empty list when no backups exist"
        );
    }

    #[test]
    fn test_list_backups_multiple() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        manager
            .create_backup("s/a/b/", std::slice::from_ref(&test_file))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        manager
            .create_backup("s/c/d/", std::slice::from_ref(&test_file))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        manager.create_backup("s/e/f/", &[test_file]).unwrap();

        let backups = manager.list_backups().unwrap();
        assert_eq!(backups.len(), 3);
    }

    #[test]
    fn test_list_backups_sorted_by_timestamp() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let id1 = manager
            .create_backup("s/a/b/", std::slice::from_ref(&test_file))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let id2 = manager
            .create_backup("s/c/d/", std::slice::from_ref(&test_file))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let id3 = manager.create_backup("s/e/f/", &[test_file]).unwrap();

        let backups = manager.list_backups().unwrap();

        // Verify they're in chronological order
        assert_eq!(backups[0].id, id1);
        assert_eq!(backups[1].id, id2);
        assert_eq!(backups[2].id, id3);

        // Verify timestamps are in ascending order
        assert!(backups[0].timestamp < backups[1].timestamp);
        assert!(backups[1].timestamp < backups[2].timestamp);
    }

    #[test]
    fn test_list_backups_ignores_invalid_directories() {
        let (manager, _temp_dir) = create_test_manager();

        // Create a directory without operation.json
        let invalid_dir = manager.backups_dir().join("invalid-backup");
        fs::create_dir_all(&invalid_dir).unwrap();
        fs::write(invalid_dir.join("some_file.txt"), "data").unwrap();

        let backups = manager.list_backups().unwrap();
        assert_eq!(
            backups.len(),
            0,
            "Should ignore directories without operation.json"
        );
    }

    // ============================================================================
    // remove_backup_by_id() tests
    // ============================================================================

    #[test]
    fn test_remove_backup_existing() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let backup_id = manager.create_backup("s/a/b/", &[test_file]).unwrap();
        let backup_dir = manager.backups_dir().join(&backup_id);

        assert!(backup_dir.exists(), "Backup should exist before removal");

        manager.remove_backup_by_id(&backup_id).unwrap();

        assert!(
            !backup_dir.exists(),
            "Backup should not exist after removal"
        );
    }

    #[test]
    fn test_remove_backup_nonexistent() {
        let (manager, _) = create_test_manager();

        let result = manager.remove_backup_by_id("nonexistent-backup");
        // This should fail since the directory doesn't exist
        assert!(
            result.is_err(),
            "Should return error when removing nonexistent backup"
        );
    }

    // ============================================================================
    // prune_backups() tests
    // ============================================================================

    #[test]
    fn test_prune_backups_keep_all() {
        let (manager, _temp_dir) = create_test_manager();

        let removed = manager.prune_backups(10).unwrap();
        assert_eq!(
            removed, 0,
            "Should remove 0 backups when fewer than keep count"
        );
    }

    #[test]
    fn test_prune_backups_keep_some() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        // Create 5 backups
        let mut backup_ids = Vec::new();
        for i in 0..5 {
            backup_ids.push(
                manager
                    .create_backup(
                        &format!("s/test{i}/", i = i),
                        std::slice::from_ref(&test_file),
                    )
                    .unwrap(),
            );
            std::thread::sleep(std::time::Duration::from_millis(10));
        }

        // Keep only the 2 most recent
        let removed = manager.prune_backups(2).unwrap();
        assert_eq!(removed, 3, "Should remove 3 oldest backups");

        // Verify only the 2 most recent backups remain
        let backups = manager.list_backups().unwrap();
        assert_eq!(backups.len(), 2);

        // The remaining backups should be the most recent ones
        assert_eq!(backups[0].id, backup_ids[3]); // 4th created
        assert_eq!(backups[1].id, backup_ids[4]); // 5th created (most recent)
    }

    #[test]
    fn test_prune_backups_exact_count() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        // Create exactly 3 backups
        for i in 0..3 {
            manager
                .create_backup(&format!("s/test{}/", i), std::slice::from_ref(&test_file))
                .unwrap();
            std::thread::sleep(std::time::Duration::from_millis(10));
        }

        // Keep 3 (same as current count)
        let removed = manager.prune_backups(3).unwrap();
        assert_eq!(
            removed, 0,
            "Should remove 0 backups when count equals keep count"
        );

        let backups = manager.list_backups().unwrap();
        assert_eq!(backups.len(), 3);
    }

    // ============================================================================
    // prune_backups_older_than() tests
    // ============================================================================

    #[test]
    fn test_prune_backups_older_than_none_removed() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        manager.create_backup("s/a/b/", &[test_file]).unwrap();

        // Prune backups older than 30 days (should remove none)
        let removed = manager.prune_backups_older_than(30).unwrap();
        assert_eq!(removed, 0, "Should remove 0 backups when all are recent");
    }

    #[test]
    fn test_prune_backups_older_than_removes_old() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        // Create some backups
        for _ in 0..3 {
            manager
                .create_backup("s/a/b/", std::slice::from_ref(&test_file))
                .unwrap();
        }

        // Manually create an "old" backup by modifying its metadata
        let recent_backup_id = manager.create_backup("s/c/d/", &[test_file]).unwrap();
        let backup_dir = manager.backups_dir().join(&recent_backup_id);
        let metadata_path = backup_dir.join("operation.json");

        // Read, modify, and write back with old timestamp
        let metadata_json = fs::read_to_string(&metadata_path).unwrap();
        let mut metadata: BackupMetadata = serde_json::from_str(&metadata_json).unwrap();
        metadata.timestamp = Utc::now() - chrono::Duration::days(10);
        let new_json = serde_json::to_string_pretty(&metadata).unwrap();
        fs::write(&metadata_path, new_json).unwrap();

        // Prune backups older than 5 days (should remove the one we made "old")
        let removed = manager.prune_backups_older_than(5).unwrap();
        assert_eq!(removed, 1, "Should remove 1 old backup");
    }

    // ============================================================================
    // parse_backup_metadata() tests
    // ============================================================================

    #[test]
    fn test_parse_backup_metadata_valid() {
        let json = r#"{
            "id": "20240201-120000-abc123",
            "timestamp": "2024-02-01T12:00:00Z",
            "expression": "s/foo/bar/g",
            "files": [
                {
                    "original_path": "/path/to/file1.txt",
                    "backup_path": "/backup/path/file1.txt"
                },
                {
                    "original_path": "/path/to/file2.txt",
                    "backup_path": "/backup/path/file2.txt"
                }
            ]
        }"#;

        let metadata = BackupManager::parse_backup_metadata(json).unwrap();

        assert_eq!(metadata.id, "20240201-120000-abc123");
        assert_eq!(metadata.expression, "s/foo/bar/g");
        assert_eq!(metadata.files.len(), 2);
        assert_eq!(
            metadata.files[0].original_path,
            PathBuf::from("/path/to/file1.txt")
        );
        assert_eq!(
            metadata.files[1].original_path,
            PathBuf::from("/path/to/file2.txt")
        );
    }

    #[test]
    fn test_parse_backup_metadata_invalid_json() {
        let invalid_json = r#"{ invalid json }"#;

        let result = BackupManager::parse_backup_metadata(invalid_json);
        assert!(result.is_err(), "Should return error for invalid JSON");
    }

    #[test]
    fn test_parse_backup_metadata_missing_required_field() {
        // Missing "id" field
        let json = r#"{
            "timestamp": "2024-02-01T12:00:00Z",
            "expression": "s/foo/bar/g",
            "files": []
        }"#;

        let result = BackupManager::parse_backup_metadata(json);
        assert!(
            result.is_err(),
            "Should return error when missing required field"
        );
    }

    #[test]
    fn test_parse_backup_metadata_malformed_timestamp() {
        let json = r#"{
            "id": "20240201-120000-abc123",
            "timestamp": "not-a-valid-timestamp",
            "expression": "s/foo/bar/g",
            "files": []
        }"#;

        let result = BackupManager::parse_backup_metadata(json);
        assert!(
            result.is_err(),
            "Should return error for malformed timestamp"
        );
    }

    #[test]
    fn test_parse_backup_metadata_empty_files() {
        let json = r#"{
            "id": "20240201-120000-abc123",
            "timestamp": "2024-02-01T12:00:00Z",
            "expression": "s/foo/bar/g",
            "files": []
        }"#;

        let metadata = BackupManager::parse_backup_metadata(json).unwrap();
        assert_eq!(metadata.files.len(), 0);
    }

    // ============================================================================
    // with_directory() tests
    // ============================================================================

    #[test]
    fn test_with_directory_creates_directory() {
        let temp_dir = TempDir::new().unwrap();
        let custom_path = temp_dir.path().join("custom_backup_dir");

        assert!(!custom_path.exists(), "Directory should not exist yet");

        let _manager =
            BackupManager::with_directory(custom_path.to_str().unwrap().to_string()).unwrap();

        assert!(custom_path.exists(), "Directory should be created");
    }

    #[test]
    fn test_backups_dir_returns_correct_path() {
        let (manager, _temp_dir) = create_test_manager();

        let returned_path = manager.backups_dir();
        assert!(returned_path.exists(), "Returned path should exist");
        assert!(
            returned_path.ends_with("backups"),
            "Returned path should end with 'backups'"
        );
    }

    // ============================================================================
    // Legacy backup compatibility
    // ============================================================================

    #[test]
    fn restore_accepts_legacy_uncompressed_backup() {
        // Pre-v1.1 backups stored files as raw copies (no .gz). restore_backup
        // must still handle those so in-flight backups from older installs
        // remain recoverable after an upgrade.
        let (mut manager, temp_dir) = create_test_manager();
        let original = create_test_file(temp_dir.path(), "legacy.txt", "pre-upgrade");

        // Create a backup the new way, then rewrite the backup on disk and
        // metadata to look like a legacy uncompressed backup.
        let backup_id = manager
            .create_backup("s/a/b/", std::slice::from_ref(&original))
            .unwrap();
        let backup_dir = manager.backups_dir().join(&backup_id);
        let gzipped = backup_dir.join("legacy.txt.gz");
        let uncompressed = backup_dir.join("legacy.txt");
        fs::remove_file(&gzipped).unwrap();
        fs::write(&uncompressed, "pre-upgrade").unwrap();

        let metadata_path = backup_dir.join("operation.json");
        let mut metadata: BackupMetadata =
            serde_json::from_str(&fs::read_to_string(&metadata_path).unwrap()).unwrap();
        metadata.files[0].backup_path = uncompressed;
        fs::write(
            &metadata_path,
            serde_json::to_string_pretty(&metadata).unwrap(),
        )
        .unwrap();

        // Mutate the original so we can detect that restore ran.
        fs::write(&original, "after-edit").unwrap();

        manager.restore_backup(&backup_id).unwrap();
        assert_eq!(fs::read_to_string(&original).unwrap(), "pre-upgrade");
    }

    // ============================================================================
    // cleanup_old_backups() behavior via MAX_BACKUPS
    // ============================================================================

    #[test]
    fn test_auto_cleanup_on_create_backup() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        // Create more than MAX_BACKUPS (50) backups
        // For testing efficiency, we'll create just a few and verify the mechanism works
        let mut backup_ids = Vec::new();

        for i in 0..5 {
            backup_ids.push(
                manager
                    .create_backup(&format!("s/test{}/", i), std::slice::from_ref(&test_file))
                    .unwrap(),
            );
            std::thread::sleep(std::time::Duration::from_millis(10));
        }

        // All backups should still exist (less than MAX_BACKUPS)
        let backups = manager.list_backups().unwrap();
        assert_eq!(backups.len(), 5);

        // The oldest backup should still be the first one created
        assert_eq!(backups[0].id, backup_ids[0]);
    }

    // ============================================================================
    // Edge cases and error handling
    // ============================================================================

    #[test]
    fn test_create_backup_empty_file_list() {
        let (mut manager, _temp_dir) = create_test_manager();

        let backup_id = manager.create_backup("s/a/b/", &[]);
        let backup_dir = manager.backups_dir().join(backup_id.as_ref().unwrap());

        // Backup should be created even with no files
        assert!(
            backup_id.is_ok(),
            "Should create backup even with empty file list"
        );
        assert!(backup_dir.exists(), "Backup directory should exist");

        // Metadata should exist with empty files list
        let metadata_path = backup_dir.join("operation.json");
        let metadata: BackupMetadata =
            serde_json::from_str(&fs::read_to_string(&metadata_path).unwrap()).unwrap();
        assert_eq!(metadata.files.len(), 0);
    }

    #[test]
    fn test_restore_backup_with_missing_backup_file() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "original");

        let backup_id = manager
            .create_backup("s/a/b/", std::slice::from_ref(&test_file))
            .unwrap();

        // Manually remove the backup file (simulating corruption)
        let backup_dir = manager.backups_dir().join(&backup_id);
        let backup_file = backup_dir.join("test.txt.gz");
        fs::remove_file(&backup_file).unwrap();

        // Restore should still succeed but warn about missing file
        let result = manager.restore_backup(&backup_id);
        assert!(
            result.is_ok(),
            "Restore should succeed even with missing backup file"
        );

        // Original file should remain unchanged
        let content = fs::read_to_string(&test_file).unwrap();
        assert_eq!(content, "original");
    }

    #[test]
    fn test_backup_id_format() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let backup_id = manager.create_backup("s/a/b/", &[test_file]).unwrap();

        // Verify ID format: YYYYMMDD-HHMMSSmmm-XXXXXXXX
        // e.g., 20240201-120000123-abc12345
        assert!(
            backup_id.len() >= 20,
            "Backup ID should be at least 20 characters"
        );
        assert!(backup_id.contains('-'), "Backup ID should contain hyphens");

        // First part should be date format (8 digits)
        let parts: Vec<&str> = backup_id.split('-').collect();
        assert_eq!(parts[0].len(), 8, "First part should be 8 digits (date)");

        // Second part should be time format with milliseconds (9+ digits)
        assert!(
            parts[1].len() >= 9,
            "Second part should be at least 9 digits (time with milliseconds)"
        );
    }

    #[test]
    fn test_expression_preserved_in_metadata() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let test_expression = "s/foo\\(bar\\)/baz\\1/gi";
        let backup_id = manager
            .create_backup(test_expression, &[test_file])
            .unwrap();

        let backup_dir = manager.backups_dir().join(&backup_id);
        let metadata_path = backup_dir.join("operation.json");
        let metadata: BackupMetadata =
            serde_json::from_str(&fs::read_to_string(&metadata_path).unwrap()).unwrap();

        assert_eq!(
            metadata.expression, test_expression,
            "Expression should be preserved exactly"
        );
    }

    #[test]
    fn test_multiple_backups_same_file_different_expressions() {
        let (mut manager, temp_dir) = create_test_manager();
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let id1 = manager
            .create_backup("s/a/b/", std::slice::from_ref(&test_file))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let id2 = manager
            .create_backup("s/x/y/", std::slice::from_ref(&test_file))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let id3 = manager.create_backup("s/1/2/", &[test_file]).unwrap();

        // All backups should have different IDs
        assert_ne!(id1, id2);
        assert_ne!(id2, id3);
        assert_ne!(id1, id3);

        // Verify expressions are different in metadata
        let backups = manager.list_backups().unwrap();
        assert_eq!(backups[0].expression, "s/a/b/");
        assert_eq!(backups[1].expression, "s/x/y/");
        assert_eq!(backups[2].expression, "s/1/2/");
    }
}