dmsc 0.1.9

Ri - A high-performance Rust middleware framework with modular architecture
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
//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
//!
//! This file is part of Ri.
//! The Ri project belongs to the Dunimd Team.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! You may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//!     http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.

#![allow(non_snake_case)]

//! # File System Module
//! 
//! This module provides a comprehensive file system abstraction for Ri, offering safe and reliable
//! file operations with support for atomic writes, directory management, and structured data formats.
//! 
//! ## Key Components
//! 
//! - **RiFileSystem**: Public-facing file system class
//! - **FileSystemImpl**: Internal file system implementation
//! 
//! ## Design Principles
//! 
//! 1. **Safe Operations**: All file operations are designed to be safe and reliable
//! 2. **Atomic Writes**: Uses atomic write operations to prevent data corruption
//! 3. **Directory Management**: Automatically creates necessary directories
//! 4. **Structured Data Support**: Built-in support for JSON serialization and deserialization
//! 5. **Category-Based Organization**: Organizes files into categories (logs, cache, reports, etc.)
//! 6. **Error Handling**: Provides comprehensive error handling for all file operations
//! 7. **Cloneable**: Designed to be easily cloned for use across different components
//! 
//! ## Usage
//! 
//! ```rust
//! use ri::prelude::*;
//! use std::path::PathBuf;
//! 
//! fn example() -> RiResult<()> {
//!     // Create a file system with a project root
//!     let project_root = PathBuf::from(".");
//!     let fs = RiFileSystem::new_with_root(project_root);
//!     
//!     // Write text to a file
//!     fs.atomic_write_text("example.txt", "Hello, Ri!")?;
//!     
//!     // Read text from a file
//!     let content = fs.read_text("example.txt")?;
//!     println!("File content: {}", content);
//!     
//!     // Write JSON to a file
//!     let data = json!({"key": "value"});
//!     fs.write_json("example.json", &data)?;
//!     
//!     // Read JSON from a file
//!     let read_data: serde_json::Value = fs.read_json("example.json")?;
//!     println!("JSON data: {:?}", read_data);
//!     
//!     // Get category directories
//!     let logs_dir = fs.logs_dir();
//!     println!("Logs directory: {:?}", logs_dir);
//!     
//!     Ok(())
//! }
//! ```

use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::fs::OpenOptions;
use std::time::SystemTime;

use crate::core::RiResult;
use serde::de::DeserializeOwned;
use serde::Serialize;

/// Internal filesystem implementation.
/// 
/// This struct provides the internal implementation of the file system functionality, including
/// directory management, file operations, and category-based organization.
#[derive(Clone)]
struct FileSystemImpl {
    /// Project root directory
    project_root: PathBuf,
    /// Application data root directory
    app_data_root: PathBuf,
}

impl FileSystemImpl {
    /// Creates a new internal file system implementation with specified roots.
    /// 
    /// # Parameters
    /// 
    /// - `project_root`: The project root directory
    /// - `app_data_root`: The application data root directory
    /// 
    /// # Returns
    /// 
    /// A new `FileSystemImpl` instance
    fn new_with_roots(project_root: PathBuf, app_data_root: PathBuf) -> Self {
        FileSystemImpl { project_root, app_data_root }
    }

    /// Creates a new internal file system implementation with a project root and default app data root.
    /// 
    /// The default app data root is created under the project root at `.dms`.
    /// 
    /// # Parameters
    /// 
    /// - `project_root`: The project root directory
    /// 
    /// # Returns
    /// 
    /// A new `FileSystemImpl` instance
    fn new_with_root(project_root: PathBuf) -> Self {
        // Default app data root under project root; can be overridden by core/config.
        let app_data_root = project_root.join(".dms");
        FileSystemImpl::new_with_roots(project_root, app_data_root)
    }

