brrr-lint 0.1.0

A fast linter and language server for F* (FStar) with autofix capabilities
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
//! Atomic file write safety module.
//!
//! This module provides safe, atomic file writing with backup and rollback capabilities
//! to prevent data corruption during fix application.
//!
//! ## Safety Guarantees
//!
//! 1. **Atomicity**: File writes either complete fully or not at all (via temp+rename)
//! 2. **Backup**: Original file is preserved before modification
//! 3. **Lock Files**: Prevents concurrent modification of the same file
//! 4. **Rollback**: Can restore from backup if something goes wrong
//!
//! ## Usage
//!
//! ```rust,ignore
//! use crate::lint::file_safety::AtomicWriter;
//!
//! let writer = AtomicWriter::new();
//! let backup_path = writer.write_with_backup(&target_path, &new_content)?;
//! // On failure, call writer.rollback(&target_path, &backup_path)?;
//! ```

use std::collections::HashMap;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use tracing::{debug, error, info, warn};

/// Default backup retention time: 24 hours
const DEFAULT_BACKUP_RETENTION_HOURS: u64 = 24;

/// Lock file timeout: 30 seconds
const LOCK_TIMEOUT_SECS: u64 = 30;

/// Backup directory name
const BACKUP_DIR_NAME: &str = ".fstar-lint-backups";

/// Errors that can occur during atomic file operations.
#[derive(Debug)]
pub enum AtomicWriteError {
    /// Failed to create temporary file
    TempFileCreation { path: PathBuf, source: io::Error },
    /// Failed to write to temporary file
    TempFileWrite { path: PathBuf, source: io::Error },
    /// Failed to sync temporary file to disk
    TempFileSync { path: PathBuf, source: io::Error },
    /// Failed to rename temporary file to target
    Rename {
        from: PathBuf,
        to: PathBuf,
        source: io::Error,
    },
    /// Failed to create backup
    BackupCreation { path: PathBuf, source: io::Error },
    /// Failed to read original file for backup
    OriginalRead { path: PathBuf, source: io::Error },
    /// Failed to create backup directory
    BackupDirCreation { path: PathBuf, source: io::Error },
    /// Failed to acquire lock (file is being modified by another process)
    LockAcquisitionFailed { path: PathBuf, reason: String },
    /// Lock file is stale but cannot be removed
    StaleLockRemoval { path: PathBuf, source: io::Error },
    /// Failed to release lock
    LockReleaseFailed { path: PathBuf, source: io::Error },
    /// Rollback failed
    RollbackFailed { path: PathBuf, source: io::Error },
    /// Content validation failed after write
    ValidationFailed {
        path: PathBuf,
        expected_len: usize,
        actual_len: usize,
    },
    /// Parent directory does not exist
    ParentDirMissing { path: PathBuf },
    /// File is on different filesystem than temp directory (rename would fail)
    CrossFilesystem { path: PathBuf },
}

