rcman 0.1.9

Framework-agnostic settings management with schema, backup/restore, secrets and derive macro support
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
//! Profile manager implementation
//!
//! Handles profile lifecycle: create, switch, delete, rename, duplicate.

use crate::error::{Error, Result};
use crate::profiles::{DEFAULT_PROFILE, PROFILES_DIR, validate_profile_name};
use crate::utils::sync::RwLockExt;

use log::{debug, info};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

/// Type alias for cache invalidation callback
pub type InvalidateCallback = Arc<dyn Fn() + Send + Sync>;

// =============================================================================
// Profile Manifest
// =============================================================================

/// Profile manifest stored in `.profiles.json`
///
/// Tracks which profiles exist and which is currently active.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileManifest {
    /// Currently active profile name
    pub active: String,

    /// List of all profile names
    pub profiles: Vec<String>,
}

impl Default for ProfileManifest {
    fn default() -> Self {
        Self {
            active: DEFAULT_PROFILE.to_string(),
            profiles: vec![DEFAULT_PROFILE.to_string()],
        }
    }
}

impl ProfileManifest {
    /// Create a new manifest with a single default profile
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Check if a profile exists
    #[must_use]
    pub fn has_profile(&self, name: &str) -> bool {
        self.profiles.iter().any(|p| p == name)
    }

    /// Add a profile to the manifest
    pub fn add_profile(&mut self, name: String) {
        if !self.has_profile(&name) {
            self.profiles.push(name);
        }
    }

    /// Remove a profile from the manifest
    pub fn remove_profile(&mut self, name: &str) -> bool {
        if let Some(pos) = self.profiles.iter().position(|p| p == name) {
            self.profiles.remove(pos);
            true
        } else {
            false
        }
    }

    /// Rename a profile in the manifest
    pub fn rename_profile(&mut self, from: &str, to: String) -> bool {
        if let Some(pos) = self.profiles.iter().position(|p| p == from) {
            self.profiles[pos].clone_from(&to);
            if self.active == from {
                self.active = to;
            }
            true
        } else {
            false
        }
    }

    /// Set the active profile
    pub fn set_active(&mut self, name: &str) -> bool {
        if self.has_profile(name) {
            self.active = name.to_string();
            true
        } else {
            false
        }
    }
}

// =============================================================================
// Profile Event
// =============================================================================

/// Events emitted when profiles change
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProfileEvent {
    /// Profile was switched
    Switched {
        /// Previous active profile
        from: String,
        /// New active profile
        to: String,
    },
    /// New profile was created
    Created {
        /// Name of the created profile
        name: String,
    },
    /// Profile was deleted
    Deleted {
        /// Name of the deleted profile
        name: String,
    },
    /// Profile was renamed
    Renamed {
        /// Original name
        from: String,
        /// New name
        to: String,
    },
    /// Profile was duplicated
    Duplicated {
        /// Source profile
        source: String,
        /// New profile name
        target: String,
    },
}

// =============================================================================
// Profile Manager
// =============================================================================

use crate::storage::StorageBackend;

/// Type alias for profile event callback
pub type ProfileEventCallback = Arc<dyn Fn(ProfileEvent) + Send + Sync>;

/// Manages profiles for a specific target (settings or sub-settings)
///
/// The `ProfileManager` handles:
/// - Creating, deleting, renaming, and duplicating profiles
/// - Switching the active profile
/// - Persisting the profile manifest
/// - Emitting events on profile changes
pub struct ProfileManager<S: StorageBackend = crate::storage::JsonStorage> {
    /// Path to the manifest file (e.g., .profiles.json or .profiles.toml)
    manifest_path: PathBuf,

    /// Path to the profiles directory
    profiles_dir: PathBuf,

    /// Name of this profile target (for logging/errors)
    target_name: String,

    /// Storage backend for reading/writing manifest
    storage: S,

    /// Cached manifest (loaded on first access)
    manifest: RwLock<Option<ProfileManifest>>,

    /// Event callback
    on_event: RwLock<Option<ProfileEventCallback>>,

    /// Callback to invalidate caches when profile switches
    on_invalidate: RwLock<Option<InvalidateCallback>>,
}