    /// Validates that a path is safe and within the allowed directories.
    ///
    /// This method prevents path traversal attacks by ensuring that the resolved
    /// path is within the project root or app data root.
    ///
    /// # Parameters
    ///
    /// - `path`: The path to validate
    ///
    /// # Returns
    ///
    /// A `RiResult<PathBuf>` containing the canonicalized path if valid
    fn validate_path(&self, path: &Path) -> RiResult<PathBuf> {
        // Security: Check for symlink attacks
        // 1. First canonicalize the allowed directories
        let canonical_project = self.project_root.canonicalize()
            .map_err(|e| crate::core::RiError::Other(format!("Project root canonicalization failed: {e}")))?;
        
        let canonical_app_data = self.app_data_root.canonicalize()
            .map_err(|e| crate::core::RiError::Other(format!("App data root canonicalization failed: {e}")))?;
        
        // 2. For the target path, handle non-existent paths safely
        let canonical_path = if path.exists() {
            // Path exists - canonicalize it (this resolves symlinks)
            path.canonicalize()
                .map_err(|e| crate::core::RiError::Other(format!("Path canonicalization failed: {e}")))?
        } else {
            // Path doesn't exist - check parent directory for symlinks
            let parent = path.parent().ok_or_else(|| {
                crate::core::RiError::Other("Invalid path: no parent directory".to_string())
            })?;
            
            if parent.exists() {
                // Canonicalize parent to resolve any symlinks
                let canonical_parent = parent.canonicalize()
                    .map_err(|e| crate::core::RiError::Other(format!("Parent canonicalization failed: {e}")))?;
                
                // Reconstruct the path with canonicalized parent
                let file_name = path.file_name().ok_or_else(|| {
                    crate::core::RiError::Other("Invalid path: no file name".to_string())
                })?;
                
                canonical_parent.join(file_name)
            } else {
                // Parent doesn't exist - this is an error for security
                return Err(crate::core::RiError::Other(
                    "Path validation failed: parent directory does not exist".to_string()
                ));
            }
        };
        
        // 3. Check if the canonical path is within allowed directories
        if !canonical_path.starts_with(&canonical_project) && 
           !canonical_path.starts_with(&canonical_app_data) {
            return Err(crate::core::RiError::Other(
                "Path traversal detected: path is outside allowed directories".to_string()
            ));
        }
        
        // 4. Additional symlink check: ensure no symlink components in the path
        // This prevents TOCTOU attacks where a symlink is created after validation
        let mut current = canonical_path.clone();
        while let Some(parent) = current.parent() {
            if parent.join(current.file_name().unwrap_or_default()).exists() {
                let metadata = std::fs::symlink_metadata(&current)
                    .map_err(|e| crate::core::RiError::Other(format!("Symlink metadata check failed: {e}")))?;
                
                if metadata.file_type().is_symlink() {
                    // Symlink found - verify it points to allowed directory
                    let symlink_target = std::fs::read_link(&current)
                        .map_err(|e| crate::core::RiError::Other(format!("Failed to read symlink: {e}")))?;
                    
                    let canonical_target = symlink_target.canonicalize()
                        .map_err(|e| crate::core::RiError::Other(format!("Symlink target canonicalization failed: {e}")))?;
                    
                    if !canonical_target.starts_with(&canonical_project) && 
                       !canonical_target.starts_with(&canonical_app_data) {
                        return Err(crate::core::RiError::Other(
                            "Symlink points outside allowed directories".to_string()
                        ));
                    }
                }
            }
            current = parent.to_path_buf();
        }
        
        Ok(canonical_path)
    }

    /// Safely resolves and validates a path relative to the project root.
    ///
    /// # Parameters
    ///
    /// - `path`: The relative or absolute path to resolve
    ///
    /// # Returns
    ///
    /// A `RiResult<PathBuf>` containing the resolved and validated path
    fn resolve_and_validate_path(&self, path: &Path) -> RiResult<PathBuf> {
        let resolved = if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.project_root.join(path)
        };
        