impl std::fmt::Display for AtomicWriteError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AtomicWriteError::TempFileCreation { path, source } => {
                write!(
                    f,
                    "Failed to create temporary file at {}: {}",
                    path.display(),
                    source
                )
            }
            AtomicWriteError::TempFileWrite { path, source } => {
                write!(
                    f,
                    "Failed to write to temporary file {}: {}",
                    path.display(),
                    source
                )
            }
            AtomicWriteError::TempFileSync { path, source } => {
                write!(
                    f,
                    "Failed to sync temporary file {}: {}",
                    path.display(),
                    source
                )
            }
            AtomicWriteError::Rename { from, to, source } => {
                write!(
                    f,
                    "Failed to rename {} to {}: {}",
                    from.display(),
                    to.display(),
                    source
                )
            }
            AtomicWriteError::BackupCreation { path, source } => {
                write!(f, "Failed to create backup at {}: {}", path.display(), source)
            }
            AtomicWriteError::OriginalRead { path, source } => {
                write!(
                    f,
                    "Failed to read original file {}: {}",
                    path.display(),
                    source
                )
            }
            AtomicWriteError::BackupDirCreation { path, source } => {
                write!(
                    f,
                    "Failed to create backup directory {}: {}",
                    path.display(),
                    source
                )
            }
            AtomicWriteError::LockAcquisitionFailed { path, reason } => {
                write!(
                    f,
                    "Failed to acquire lock for {}: {}",
                    path.display(),
                    reason
                )
            }
            AtomicWriteError::StaleLockRemoval { path, source } => {
                write!(
                    f,
                    "Failed to remove stale lock file {}: {}",
                    path.display(),
                    source
                )
            }
            AtomicWriteError::LockReleaseFailed { path, source } => {
                write!(f, "Failed to release lock for {}: {}", path.display(), source)
            }
            AtomicWriteError::RollbackFailed { path, source } => {
                write!(f, "Failed to rollback {}: {}", path.display(), source)
            }
            AtomicWriteError::ValidationFailed {
                path,
                expected_len,
                actual_len,
            } => {
                write!(
                    f,
                    "Content validation failed for {}: expected {} bytes, got {}",
                    path.display(),
                    expected_len,
                    actual_len
                )
            }
            AtomicWriteError::ParentDirMissing { path } => {
                write!(
                    f,
                    "Parent directory does not exist for {}",
                    path.display()
                )
            }
            AtomicWriteError::CrossFilesystem { path } => {
                write!(
                    f,
                    "File {} is on different filesystem, atomic rename not possible",
                    path.display()
                )
            }
        }
    }
}