impl<S: StorageBackend> ProfileManager<S> {
    /// Create a new profile manager for a given base directory
    ///
    /// # Arguments
    ///
    /// * `base_dir` - The directory containing the profiles
    /// * `target_name` - Name of this profile target (e.g., "remotes", "settings")
    /// * `storage` - Storage backend to use for manifest
    pub fn new(base_dir: &Path, target_name: impl Into<String>, storage: S) -> Self {
        // Manifest filename depends on storage extension
        let filename = format!(".profiles.{}", storage.extension());

        Self {
            manifest_path: base_dir.join(filename),
            profiles_dir: base_dir.join(PROFILES_DIR),
            target_name: target_name.into(),
            storage,
            manifest: RwLock::new(None),
            on_event: RwLock::new(None),
            on_invalidate: RwLock::new(None),
        }
    }

    /// Initialize the profile manager, running migrations if enabled
    ///
    /// This is a helper to centralize initialization logic that was previously in `SettingsManager`.
    ///
    /// # Arguments
    ///
    /// * `config_dir` - The root configuration directory
    /// * `target_name` - The name of the target (e.g. "settings")
    /// * `storage` - Storage backend
    /// * `enabled` - Whether profiles are enabled
    /// * `migrator` - Migration strategy
    ///
    /// # Returns
    ///
    /// Returns a tuple of `(active_settings_dir, Option<ProfileManager>)`.
    /// If profiles are disabled, returns `(config_dir, None)`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Migration fails
    /// - Profile manager initialization fails
    /// - Active profile path cannot be resolved
    pub fn initialize(
        config_dir: &Path,
        target_name: &str,
        storage: S,
        enabled: bool,
        migrator: &crate::profiles::ProfileMigrator,
    ) -> Result<(PathBuf, Option<Self>)> {
        if enabled {
            // Run migration if needed
            // For main settings, we assume multi-file mode (false) and no specific extension (None)
            // as it manages a directory of settings.
            crate::profiles::migrate(config_dir, target_name, false, &storage, migrator)?;

            let pm = Self::new(config_dir, target_name, storage);
            // Use active path from manifest (defaults to "default")
            let active = pm.active_path()?;

            info!(
                "Profiles initialized for '{target_name}' (active: {})",
                active.display()
            );
            Ok((active, Some(pm)))
        } else {
            Ok((config_dir.to_path_buf(), None))
        }
    }

    /// Set the event callback
    ///
    /// # Arguments
    ///
    /// * `callback` - The callback function to be called when a profile event occurs
    pub fn set_on_event<F>(&self, callback: F)
    where
        F: Fn(ProfileEvent) + Send + Sync + 'static,
    {
        if let Ok(mut guard) = self.on_event.write_recovered() {
            *guard = Some(Arc::new(callback));
        } else {
            debug!(
                "Failed to register profile event callback for '{}' due to lock recovery error",
                self.target_name
            );
        }
    }

    /// Set the cache invalidation callback
    ///
    /// # Arguments
    ///
    /// * `callback` - The callback function to be called when a profile switch occurs
    pub fn set_on_invalidate<F>(&self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        if let Ok(mut guard) = self.on_invalidate.write_recovered() {
            *guard = Some(Arc::new(callback));
        } else {
            debug!(
                "Failed to register profile invalidation callback for '{}' due to lock recovery error",
                self.target_name
            );
        }
    }

    /// Emit a profile event
    fn emit_event(&self, event: ProfileEvent) {
        if let Ok(guard) = self.on_event.read_recovered() {
            if let Some(callback) = guard.as_ref() {
                callback(event);
            }
        } else {
            debug!(
                "Failed to emit profile event for '{}' due to lock recovery error",
                self.target_name
            );
        }
    }

    /// Invalidate caches
    fn invalidate_caches(&self) {
        if let Ok(guard) = self.on_invalidate.read_recovered() {
            if let Some(callback) = guard.as_ref() {
                callback();
            }
        } else {
            debug!(
                "Failed to run profile invalidation callback for '{}' due to lock recovery error",
                self.target_name
            );
        }
    }