        self.validate_path(&resolved)
    }

    /// Returns the project root directory.
    /// 
    /// # Returns
    /// 
    /// A reference to the project root path
    fn project_root(&self) -> &Path {
        &self.project_root
    }

    /// Safely creates a directory and all its parent directories if they don't exist.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the directory to create
    /// 
    /// # Returns
    /// 
    /// A `RiResult<PathBuf>` containing the created directory path
    fn safe_mkdir(&self, path: &Path) -> RiResult<PathBuf> {
        fs::create_dir_all(path).map_err(|e| crate::core::RiError::Other(format!("safe_mkdir failed: {e}")))?;
        Ok(path.to_path_buf())
    }

    /// Ensures that the parent directory of a given path exists.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path whose parent directory should be ensured
    /// 
    /// # Returns
    /// 
    /// A `RiResult<PathBuf>` containing the parent directory path
    fn ensure_parent_dir(&self, path: &Path) -> RiResult<PathBuf> {
        if let Some(parent) = path.parent() {
            self.safe_mkdir(parent)
        } else {
            Ok(self.project_root.clone())
        }
    }

    /// Atomically writes text to a file.
    /// 
    /// This method writes to a temporary file first, then renames it to the target path,
    /// ensuring that the write operation is atomic.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to write
    /// - `text`: The text to write to the file
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    fn atomic_write_text(&self, path: &Path, text: &str) -> RiResult<()> {
        let validated_path = self.resolve_and_validate_path(path)?;
        self.ensure_parent_dir(&validated_path)?;
        let dir = validated_path.parent().unwrap_or_else(|| Path::new("."));
        let ts = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| crate::core::RiError::Other(format!("timestamp error: {e}")))?;
        let tmp_name = format!(".tmp_{}_{}", ts.as_millis(), validated_path.file_name().and_then(|s| s.to_str()).unwrap_or("tmp"));
        let tmp_path = dir.join(tmp_name);

        {
            let mut file = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&tmp_path)
                .map_err(|e| crate::core::RiError::Other(format!("atomic_write_text open tmp failed: {e}")))?;
            file.write_all(text.as_bytes())
                .map_err(|e| crate::core::RiError::Other(format!("atomic_write_text write failed: {e}")))?;
            file.sync_all()
                .map_err(|e| crate::core::RiError::Other(format!("atomic_write_text sync failed: {e}")))?;
        }

        fs::rename(&tmp_path, &validated_path)
            .map_err(|e| crate::core::RiError::Other(format!("atomic_write_text rename failed: {e}")))?;

        Ok(())
    }

    /// Atomically writes bytes to a file.
    /// 
    /// This method writes to a temporary file first, then renames it to the target path,
    /// ensuring that the write operation is atomic.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to write
    /// - `data`: The bytes to write to the file
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    fn atomic_write_bytes(&self, path: &Path, data: &[u8]) -> RiResult<()> {
        let validated_path = self.resolve_and_validate_path(path)?;
        self.ensure_parent_dir(&validated_path)?;
        let dir = validated_path.parent().unwrap_or_else(|| Path::new("."));
        let ts = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| crate::core::RiError::Other(format!("timestamp error: {e}")))?;
        let tmp_name = format!(".tmp_{}_{}", ts.as_millis(), validated_path.file_name().and_then(|s| s.to_str()).unwrap_or("tmp"));
        let tmp_path = dir.join(tmp_name);

        {
            let mut file = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&tmp_path)
                .map_err(|e| crate::core::RiError::Other(format!("atomic_write_bytes open tmp failed: {e}")))?;
            file.write_all(data)
                .map_err(|e| crate::core::RiError::Other(format!("atomic_write_bytes write failed: {e}")))?;
            file.sync_all()
                .map_err(|e| crate::core::RiError::Other(format!("atomic_write_bytes sync failed: {e}")))?;
        }

        fs::rename(&tmp_path, &validated_path)
            .map_err(|e| crate::core::RiError::Other(format!("atomic_write_bytes rename failed: {e}")))?;

        Ok(())
    }

    /// Reads text from a file.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to read
    /// 
    /// # Returns
    /// 
    /// A `RiResult<String>` containing the file content
    fn read_text(&self, path: &Path) -> RiResult<String> {
        let validated_path = self.resolve_and_validate_path(path)?;
        let mut file = OpenOptions::new()
            .read(true)
            .open(&validated_path)
            .map_err(|e| crate::core::RiError::Other(format!("read_text open failed: {e}")))?;
        let mut buf = String::new();
        file.read_to_string(&mut buf)
            .map_err(|e| crate::core::RiError::Other(format!("read_text read failed: {e}")))?;
        Ok(buf)
    }

    /// Returns the application data directory.
    /// 
    /// Ensures the directory exists before returning it.
    /// 
    /// # Returns
    /// 
    /// The application data directory path
    fn app_dir(&self) -> PathBuf {
        let _ = fs::create_dir_all(&self.app_data_root);
        self.app_data_root.clone()
    }

    /// Returns a category-specific directory.
    /// 
    /// Ensures the directory exists before returning it.
    /// 
    /// # Parameters
    /// 
    /// - `name`: The name of the category
    /// 
    /// # Returns
    /// 
    /// The category directory path
    fn category_dir(&self, name: &str) -> PathBuf {
        let dir = self.app_dir().join(name);
        let _ = fs::create_dir_all(&dir);
        dir
    }
}