impl std::error::Error for AtomicWriteError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            AtomicWriteError::TempFileCreation { source, .. } => Some(source),
            AtomicWriteError::TempFileWrite { source, .. } => Some(source),
            AtomicWriteError::TempFileSync { source, .. } => Some(source),
            AtomicWriteError::Rename { source, .. } => Some(source),
            AtomicWriteError::BackupCreation { source, .. } => Some(source),
            AtomicWriteError::OriginalRead { source, .. } => Some(source),
            AtomicWriteError::BackupDirCreation { source, .. } => Some(source),
            AtomicWriteError::StaleLockRemoval { source, .. } => Some(source),
            AtomicWriteError::LockReleaseFailed { source, .. } => Some(source),
            AtomicWriteError::RollbackFailed { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Result type for atomic write operations.
pub type AtomicWriteResult<T> = Result<T, AtomicWriteError>;

/// Information about a backup file.
#[derive(Debug, Clone)]
pub struct BackupInfo {
    /// Path to the backup file
    pub backup_path: PathBuf,
    /// Path to the original file
    pub original_path: PathBuf,
    /// Timestamp when backup was created
    pub created_at: SystemTime,
    /// Size of the backup in bytes
    pub size: u64,
}

/// Atomic file writer with backup and lock file support.
///
/// This struct provides safe file writing operations that:
/// - Write to a temp file first, then atomic rename
/// - Create backups before modifying files
/// - Use lock files to prevent concurrent modification
/// - Support rollback from backup
pub struct AtomicWriter {
    /// Active locks held by this writer (path -> lock file path)
    active_locks: Arc<Mutex<HashMap<PathBuf, PathBuf>>>,
    /// Backup retention duration
    backup_retention: Duration,
    /// Whether to validate content after write
    validate_writes: bool,
}

impl Default for AtomicWriter {
    fn default() -> Self {
        Self::new()
    }
}

impl AtomicWriter {
    /// Create a new AtomicWriter with default settings.
    pub fn new() -> Self {
        Self {
            active_locks: Arc::new(Mutex::new(HashMap::new())),
            backup_retention: Duration::from_secs(DEFAULT_BACKUP_RETENTION_HOURS * 3600),
            validate_writes: true,
        }
    }

    /// Create an AtomicWriter with custom backup retention.
    pub fn with_retention(retention_hours: u64) -> Self {
        Self {
            active_locks: Arc::new(Mutex::new(HashMap::new())),
            backup_retention: Duration::from_secs(retention_hours * 3600),
            validate_writes: true,
        }
    }

    /// Disable write validation (not recommended for production).
    pub fn without_validation(mut self) -> Self {
        self.validate_writes = false;
        self
    }

    /// Atomically write content to a file.
    ///
    /// This function:
    /// 1. Creates a temp file in the same directory as the target
    /// 2. Writes content to the temp file
    /// 3. Syncs the temp file to disk
    /// 4. Atomically renames temp file to target
    ///
    /// If any step fails, the original file is untouched.
    pub fn write(&self, path: &Path, content: &str) -> AtomicWriteResult<()> {
        // Verify parent directory exists
        let parent = path.parent().ok_or_else(|| AtomicWriteError::ParentDirMissing {
            path: path.to_path_buf(),
        })?;

        if !parent.exists() {
            return Err(AtomicWriteError::ParentDirMissing {
                path: path.to_path_buf(),
            });
        }

        // Generate temp file path in same directory (ensures same filesystem for atomic rename)
        let temp_path = self.generate_temp_path(path);
        debug!("Creating temp file: {}", temp_path.display());

        // Create and write to temp file
        let mut temp_file = File::create(&temp_path).map_err(|e| AtomicWriteError::TempFileCreation {
            path: temp_path.clone(),
            source: e,
        })?;

        temp_file
            .write_all(content.as_bytes())
            .map_err(|e| AtomicWriteError::TempFileWrite {
                path: temp_path.clone(),
                source: e,
            })?;

        // Sync to disk to ensure durability
        temp_file
            .sync_all()
            .map_err(|e| AtomicWriteError::TempFileSync {
                path: temp_path.clone(),
                source: e,
            })?;

        // Close the file explicitly before rename
        drop(temp_file);

        // Atomic rename
        fs::rename(&temp_path, path).map_err(|e| {
            // Clean up temp file on failure
            let _ = fs::remove_file(&temp_path);
            AtomicWriteError::Rename {
                from: temp_path.clone(),
                to: path.to_path_buf(),
                source: e,
            }
        })?;

        // Validate if enabled
        if self.validate_writes {
            self.validate_content(path, content)?;
        }

        debug!("Successfully wrote {} bytes to {}", content.len(), path.display());
        Ok(())
    }

    /// Atomically write content to a file with backup.
    ///
    /// This function:
    /// 1. Acquires a lock on the file
    /// 2. Creates a backup of the original file
    /// 3. Atomically writes new content
    /// 4. Releases the lock
    ///
    /// Returns the path to the backup file for potential rollback.
    pub fn write_with_backup(&self, path: &Path, content: &str) -> AtomicWriteResult<PathBuf> {
        // Acquire lock
        self.acquire_lock(path)?;

        // Create backup (if file exists)
        let backup_path = if path.exists() {
            Some(self.create_backup(path)?)
        } else {
            None
        };

        // Attempt atomic write
        let write_result = self.write(path, content);

        // Release lock regardless of write result
        let release_result = self.release_lock(path);

        // Handle write failure - attempt rollback
        if let Err(write_err) = write_result {
            if let Some(ref backup) = backup_path {
                warn!("Write failed, attempting rollback from backup");
                if let Err(rollback_err) = self.rollback(path, backup) {
                    error!(
                        "CRITICAL: Write failed AND rollback failed! Backup at: {}",
                        backup.display()
                    );
                    // Return the original write error since that's the root cause
                    return Err(write_err);
                }
                info!("Successfully rolled back from backup");
            }
            return Err(write_err);
        }

        // Handle lock release failure (write succeeded)
        if let Err(lock_err) = release_result {
            warn!("Lock release failed (but write succeeded): {:?}", lock_err);
            // Don't fail the operation since the write succeeded
        }

        Ok(backup_path.unwrap_or_else(|| self.generate_backup_path(path)))
    }

    /// Rollback a file from its backup.
    pub fn rollback(&self, original: &Path, backup: &Path) -> AtomicWriteResult<()> {
        if !backup.exists() {
            warn!("Backup file does not exist: {}", backup.display());
            return Ok(());
        }

        // Read backup content
        let mut backup_content = String::new();
        File::open(backup)
            .and_then(|mut f| f.read_to_string(&mut backup_content))
            .map_err(|e| AtomicWriteError::RollbackFailed {
                path: original.to_path_buf(),
                source: e,
            })?;

        // Atomic write the backup content
        self.write(original, &backup_content)?;

        info!(
            "Rolled back {} from backup {}",
            original.display(),
            backup.display()
        );
        Ok(())
    }

    /// Create a backup of a file.
    fn create_backup(&self, path: &Path) -> AtomicWriteResult<PathBuf> {
        let backup_dir = self.get_backup_dir(path)?;
        let backup_path = self.generate_backup_path(path);

        // Read original content
        let mut content = String::new();
        File::open(path)
            .and_then(|mut f| f.read_to_string(&mut content))
            .map_err(|e| AtomicWriteError::OriginalRead {
                path: path.to_path_buf(),
                source: e,
            })?;

        // Create backup directory if needed
        if !backup_dir.exists() {
            fs::create_dir_all(&backup_dir).map_err(|e| AtomicWriteError::BackupDirCreation {
                path: backup_dir.clone(),
                source: e,
            })?;
        }

        // Write backup file (using atomic write for safety)
        let mut backup_file =
            File::create(&backup_path).map_err(|e| AtomicWriteError::BackupCreation {
                path: backup_path.clone(),
                source: e,
            })?;

        backup_file
            .write_all(content.as_bytes())
            .map_err(|e| AtomicWriteError::BackupCreation {
                path: backup_path.clone(),
                source: e,
            })?;

        backup_file
            .sync_all()
            .map_err(|e| AtomicWriteError::BackupCreation {
                path: backup_path.clone(),
                source: e,
            })?;

        info!("Created backup: {}", backup_path.display());
        Ok(backup_path)
    }

    /// Acquire a lock on a file to prevent concurrent modification.
    fn acquire_lock(&self, path: &Path) -> AtomicWriteResult<()> {
        let lock_path = self.get_lock_path(path);

        // Check for existing lock
        if lock_path.exists() {
            // Check if lock is stale
            if self.is_lock_stale(&lock_path)? {
                info!("Removing stale lock: {}", lock_path.display());
                fs::remove_file(&lock_path).map_err(|e| AtomicWriteError::StaleLockRemoval {
                    path: lock_path.clone(),
                    source: e,
                })?;
            } else {
                return Err(AtomicWriteError::LockAcquisitionFailed {
                    path: path.to_path_buf(),
                    reason: format!(
                        "File is locked by another process (lock file: {})",
                        lock_path.display()
                    ),
                });
            }
        }

        // Create lock file with our PID
        let lock_content = format!(
            "pid:{}\ntime:{}\nfile:{}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            path.display()
        );

        // Create parent dir for lock file if needed
        if let Some(parent) = lock_path.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent).map_err(|e| AtomicWriteError::BackupDirCreation {
                    path: parent.to_path_buf(),
                    source: e,
                })?;
            }
        }

        let mut lock_file = OpenOptions::new()
            .write(true)
            .create_new(true) // Fail if file exists (atomic check-and-create)
            .open(&lock_path)
            .map_err(|e| {
                if e.kind() == io::ErrorKind::AlreadyExists {
                    AtomicWriteError::LockAcquisitionFailed {
                        path: path.to_path_buf(),
                        reason: "Lock file was created by another process".to_string(),
                    }
                } else {
                    AtomicWriteError::LockAcquisitionFailed {
                        path: path.to_path_buf(),
                        reason: format!("Failed to create lock file: {}", e),
                    }
                }
            })?;

        lock_file.write_all(lock_content.as_bytes()).map_err(|e| {
            let _ = fs::remove_file(&lock_path);
            AtomicWriteError::LockAcquisitionFailed {
                path: path.to_path_buf(),
                reason: format!("Failed to write lock file content: {}", e),
            }
        })?;

        // Track active lock
        let mut locks = self.active_locks.lock().unwrap();
        locks.insert(path.to_path_buf(), lock_path.clone());

        debug!("Acquired lock: {}", lock_path.display());
        Ok(())
    }

    /// Release a lock on a file.
    fn release_lock(&self, path: &Path) -> AtomicWriteResult<()> {
        let lock_path = self.get_lock_path(path);

        // Remove from active locks
        {
            let mut locks = self.active_locks.lock().unwrap();
            locks.remove(path);
        }

        // Delete lock file
        if lock_path.exists() {
            fs::remove_file(&lock_path).map_err(|e| AtomicWriteError::LockReleaseFailed {
                path: path.to_path_buf(),
                source: e,
            })?;
        }

        debug!("Released lock: {}", lock_path.display());
        Ok(())
    }

    /// Check if a lock file is stale (older than LOCK_TIMEOUT_SECS).
    fn is_lock_stale(&self, lock_path: &Path) -> AtomicWriteResult<bool> {
        let metadata = fs::metadata(lock_path).map_err(|e| AtomicWriteError::LockAcquisitionFailed {
            path: lock_path.to_path_buf(),
            reason: format!("Cannot read lock file metadata: {}", e),
        })?;

        let modified = metadata.modified().map_err(|e| {
            AtomicWriteError::LockAcquisitionFailed {
                path: lock_path.to_path_buf(),
                reason: format!("Cannot read lock file mtime: {}", e),
            }
        })?;

        let age = SystemTime::now()
            .duration_since(modified)
            .unwrap_or(Duration::ZERO);

        Ok(age.as_secs() > LOCK_TIMEOUT_SECS)
    }

    /// Validate that written content matches expected content.
    fn validate_content(&self, path: &Path, expected: &str) -> AtomicWriteResult<()> {
        let mut actual = String::new();
        File::open(path)
            .and_then(|mut f| f.read_to_string(&mut actual))
            .map_err(|e| AtomicWriteError::OriginalRead {
                path: path.to_path_buf(),
                source: e,
            })?;

        if actual.len() != expected.len() {
            return Err(AtomicWriteError::ValidationFailed {
                path: path.to_path_buf(),
                expected_len: expected.len(),
                actual_len: actual.len(),
            });
        }

        // Full content comparison for safety
        if actual != expected {
            return Err(AtomicWriteError::ValidationFailed {
                path: path.to_path_buf(),
                expected_len: expected.len(),
                actual_len: actual.len(),
            });
        }

        Ok(())
    }

    /// Generate a unique temp file path in the same directory as the target.
    fn generate_temp_path(&self, path: &Path) -> PathBuf {
        let parent = path.parent().unwrap_or(Path::new("."));
        let filename = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("file");

        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();

        parent.join(format!(".{}.{}.tmp", filename, timestamp))
    }

    /// Generate a backup file path.
    /// Uses millisecond precision to avoid collisions when multiple backups are created quickly.
    fn generate_backup_path(&self, path: &Path) -> PathBuf {
        let backup_dir = self.get_backup_dir(path).unwrap_or_else(|_| {
            path.parent()
                .unwrap_or(Path::new("."))
                .join(BACKUP_DIR_NAME)
        });

        let filename = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("file");

        // Use milliseconds for better uniqueness when creating multiple backups quickly
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis();

        backup_dir.join(format!("{}.{}.bak", filename, timestamp))
    }

    /// Get the backup directory for a file.
    fn get_backup_dir(&self, path: &Path) -> AtomicWriteResult<PathBuf> {
        let parent = path.parent().ok_or_else(|| AtomicWriteError::ParentDirMissing {
            path: path.to_path_buf(),
        })?;

        Ok(parent.join(BACKUP_DIR_NAME))
    }

    /// Get the lock file path for a file.
    fn get_lock_path(&self, path: &Path) -> PathBuf {
        let backup_dir = self
            .get_backup_dir(path)
            .unwrap_or_else(|_| path.parent().unwrap_or(Path::new(".")).join(BACKUP_DIR_NAME));

        let filename = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("file");

        backup_dir.join(format!("{}.lock", filename))
    }

    /// List all backups for a given directory.
    pub fn list_backups(&self, dir: &Path) -> AtomicWriteResult<Vec<BackupInfo>> {
        let backup_dir = dir.join(BACKUP_DIR_NAME);
        if !backup_dir.exists() {
            return Ok(Vec::new());
        }

        let mut backups = Vec::new();

        let entries = fs::read_dir(&backup_dir).map_err(|e| AtomicWriteError::BackupDirCreation {
            path: backup_dir.clone(),
            source: e,
        })?;

        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("bak") {
                if let Ok(metadata) = fs::metadata(&path) {
                    let created_at = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH);

                    // Parse original filename from backup name
                    let filename = path
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("");

                    // Format: "original.timestamp.bak" -> "original"
                    let original_name: String = filename
                        .rsplitn(3, '.')
                        .skip(2)
                        .collect::<Vec<_>>()
                        .into_iter()
                        .rev()
                        .collect::<Vec<_>>()
                        .join(".");

                    let original_path = dir.join(&original_name);

                    backups.push(BackupInfo {
                        backup_path: path,
                        original_path,
                        created_at,
                        size: metadata.len(),
                    });
                }
            }
        }

        // Sort by creation time, newest first
        backups.sort_by(|a, b| b.created_at.cmp(&a.created_at));

        Ok(backups)
    }

    /// Clean up old backups beyond retention period.
    pub fn cleanup_old_backups(&self, dir: &Path) -> AtomicWriteResult<usize> {
        let backups = self.list_backups(dir)?;
        let now = SystemTime::now();
        let mut removed = 0;

        for backup in backups {
            let age = now.duration_since(backup.created_at).unwrap_or(Duration::ZERO);

            if age > self.backup_retention {
                if let Err(e) = fs::remove_file(&backup.backup_path) {
                    warn!(
                        "Failed to remove old backup {}: {}",
                        backup.backup_path.display(),
                        e
                    );
                } else {
                    debug!("Removed old backup: {}", backup.backup_path.display());
                    removed += 1;
                }
            }
        }

        // Remove backup directory if empty
        let backup_dir = dir.join(BACKUP_DIR_NAME);
        if backup_dir.exists() {
            if let Ok(entries) = fs::read_dir(&backup_dir) {
                // Count non-lock files
                let file_count = entries
                    .flatten()
                    .filter(|e| {
                        e.path()
                            .extension()
                            .and_then(|ext| ext.to_str())
                            .map(|ext| ext != "lock")
                            .unwrap_or(true)
                    })
                    .count();

                if file_count == 0 {
                    let _ = fs::remove_dir(&backup_dir);
                }
            }
        }

        if removed > 0 {
            info!("Cleaned up {} old backup(s) from {}", removed, dir.display());
        }

        Ok(removed)
    }

    /// Restore a specific backup.
    pub fn restore_backup(&self, backup: &BackupInfo) -> AtomicWriteResult<()> {
        if !backup.backup_path.exists() {
            return Err(AtomicWriteError::RollbackFailed {
                path: backup.original_path.clone(),
                source: io::Error::new(io::ErrorKind::NotFound, "Backup file not found"),
            });
        }

        self.rollback(&backup.original_path, &backup.backup_path)
    }
}