    /// Invalidate the internal manifest cache
    ///
    /// This forces the manifest to be re-read from disk on the next access.
    pub fn invalidate_manifest(&self) {
        if let Ok(mut guard) = self.manifest.write_recovered() {
            *guard = None;
        } else {
            debug!(
                "Failed to invalidate profile manifest cache for '{}' due to lock recovery error",
                self.target_name
            );
        }
    }

    /// Get the path to a specific profile's directory
    pub fn profile_path(&self, name: &str) -> PathBuf {
        self.profiles_dir.join(name)
    }

    /// Get the path to the active profile's directory
    ///
    /// # Returns
    ///
    /// Returns the path to the active profile's directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be read.
    pub fn active_path(&self) -> Result<PathBuf> {
        let active = self.active()?;
        Ok(self.profile_path(&active))
    }

    /// Ensure the manifest is loaded
    fn ensure_manifest(&self) -> Result<()> {
        {
            let guard = self.manifest.read_recovered()?;
            if guard.is_some() {
                return Ok(());
            }
        }

        let mut guard = self.manifest.write_recovered()?;
        if guard.is_some() {
            return Ok(());
        }

        // Try to load existing manifest
        let load_result = if self.manifest_path.exists() {
            // Normal case: load from current manifest path
            self.storage.read(&self.manifest_path).map(Some)
        } else {
            Ok(None)
        };

        match load_result {
            Ok(Some(manifest)) => {
                *guard = Some(manifest);
            }
            Ok(None) => {
                // Create default manifest
                *guard = Some(ProfileManifest::default());
            }
            Err(e) => return Err(e),
        }

        Ok(())
    }

    /// Save the manifest to disk
    fn save_manifest(&self) -> Result<()> {
        let manifest_clone = {
            let guard = self.manifest.read_recovered()?;
            let manifest = guard.as_ref().ok_or(Error::NotInitialized)?;
            manifest.clone()
        };
        // The read lock is now dropped, so concurrent operations are not blocked
        // while we wait for the (potentially slow) disk I/O to complete.

        self.storage.write(&self.manifest_path, &manifest_clone)?;

        debug!(
            "Saved profile manifest for '{}': active={}",
            self.target_name, manifest_clone.active
        );

        Ok(())
    }

    // =========================================================================
    // Public API
    // =========================================================================

    /// Get the currently active profile name
    ///
    /// # Returns
    ///
    /// Returns the name of the currently active profile.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be read.
    pub fn active(&self) -> Result<String> {
        self.ensure_manifest()?;
        let guard = self.manifest.read_recovered()?;
        Ok(guard.as_ref().ok_or(Error::NotInitialized)?.active.clone())
    }

    /// List all profile names
    ///
    /// # Returns
    ///
    /// Returns a vector of profile names.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be read.
    pub fn list(&self) -> Result<Vec<String>> {
        self.ensure_manifest()?;
        let guard = self.manifest.read_recovered()?;
        Ok(guard
            .as_ref()
            .ok_or(Error::NotInitialized)?
            .profiles
            .clone())
    }

    /// Check if a profile exists
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the profile to check
    ///
    /// # Returns
    ///
    /// Returns `true` if the profile exists, `false` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be read.
    pub fn exists(&self, name: &str) -> Result<bool> {
        self.ensure_manifest()?;
        let guard = self.manifest.read_recovered()?;
        Ok(guard
            .as_ref()
            .ok_or(Error::NotInitialized)?
            .has_profile(name))
    }

    /// Create a new profile
    ///
    /// Creates an empty profile directory and updates the manifest.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the profile to create
    ///
    /// # Errors
    ///
    /// Returns an error if the profile cannot be created.
    pub fn create(&self, name: &str) -> Result<()> {
        validate_profile_name(name)?;
        self.ensure_manifest()?;

        // Check if already exists
        {
            let guard = self.manifest.read_recovered()?;
            if guard
                .as_ref()
                .ok_or(Error::NotInitialized)?
                .has_profile(name)
            {
                return Err(Error::ProfileAlreadyExists(name.to_string()));
            }
        }

        // Create profile directory
        let profile_dir = self.profile_path(name);
        crate::utils::security::ensure_secure_dir(&profile_dir)?;

        // Update manifest
        {
            let mut guard = self.manifest.write_recovered()?;
            guard
                .as_mut()
                .ok_or(Error::NotInitialized)?
                .add_profile(name.to_string());
        }
        self.save_manifest()?;

        info!("Created profile '{}' for '{}'", name, self.target_name);
        self.emit_event(ProfileEvent::Created {
            name: name.to_string(),
        });

        Ok(())
    }