/// Public-facing filesystem class.
/// 
/// This struct provides a comprehensive file system abstraction for Ri, offering safe and reliable
/// file operations with support for atomic writes, directory management, and structured data formats.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
#[derive(Clone)]
pub struct RiFileSystem {
    /// Internal file system implementation
    inner: FileSystemImpl,
}

impl RiFileSystem {
    /// Creates a new file system with a project root and default app data root.
    /// 
    /// # Parameters
    /// 
    /// - `project_root`: The project root directory
    /// 
    /// # Returns
    /// 
    /// A new `RiFileSystem` instance
    pub fn new_with_root(project_root: PathBuf) -> Self {
        let inner = FileSystemImpl::new_with_root(project_root);
        RiFileSystem { inner }
    }

    /// Creates a new file system with specified roots.
    /// 
    /// # Parameters
    /// 
    /// - `project_root`: The project root directory
    /// - `app_data_root`: The application data root directory
    /// 
    /// # Returns
    /// 
    /// A new `RiFileSystem` instance
    pub fn new_with_roots(project_root: PathBuf, app_data_root: PathBuf) -> Self {
        let inner = FileSystemImpl::new_with_roots(project_root, app_data_root);
        RiFileSystem { inner }
    }

    /// Creates a new file system with the current working directory as the project root.
    /// 
    /// # Returns
    /// 
    /// A `RiResult<Self>` containing the new `RiFileSystem` instance
    pub fn new_auto_root() -> RiResult<Self> {
        let cwd = std::env::current_dir()
            .map_err(|e| crate::core::RiError::Other(format!("detect project root failed: {e}")))?;
        Ok(Self::new_with_root(cwd))
    }

    /// Returns the project root directory.
    /// 
    /// # Returns
    /// 
    /// A reference to the project root path
    pub fn project_root(&self) -> &Path {
        self.inner.project_root()
    }

    /// Safely creates a directory and all its parent directories if they don't exist.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the directory to create
    /// 
    /// # Returns
    /// 
    /// A `RiResult<PathBuf>` containing the created directory path
    pub fn safe_mkdir<P: AsRef<Path>>(&self, path: P) -> RiResult<PathBuf> {
        self.inner.safe_mkdir(path.as_ref())
    }

    /// Ensures that the parent directory of a given path exists.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path whose parent directory should be ensured
    /// 
    /// # Returns
    /// 
    /// A `RiResult<PathBuf>` containing the parent directory path
    pub fn ensure_parent_dir<P: AsRef<Path>>(&self, path: P) -> RiResult<PathBuf> {
        self.inner.ensure_parent_dir(path.as_ref())
    }

    /// Atomically writes text to a file.
    /// 
    /// This method writes to a temporary file first, then renames it to the target path,
    /// ensuring that the write operation is atomic.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to write
    /// - `text`: The text to write to the file
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    pub fn atomic_write_text<P: AsRef<Path>>(&self, path: P, text: &str) -> RiResult<()> {
        self.inner.atomic_write_text(path.as_ref(), text)
    }

    /// Atomically writes bytes to a file.
    /// 
    /// This method writes to a temporary file first, then renames it to the target path,
    /// ensuring that the write operation is atomic.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to write
    /// - `data`: The bytes to write to the file
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    pub fn atomic_write_bytes<P: AsRef<Path>>(&self, path: P, data: &[u8]) -> RiResult<()> {
        self.inner.atomic_write_bytes(path.as_ref(), data)
    }