impl Drop for AtomicWriter {
    fn drop(&mut self) {
        // Release all held locks on drop
        let locks = self.active_locks.lock().unwrap();
        for (path, lock_path) in locks.iter() {
            if lock_path.exists() {
                if let Err(e) = fs::remove_file(lock_path) {
                    error!(
                        "Failed to release lock for {} on drop: {}",
                        path.display(),
                        e
                    );
                }
            }
        }
    }
}

/// Convenience function for simple atomic write without backup.
pub fn atomic_write(path: &Path, content: &str) -> AtomicWriteResult<()> {
    AtomicWriter::new().write(path, content)
}

/// Convenience function for atomic write with backup.
pub fn atomic_write_with_backup(path: &Path, content: &str) -> AtomicWriteResult<PathBuf> {
    AtomicWriter::new().write_with_backup(path, content)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn create_test_file(dir: &TempDir, name: &str, content: &str) -> PathBuf {
        let path = dir.path().join(name);
        fs::write(&path, content).expect("Failed to write test file");
        path
    }

    #[test]
    fn test_atomic_write_success() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("test.txt");

        let writer = AtomicWriter::new();
        writer
            .write(&file_path, "Hello, World!")
            .expect("Atomic write should succeed");

        let content = fs::read_to_string(&file_path).expect("Should read file");
        assert_eq!(content, "Hello, World!");
    }

    #[test]
    fn test_atomic_write_overwrites_existing() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = create_test_file(&temp_dir, "test.txt", "Original content");

        let writer = AtomicWriter::new();
        writer
            .write(&file_path, "New content")
            .expect("Atomic write should succeed");

        let content = fs::read_to_string(&file_path).expect("Should read file");
        assert_eq!(content, "New content");
    }

    #[test]
    fn test_atomic_write_with_backup_creates_backup() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = create_test_file(&temp_dir, "test.fst", "Original F* content");

        let writer = AtomicWriter::new();
        let backup_path = writer
            .write_with_backup(&file_path, "Modified F* content")
            .expect("Atomic write with backup should succeed");

        // Check new content
        let content = fs::read_to_string(&file_path).expect("Should read file");
        assert_eq!(content, "Modified F* content");

        // Check backup exists
        assert!(backup_path.exists(), "Backup file should exist");

        // Check backup content
        let backup_content = fs::read_to_string(&backup_path).expect("Should read backup");
        assert_eq!(backup_content, "Original F* content");
    }

    #[test]
    fn test_rollback_restores_original() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = create_test_file(&temp_dir, "test.fst", "Original content");

        let writer = AtomicWriter::new();

        // Write with backup
        let backup_path = writer
            .write_with_backup(&file_path, "Modified content")
            .expect("Write with backup should succeed");

        // Verify modification
        let content = fs::read_to_string(&file_path).expect("Should read file");
        assert_eq!(content, "Modified content");

        // Rollback
        writer
            .rollback(&file_path, &backup_path)
            .expect("Rollback should succeed");

        // Verify restoration
        let restored = fs::read_to_string(&file_path).expect("Should read file");
        assert_eq!(restored, "Original content");
    }

    #[test]
    fn test_lock_prevents_concurrent_access() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = create_test_file(&temp_dir, "test.fst", "Content");

        let writer1 = AtomicWriter::new();
        let writer2 = AtomicWriter::new();

        // First writer acquires lock
        writer1
            .acquire_lock(&file_path)
            .expect("First lock should succeed");

        // Second writer should fail
        let result = writer2.acquire_lock(&file_path);
        assert!(result.is_err(), "Second lock should fail");

        // Release first lock
        writer1
            .release_lock(&file_path)
            .expect("Lock release should succeed");

        // Now second writer should succeed
        writer2
            .acquire_lock(&file_path)
            .expect("Second lock should succeed after release");

        writer2
            .release_lock(&file_path)
            .expect("Cleanup lock release");
    }

    #[test]
    fn test_list_backups() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = create_test_file(&temp_dir, "test.fst", "Content v1");

        let writer = AtomicWriter::new();

        // Create multiple backups
        writer
            .write_with_backup(&file_path, "Content v2")
            .expect("First backup should succeed");

        // Small delay to ensure different timestamps
        std::thread::sleep(std::time::Duration::from_millis(100));

        writer
            .write_with_backup(&file_path, "Content v3")
            .expect("Second backup should succeed");

        // List backups
        let backups = writer
            .list_backups(temp_dir.path())
            .expect("List backups should succeed");

        assert!(backups.len() >= 2, "Should have at least 2 backups");
    }

    #[test]
    fn test_cleanup_old_backups() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = create_test_file(&temp_dir, "test.fst", "Content");

        // Create writer with very short retention (1 second)
        let writer = AtomicWriter {
            active_locks: Arc::new(Mutex::new(HashMap::new())),
            backup_retention: Duration::from_secs(1),
            validate_writes: true,
        };

        // Create backup
        writer
            .write_with_backup(&file_path, "New content")
            .expect("Backup should succeed");

        // Wait for backup to become "old"
        std::thread::sleep(std::time::Duration::from_secs(2));

        // Cleanup
        let removed = writer
            .cleanup_old_backups(temp_dir.path())
            .expect("Cleanup should succeed");

        assert!(removed > 0, "Should have removed at least one old backup");
    }

    #[test]
    fn test_temp_file_cleanup_on_failure() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("nonexistent_dir").join("test.txt");

        let writer = AtomicWriter::new();
        let result = writer.write(&file_path, "Content");

        // Should fail because parent directory doesn't exist
        assert!(result.is_err());

        // Verify no temp files left behind
        let temp_files: Vec<_> = fs::read_dir(temp_dir.path())
            .expect("Should read dir")
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.path()
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .map(|ext| ext == "tmp")
                    .unwrap_or(false)
            })
            .collect();

        assert!(temp_files.is_empty(), "No temp files should be left behind");
    }

    #[test]
    fn test_validation_catches_corruption() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("test.txt");

        let writer = AtomicWriter::new();

        // Write normally first
        writer
            .write(&file_path, "Test content")
            .expect("Write should succeed");

        // Validation during write should pass
        let content = fs::read_to_string(&file_path).expect("Read should succeed");
        assert_eq!(content, "Test content");
    }

    #[test]
    fn test_write_new_file_without_backup() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("new_file.fst");

        let writer = AtomicWriter::new();

        // File doesn't exist, so backup path will be generated but no actual backup created
        let result = writer.write_with_backup(&file_path, "New file content");

        assert!(result.is_ok(), "Write should succeed for new file");

        let content = fs::read_to_string(&file_path).expect("Should read file");
        assert_eq!(content, "New file content");
    }

    #[test]
    fn test_convenience_functions() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Test atomic_write
        let file1 = temp_dir.path().join("file1.txt");
        atomic_write(&file1, "Content 1").expect("atomic_write should succeed");
        assert_eq!(
            fs::read_to_string(&file1).unwrap(),
            "Content 1"
        );

        // Test atomic_write_with_backup
        let file2 = temp_dir.path().join("file2.txt");
        fs::write(&file2, "Original").expect("Setup file");
        let backup = atomic_write_with_backup(&file2, "Content 2")
            .expect("atomic_write_with_backup should succeed");

        assert_eq!(
            fs::read_to_string(&file2).unwrap(),
            "Content 2"
        );
        assert!(backup.exists() || !temp_dir.path().join(BACKUP_DIR_NAME).exists());
    }

    #[test]
    fn test_restore_backup() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = create_test_file(&temp_dir, "test.fst", "Original content");

        let writer = AtomicWriter::new();

        // Create backup
        writer
            .write_with_backup(&file_path, "Modified content")
            .expect("Write should succeed");

        // Get backups
        let backups = writer
            .list_backups(temp_dir.path())
            .expect("List should succeed");

        assert!(!backups.is_empty(), "Should have backups");

        // Restore first backup
        writer
            .restore_backup(&backups[0])
            .expect("Restore should succeed");

        // Verify restoration
        let content = fs::read_to_string(&file_path).expect("Read should succeed");
        assert_eq!(content, "Original content");
    }
}