    /// Switch to a different profile
    ///
    /// Updates the active profile in the manifest and invalidates caches.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the profile to switch to
    ///
    /// # Errors
    ///
    /// Returns an error if the profile cannot be switched.
    pub fn switch(&self, name: &str) -> Result<()> {
        self.ensure_manifest()?;

        let from = {
            let guard = self.manifest.read_recovered()?;
            let manifest = guard.as_ref().ok_or(Error::NotInitialized)?;
            if !manifest.has_profile(name) {
                return Err(Error::ProfileNotFound(name.to_string()));
            }
            manifest.active.clone()
        };

        if from == name {
            debug!("Profile '{name}' is already active");
            return Ok(());
        }

        // Update manifest
        {
            let mut guard = self.manifest.write_recovered()?;
            guard
                .as_mut()
                .ok_or(Error::NotInitialized)?
                .set_active(name);
        }
        self.save_manifest()?;

        info!(
            "Switched profile for '{}': {} -> {}",
            self.target_name, from, name
        );

        // Invalidate caches
        self.invalidate_caches();

        self.emit_event(ProfileEvent::Switched {
            from,
            to: name.to_string(),
        });

        Ok(())
    }

    /// Delete a profile
    ///
    /// Removes the profile directory and updates the manifest.
    /// Cannot delete the active profile or the last remaining profile.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the profile to delete
    ///
    /// # Errors
    ///
    /// Returns an error if the profile cannot be deleted.
    pub fn delete(&self, name: &str) -> Result<()> {
        self.ensure_manifest()?;

        {
            let guard = self.manifest.read_recovered()?;
            let manifest = guard.as_ref().ok_or(Error::NotInitialized)?;

            if !manifest.has_profile(name) {
                return Err(Error::ProfileNotFound(name.to_string()));
            }

            if manifest.active == name {
                return Err(Error::CannotDeleteActiveProfile(name.to_string()));
            }

            if manifest.profiles.len() <= 1 {
                return Err(Error::CannotDeleteLastProfile);
            }
        }

        // Delete profile directory
        let profile_dir = self.profile_path(name);
        if profile_dir.exists() {
            std::fs::remove_dir_all(&profile_dir).map_err(|e| Error::FileDelete {
                path: profile_dir.clone(),
                source: e,
            })?;
        }

        // Update manifest
        {
            let mut guard = self.manifest.write_recovered()?;
            guard
                .as_mut()
                .ok_or(Error::NotInitialized)?
                .remove_profile(name);
        }
        self.save_manifest()?;

        info!("Deleted profile '{}' from '{}'", name, self.target_name);
        self.emit_event(ProfileEvent::Deleted {
            name: name.to_string(),
        });

        Ok(())
    }

    /// Rename a profile
    ///
    /// # Arguments
    ///
    /// * `from` - The name of the profile to rename
    /// * `to` - The new name for the profile
    ///
    /// # Errors
    ///
    /// Returns an error if the profile cannot be renamed.
    pub fn rename(&self, from: &str, to: &str) -> Result<()> {
        validate_profile_name(to)?;
        self.ensure_manifest()?;

        {
            let guard = self.manifest.read_recovered()?;
            let manifest = guard.as_ref().ok_or(Error::NotInitialized)?;

            if !manifest.has_profile(from) {
                return Err(Error::ProfileNotFound(from.to_string()));
            }

            if manifest.has_profile(to) {
                return Err(Error::ProfileAlreadyExists(to.to_string()));
            }
        }

        // Rename directory
        let from_dir = self.profile_path(from);
        let to_dir = self.profile_path(to);

        if from_dir.exists() {
            std::fs::rename(&from_dir, &to_dir).map_err(|e| Error::FileWrite {
                path: std::path::PathBuf::from(format!(
                    "{} -> {}",
                    from_dir.display(),
                    to_dir.display()
                )),
                source: e,
            })?;
        } else {
            // Create the new directory if old didn't exist
            std::fs::create_dir_all(&to_dir).map_err(|e| Error::DirectoryCreate {
                path: to_dir.clone(),
                source: e,
            })?;
        }

        // Update manifest
        {
            let mut guard = self.manifest.write_recovered()?;
            guard
                .as_mut()
                .ok_or(Error::NotInitialized)?
                .rename_profile(from, to.to_string());
        }
        self.save_manifest()?;

        info!(
            "Renamed profile '{}' -> '{}' in '{}'",
            from, to, self.target_name
        );

        self.emit_event(ProfileEvent::Renamed {
            from: from.to_string(),
            to: to.to_string(),
        });

        Ok(())
    }