    /// Reads text from a file.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to read
    /// 
    /// # Returns
    /// 
    /// A `RiResult<String>` containing the file content
    pub fn read_text<P: AsRef<Path>>(&self, path: P) -> RiResult<String> {
        self.inner.read_text(path.as_ref())
    }

    /// Reads JSON from a file and deserializes it into a type.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the JSON file to read
    /// 
    /// # Type Parameters
    /// 
    /// - `T`: The type to deserialize the JSON into
    /// 
    /// # Returns
    /// 
    /// A `RiResult<T>` containing the deserialized data
    pub fn read_json<P: AsRef<Path>, T: DeserializeOwned>(&self, path: P) -> RiResult<T> {
        let text = self.read_text(path)?;
        serde_json::from_str(&text)
            .map_err(|e| crate::core::RiError::Other(format!("json read failed: {e}")))
    }

    /// Checks if a file or directory exists.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to check
    /// 
    /// # Returns
    /// 
    /// `true` if the path exists, `false` otherwise
    pub fn exists<P: AsRef<Path>>(&self, path: P) -> bool {
        path.as_ref().exists()
    }

    /// Removes a file.
    /// 
    /// # Security
    /// 
    /// This method validates the path to prevent path traversal attacks.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to remove
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    pub fn remove_file<P: AsRef<Path>>(&self, path: P) -> RiResult<()> {
        let validated_path = self.inner.resolve_and_validate_path(path.as_ref())?;
        match fs::remove_file(&validated_path) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(crate::core::RiError::Other(format!("remove_file failed: {e}"))),
        }
    }

    /// Removes a directory and all its contents.
    /// 
    /// # Security
    /// 
    /// This method validates the path to prevent path traversal attacks.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the directory to remove
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    pub fn remove_dir_all<P: AsRef<Path>>(&self, path: P) -> RiResult<()> {
        let validated_path = self.inner.resolve_and_validate_path(path.as_ref())?;
        match fs::remove_dir_all(&validated_path) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(crate::core::RiError::Other(format!("remove_dir_all failed: {e}"))),
        }
    }

    /// Copies a file from one path to another.
    /// 
    /// # Security
    /// 
    /// This method validates both source and destination paths to prevent
    /// path traversal attacks.
    /// 
    /// # Parameters
    /// 
    /// - `from`: The source file path
    /// - `to`: The destination file path
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    pub fn copy_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, from: P, to: Q) -> RiResult<()> {
        let src = self.inner.resolve_and_validate_path(from.as_ref())?;
        let dst = self.inner.resolve_and_validate_path(to.as_ref())?;
        
        if let Some(parent) = dst.parent() {
            self.safe_mkdir(parent)?;
        }
        fs::copy(&src, &dst)
            .map_err(|e| crate::core::RiError::Other(format!("copy_file failed: {e}")))?;
        Ok(())
    }

    /// Appends text to a file.
    /// 
    /// # Security
    /// 
    /// This method validates the path to prevent path traversal attacks.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to append to
    /// - `text`: The text to append to the file
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    pub fn append_text<P: AsRef<Path>>(&self, path: P, text: &str) -> RiResult<()> {
        use std::io::Write as _;

        let validated_path = self.inner.resolve_and_validate_path(path.as_ref())?;
        self.ensure_parent_dir(&validated_path)?;
        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&validated_path)
            .map_err(|e| crate::core::RiError::Other(format!("append_text open failed: {e}")))?;
        file.write_all(text.as_bytes())
            .map_err(|e| crate::core::RiError::Other(format!("append_text write failed: {e}")))?;
        file.flush()
            .map_err(|e| crate::core::RiError::Other(format!("append_text flush failed: {e}")))?;
        Ok(())
    }

    /// Writes a JSON value to a file.
    /// 
    /// # Parameters
    /// 
    /// - `path`: The path to the file to write
    /// - `value`: The value to serialize and write
    /// 
    /// # Type Parameters
    /// 
    /// - `T`: The type of the value to serialize
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    pub fn write_json<P: AsRef<Path>, T: Serialize>(&self, path: P, value: &T) -> RiResult<()> {
        let text = serde_json::to_string_pretty(value)
            .map_err(|e| crate::core::RiError::Other(format!("json serialize failed: {e}")))?;
        self.atomic_write_text(path, &text)
    }

    /// Returns the application data directory.
    /// 
    /// # Returns
    /// 
    /// The application data directory path
    pub fn app_dir(&self) -> PathBuf {
        self.inner.app_dir()
    }

    /// Returns the logs directory.
    /// 
    /// # Returns
    /// 
    /// The logs directory path
    pub fn logs_dir(&self) -> PathBuf {
        self.inner.category_dir("logs")
    }

    /// Returns the cache directory.
    /// 
    /// # Returns
    /// 
    /// The cache directory path
    pub fn cache_dir(&self) -> PathBuf {
        self.inner.category_dir("cache")
    }

    /// Returns the reports directory.
    /// 
    /// # Returns
    /// 
    /// The reports directory path
    pub fn reports_dir(&self) -> PathBuf {
        self.inner.category_dir("reports")
    }

    /// Returns the observability directory.
    /// 
    /// # Returns
    /// 
    /// The observability directory path
    pub fn observability_dir(&self) -> PathBuf {
        self.inner.category_dir("observability")
    }

    /// Returns the temporary directory.
    /// 
    /// # Returns
    /// 
    /// The temporary directory path
    pub fn temp_dir(&self) -> PathBuf {
        self.inner.category_dir("tmp")
    }

    /// Ensures a path exists under a specific category directory.
    /// 
    /// # Parameters
    /// 
    /// - `category`: The category name ("logs", "cache", "reports", "observability", "tmp", or other)
    /// - `path_or_name`: The path or name to ensure under the category directory
    /// 
    /// # Returns
    /// 
    /// The full path to the ensured file or directory
    pub fn ensure_category_path<S: AsRef<str>, P: AsRef<Path>>(&self, category: S, path_or_name: P) -> PathBuf {
        let base = match category.as_ref() {
            "logs" => self.logs_dir(),
            "cache" => self.cache_dir(),
            "reports" => self.reports_dir(),
            "observability" => self.observability_dir(),
            "tmp" => self.temp_dir(),
            _ => self.app_dir(),
        };

        let target = base.join(path_or_name.as_ref());
        let _ = fs::create_dir_all(target.parent().unwrap_or(&base));
        target
    }

    /// Normalizes a path under a specific category directory, using only the file name.
    /// 
    /// # Parameters
    /// 
    /// - `category`: The category name ("logs", "cache", "reports", "observability", "tmp", or other)
    /// - `path_or_name`: The path or name to normalize
    /// 
    /// # Returns
    /// 
    /// The full path to the normalized file or directory
    pub fn normalize_under_category<S: AsRef<str>, P: AsRef<Path>>(&self, category: S, path_or_name: P) -> PathBuf {
        let name = path_or_name.as_ref().file_name().unwrap_or_else(|| std::ffi::OsStr::new(""));
        self.ensure_category_path(category, PathBuf::from(name))
    }
}