    /// Duplicate a profile
    ///
    /// Copies all contents from the source profile to a new profile.
    ///
    /// # Arguments
    ///
    /// * `source` - The name of the source profile
    /// * `target` - The name of the target profile
    ///
    /// # Errors
    ///
    /// Returns an error if the profile cannot be duplicated.
    pub fn duplicate(&self, source: &str, target: &str) -> Result<()> {
        validate_profile_name(target)?;
        self.ensure_manifest()?;

        {
            let guard = self.manifest.read_recovered()?;
            let manifest = guard.as_ref().ok_or(Error::NotInitialized)?;

            if !manifest.has_profile(source) {
                return Err(Error::ProfileNotFound(source.to_string()));
            }

            if manifest.has_profile(target) {
                return Err(Error::ProfileAlreadyExists(target.to_string()));
            }
        }

        let source_dir = self.profile_path(source);
        let target_dir = self.profile_path(target);

        // Copy directory contents
        if source_dir.exists() {
            copy_dir_recursive(&source_dir, &target_dir)?;
        } else {
            std::fs::create_dir_all(&target_dir).map_err(|e| Error::DirectoryCreate {
                path: target_dir.clone(),
                source: e,
            })?;
        }

        // Update manifest
        {
            let mut guard = self.manifest.write_recovered()?;
            guard
                .as_mut()
                .ok_or(Error::NotInitialized)?
                .add_profile(target.to_string());
        }
        self.save_manifest()?;

        info!(
            "Duplicated profile '{}' -> '{}' in '{}'",
            source, target, self.target_name
        );

        self.emit_event(ProfileEvent::Duplicated {
            source: source.to_string(),
            target: target.to_string(),
        });

        Ok(())
    }

    /// Rollback to flat structure (removes all profiles except active)
    ///
    /// # ⚠️ Warning
    ///
    /// This operation is **irreversible** and will:
    /// - Keep only the **active profile's** data
    /// - **Permanently delete** all other profiles
    /// - Remove the profile structure entirely
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rcman::{SettingsManager, SubSettingsConfig};
    ///
    /// let manager = SettingsManager::builder("my-app", "1.0.0")
    ///     .with_sub_settings(SubSettingsConfig::new("remotes").with_profiles())
    ///     .build()?;
    ///
    /// let remotes = manager.sub_settings("remotes")?;
    ///
    /// // Remove profile support, keeping only active profile data
    /// remotes.profiles()?.rollback_to_flat()?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the rollback fails
    pub fn rollback_to_flat(&self) -> Result<()> {
        use crate::profiles::rollback_migration;

        // Need to construct the root_dir from profiles_dir parent
        let root_dir = self
            .profiles_dir
            .parent()
            .ok_or_else(|| Error::Config("Invalid profiles directory structure".to_string()))?;

        // Determine single_file_mode by checking if root_dir is a file path
        // In single file mode, root_dir is like "config/backends" (no extension)
        // In multi file mode, root_dir is like "config/remotes" (directory)
        let single_file_mode = root_dir.with_extension(self.storage.extension()).is_file();

        rollback_migration(root_dir, &self.target_name, single_file_mode, &self.storage)?;

        // Invalidate caches
        self.invalidate_caches();

        Ok(())
    }