#[cfg(feature = "pyo3")]
/// Python bindings for RiFileSystem
#[pyo3::prelude::pymethods]
impl RiFileSystem {
    /// Create a new file system with a project root from Python
    #[new]
    fn py_new(project_root: String) -> Result<Self, pyo3::prelude::PyErr> {
        let path = PathBuf::from(project_root);
        Ok(Self::new_with_root(path))
    }
    
    /// Create a new file system with current working directory as root from Python
    #[staticmethod]
    fn new_auto_root_py() -> Result<Self, pyo3::PyErr> {
        Self::new_auto_root()
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to create filesystem: {e}")))
    }
    
    #[pyo3(name = "atomic_write_text")]
    fn atomic_write_text_impl(&self, path: String, text: String) -> Result<(), pyo3::PyErr> {
        self.atomic_write_text(&path, &text)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to write text: {e}")))
    }
    
    #[pyo3(name = "atomic_write_bytes")]
    fn atomic_write_bytes_impl(&self, path: String, data: Vec<u8>) -> Result<(), pyo3::PyErr> {
        self.atomic_write_bytes(&path, &data)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to write bytes: {e}")))
    }
    
    #[pyo3(name = "read_text")]
    fn read_text_impl(&self, path: String) -> Result<String, pyo3::PyErr> {
        self.read_text(&path)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to read text: {e}")))
    }
    