    /// Initialize profiles with auto-migration from flat structure
    ///
    /// If files exist in the base directory but no manifest exists,
    /// moves them into a "default" profile.
    ///
    /// # Arguments
    ///
    /// * `detect_existing` - A function that returns `true` if there are existing files to migrate
    ///
    /// # Returns
    ///
    /// Returns `true` if migration was needed, `false` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be read or saved.
    pub fn initialize_with_migration<F>(&self, detect_existing: F) -> Result<bool>
    where
        F: FnOnce() -> bool,
    {
        // If manifest exists, nothing to migrate
        if self.manifest_path.exists() {
            self.ensure_manifest()?;
            return Ok(false);
        }

        // Check if there are existing files to migrate
        if !detect_existing() {
            // No existing files, just initialize fresh
            self.ensure_manifest()?;

            // Create default profile directory
            let default_dir = self.profile_path(DEFAULT_PROFILE);
            if !default_dir.exists() {
                std::fs::create_dir_all(&default_dir).map_err(|e| Error::DirectoryCreate {
                    path: default_dir.clone(),
                    source: e,
                })?;
            }

            self.save_manifest()?;
            return Ok(false);
        }

        // Migration will be handled by the caller
        // Just initialize the manifest
        let mut guard = self.manifest.write_recovered()?;
        *guard = Some(ProfileManifest::default());
        drop(guard);

        // Create profiles directory
        if !self.profiles_dir.exists() {
            std::fs::create_dir_all(&self.profiles_dir).map_err(|e| Error::DirectoryCreate {
                path: self.profiles_dir.clone(),
                source: e,
            })?;
        }

        info!(
            "Initialized profiles for '{}', migration needed",
            self.target_name
        );

        Ok(true) // Migration needed
    }

    /// Mark migration as complete and save manifest
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be saved.
    pub fn complete_migration(&self) -> Result<()> {
        self.save_manifest()?;
        info!("Profile migration complete for '{}'", self.target_name);
        Ok(())
    }

    /// Get the manifest (for advanced use cases)
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be read.
    pub fn manifest(&self) -> Result<ProfileManifest> {
        self.ensure_manifest()?;
        let guard = self.manifest.read_recovered()?;
        Ok(guard.as_ref().ok_or(Error::NotInitialized)?.clone())
    }

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

// =============================================================================
// Helper Functions
// =============================================================================

/// Recursively copy a directory
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    if !dst.exists() {
        std::fs::create_dir_all(dst).map_err(|e| Error::DirectoryCreate {
            path: dst.to_path_buf(),
            source: e,
        })?;
    }

    for entry in std::fs::read_dir(src).map_err(|e| Error::FileRead {
        path: src.to_path_buf(),
        source: e,
    })? {
        let entry = entry.map_err(|e| Error::FileRead {
            path: src.to_path_buf(),
            source: e,
        })?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());

        if src_path.is_dir() {
            copy_dir_recursive(&src_path, &dst_path)?;
        } else {
            std::fs::copy(&src_path, &dst_path).map_err(|e| Error::FileWrite {
                path: dst_path.clone(),
                source: e,
            })?;
        }
    }

    Ok(())
}