    #[pyo3(name = "write_json")]
    fn write_json_impl(&self, path: String, value: String) -> Result<(), pyo3::PyErr> {
        let json_value: serde_json::Value = serde_json::from_str(&value)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid JSON: {e}")))?;
        self.write_json(&path, &json_value)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to write JSON: {e}")))
    }
    
    #[pyo3(name = "read_json")]
    fn read_json_impl(&self, path: String) -> Result<String, pyo3::PyErr> {
        let json_value: serde_json::Value = self.read_json(&path)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to read JSON: {e}")))?;
        serde_json::to_string_pretty(&json_value)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize JSON: {e}")))
    }
    
    #[pyo3(name = "exists")]
    fn exists_impl(&self, path: String) -> bool {
        self.exists(&path)
    }
    
    #[pyo3(name = "remove_file")]
    fn remove_file_impl(&self, path: String) -> Result<(), pyo3::PyErr> {
        self.remove_file(&path)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to remove file: {e}")))
    }
    
    #[pyo3(name = "remove_dir_all")]
    fn remove_dir_all_impl(&self, path: String) -> Result<(), pyo3::PyErr> {
        self.remove_dir_all(&path)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to remove directory: {e}")))
    }
    
    #[pyo3(name = "copy_file")]
    fn copy_file_impl(&self, from: String, to: String) -> Result<(), pyo3::PyErr> {
        self.copy_file(&from, &to)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to copy file: {e}")))
    }
    
    #[pyo3(name = "append_text")]
    fn append_text_impl(&self, path: String, text: String) -> Result<(), pyo3::PyErr> {
        self.append_text(&path, &text)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to append text: {e}")))
    }
    
    #[pyo3(name = "safe_mkdir")]
    fn safe_mkdir_impl(&self, path: String) -> Result<String, pyo3::PyErr> {
        let result = self.safe_mkdir(&path)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to create directory: {e}")))?;
        Ok(result.to_string_lossy().to_string())
    }
    
    #[pyo3(name = "ensure_parent_dir")]
    fn ensure_parent_dir_impl(&self, path: String) -> Result<String, pyo3::PyErr> {
        let result = self.ensure_parent_dir(&path)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to ensure parent directory: {e}")))?;
        Ok(result.to_string_lossy().to_string())
    }
    
    #[pyo3(name = "get_project_root")]
    fn get_project_root_impl(&self) -> String {
        self.project_root().to_string_lossy().to_string()
    }
    
    #[pyo3(name = "get_app_dir")]
    fn get_app_dir_impl(&self) -> String {
        self.app_dir().to_string_lossy().to_string()
    }
    
    #[pyo3(name = "get_logs_dir")]
    fn get_logs_dir_impl(&self) -> String {
        self.logs_dir().to_string_lossy().to_string()
    }
    
    #[pyo3(name = "get_cache_dir")]
    fn get_cache_dir_impl(&self) -> String {
        self.cache_dir().to_string_lossy().to_string()
    }
    
    #[pyo3(name = "get_reports_dir")]
    fn get_reports_dir_impl(&self) -> String {
        self.reports_dir().to_string_lossy().to_string()
    }
    
    #[pyo3(name = "get_observability_dir")]
    fn get_observability_dir_impl(&self) -> String {
        self.observability_dir().to_string_lossy().to_string()
    }
    
    #[pyo3(name = "get_temp_dir")]
    fn get_temp_dir_impl(&self) -> String {
        self.temp_dir().to_string_lossy().to_string()
    }
    
    #[pyo3(name = "ensure_category_path")]
    fn ensure_category_path_impl(&self, category: String, path_or_name: String) -> String {
        self.ensure_category_path(&category, &path_or_name)
            .to_string_lossy()
            .to_string()
    }
    
    #[pyo3(name = "normalize_under_category")]
    fn normalize_under_category_impl(&self, category: String, path_or_name: String) -> String {
        self.normalize_under_category(&category, &path_or_name)
            .to_string_lossy()
            .to_string()
    }
}