// =============================================================================
// Tests
// =============================================================================

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

    fn create_test_manager() -> (
        tempfile::TempDir,
        ProfileManager<crate::storage::JsonStorage>,
    ) {
        let dir = tempdir().unwrap();
        let storage = crate::storage::JsonStorage::compact();
        let manager = ProfileManager::new(dir.path(), "test", storage);
        (dir, manager)
    }

    #[test]
    fn test_create_profile() {
        let (_dir, manager) = create_test_manager();

        manager.create("work").unwrap();

        let profiles = manager.list().unwrap();
        assert!(profiles.contains(&"default".to_string()));
        assert!(profiles.contains(&"work".to_string()));
    }

    #[test]
    fn test_switch_profile() {
        let (_dir, manager) = create_test_manager();

        manager.create("work").unwrap();
        manager.switch("work").unwrap();

        assert_eq!(manager.active().unwrap(), "work");
    }

    #[test]
    fn test_switch_nonexistent_profile() {
        let (_dir, manager) = create_test_manager();

        let result = manager.switch("nonexistent");
        assert!(matches!(result, Err(Error::ProfileNotFound(_))));
    }

    #[test]
    fn test_delete_profile() {
        let (_dir, manager) = create_test_manager();

        manager.create("work").unwrap();
        manager.delete("work").unwrap();

        let profiles = manager.list().unwrap();
        assert!(!profiles.contains(&"work".to_string()));
    }

    #[test]
    fn test_cannot_delete_active_profile() {
        let (_dir, manager) = create_test_manager();

        let result = manager.delete("default");
        assert!(matches!(result, Err(Error::CannotDeleteActiveProfile(_))));
    }

    #[test]
    fn test_cannot_delete_last_profile() {
        let (_dir, manager) = create_test_manager();

        manager.create("work").unwrap();
        manager.switch("work").unwrap();
        manager.delete("default").unwrap();

        // Now only "work" remains
        let result = manager.delete("work");
        assert!(matches!(result, Err(Error::CannotDeleteActiveProfile(_))));
    }

    #[test]
    fn test_rename_profile() {
        let (_dir, manager) = create_test_manager();

        manager.create("old").unwrap();
        manager.rename("old", "new").unwrap();

        let profiles = manager.list().unwrap();
        assert!(!profiles.contains(&"old".to_string()));
        assert!(profiles.contains(&"new".to_string()));
    }

    #[test]
    fn test_duplicate_profile() {
        let (dir, manager) = create_test_manager();

        manager.create("original").unwrap();

        // Create a file in the original profile
        let original_dir = dir.path().join("profiles").join("original");
        std::fs::write(original_dir.join("test.json"), r#"{"key": "value"}"#).unwrap();

        manager.duplicate("original", "copy").unwrap();

        // Verify copy has the file
        let copy_dir = dir.path().join("profiles").join("copy");
        assert!(copy_dir.join("test.json").exists());
    }

    #[test]
    fn test_profile_already_exists() {
        let (_dir, manager) = create_test_manager();

        manager.create("work").unwrap();
        let result = manager.create("work");
        assert!(matches!(result, Err(Error::ProfileAlreadyExists(_))));
    }

    #[test]
    fn test_event_callback() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let (_dir, manager) = create_test_manager();
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = counter.clone();

        manager.set_on_event(move |_event| {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        manager.create("work").unwrap();
        manager.switch("work").unwrap();
        manager.rename("work", "job").unwrap();

        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn test_callback_paths_recover_from_poisoned_locks() {
        use std::panic::{AssertUnwindSafe, catch_unwind};
        use std::sync::atomic::{AtomicUsize, Ordering};

        let (_dir, manager) = create_test_manager();

        let _ = catch_unwind(AssertUnwindSafe(|| {
            let _guard = manager.on_event.write().unwrap();
            panic!("poison on_event lock");
        }));

        let _ = catch_unwind(AssertUnwindSafe(|| {
            let _guard = manager.on_invalidate.write().unwrap();
            panic!("poison on_invalidate lock");
        }));

        let event_count = Arc::new(AtomicUsize::new(0));
        let event_count_clone = Arc::clone(&event_count);
        manager.set_on_event(move |_event| {
            event_count_clone.fetch_add(1, Ordering::SeqCst);
        });

        let invalidate_count = Arc::new(AtomicUsize::new(0));
        let invalidate_count_clone = Arc::clone(&invalidate_count);
        manager.set_on_invalidate(move || {
            invalidate_count_clone.fetch_add(1, Ordering::SeqCst);
        });

        manager.create("work").unwrap();
        manager.switch("work").unwrap();

        assert_eq!(event_count.load(Ordering::SeqCst), 2);
        assert_eq!(invalidate_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_manifest_persistence() {
        let dir = tempdir().unwrap();

        // Create manager and add profile
        {
            let storage = crate::storage::JsonStorage::compact();
            let manager = ProfileManager::new(dir.path(), "test", storage);
            manager.create("persistent").unwrap();
        }

        // Create new manager instance
        {
            let storage = crate::storage::JsonStorage::compact();
            let manager = ProfileManager::new(dir.path(), "test", storage);
            let profiles = manager.list().unwrap();
            assert!(profiles.contains(&"persistent".to_string()));
        }
    }
}