dot-agent-core 0.5.0

Core library for dot-agent profile management
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
pub mod json_merge;
pub mod metadata;
pub mod snapshot;

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

use crate::error::{DotAgentError, Result};
use crate::platform::Platform;
use crate::profile::{IgnoreConfig, Profile};

// Internal imports
use metadata::{compute_file_hash, compute_hash};

// Re-exports
pub use json_merge::{
    is_mergeable_json, merge_json, merge_json_file, unmerge_json, unmerge_json_file, MergeRecord,
    MergeResult, UnmergeResult,
};
pub use metadata::Metadata;
pub use snapshot::{
    ProfileSnapshotManager, Snapshot, SnapshotDiff, SnapshotManager, SnapshotTrigger,
};

const CLAUDE_MD: &str = "CLAUDE.md";
const CLAUDE_DIR: &str = ".claude";

/// Callback type for file operation progress reporting
pub type FileCallback<'a> = Option<&'a dyn Fn(&str, &str)>;

/// Resolution for a file conflict during install/switch
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Resolution {
    /// Keep the local version, skip profile file
    KeepLocal,
    /// Overwrite with profile version
    OverwriteWithProfile,
    /// Abort the entire operation
    Abort,
}

/// Strategy for resolving file conflicts during install/switch operations
pub trait ConflictResolver {
    /// Called when a local file differs from the profile version.
    /// `relative_path`: path relative to target dir (e.g., "rules/my-rule.md")
    /// `local_content`: current content on disk
    /// `profile_content`: content from the profile being installed
    fn resolve(
        &self,
        relative_path: &Path,
        local_content: &[u8],
        profile_content: &[u8],
    ) -> crate::error::Result<Resolution>;
}

// Directories where files should be prefixed with profile name
const PREFIXED_DIRS: &[&str] = &["agents", "commands", "rules"];
// Directories where subdirectories should be prefixed (skills has SKILL.md inside)
const PREFIXED_SUBDIRS: &[&str] = &["skills"];

/// Generate metadata key with profile prefix.
/// Format: "{profile}:{relative_path}"
fn make_meta_key(profile_name: &str, relative_path: &str) -> String {
    format!("{}:{}", profile_name, relative_path)
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FileStatus {
    Unchanged,
    Modified,
    Added,
    Missing,
}

#[derive(Debug)]
pub struct FileInfo {
    pub relative_path: PathBuf,
    pub status: FileStatus,
}

#[derive(Debug, Default)]
pub struct InstallResult {
    pub installed: usize,
    pub skipped: usize,
    pub conflicts: usize,
    pub merged: usize,
}

#[derive(Debug, Default)]
pub struct SyncBackResult {
    pub synced: usize,
    pub unchanged: usize,
    pub files: Vec<PathBuf>,
}

#[derive(Debug, Default)]
pub struct DiffResult {
    pub unchanged: usize,
    pub modified: usize,
    pub added: usize,
    pub missing: usize,
    pub files: Vec<FileInfo>,
}

/// Options for install/upgrade/remove operations
#[derive(Default)]
pub struct InstallOptions<'a> {
    /// Force overwrite of existing files
    pub force: bool,
    /// Don't actually make changes, just show what would happen
    pub dry_run: bool,
    /// Don't add profile prefix to file names (install/upgrade only)
    pub no_prefix: bool,
    /// Don't merge JSON files (hooks.json, settings.json, etc.)
    pub no_merge: bool,
    /// File ignore configuration
    pub ignore_config: IgnoreConfig,
    /// Callback for file operation progress
    pub on_file: FileCallback<'a>,
    /// Target platform (for filtering unsupported files)
    pub platform: Option<Platform>,
    /// Strategy for resolving file conflicts (None = skip with CONFLICT report)
    pub conflict_resolver: Option<&'a dyn ConflictResolver>,
}

impl std::fmt::Debug for InstallOptions<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InstallOptions")
            .field("force", &self.force)
            .field("dry_run", &self.dry_run)
            .field("no_prefix", &self.no_prefix)
            .field("no_merge", &self.no_merge)
            .field("ignore_config", &self.ignore_config)
            .field("on_file", &self.on_file.is_some())
            .field("platform", &self.platform)
            .field("conflict_resolver", &self.conflict_resolver.is_some())
            .finish()
    }
}

impl<'a> InstallOptions<'a> {
    /// Create new options with defaults
    pub fn new() -> Self {
        Self {
            ignore_config: IgnoreConfig::with_defaults(),
            ..Default::default()
        }
    }

    /// Set force flag
    pub fn force(mut self, force: bool) -> Self {
        self.force = force;
        self
    }

    /// Set dry_run flag
    pub fn dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = dry_run;
        self
    }

    /// Set no_prefix flag
    pub fn no_prefix(mut self, no_prefix: bool) -> Self {
        self.no_prefix = no_prefix;
        self
    }

    /// Set no_merge flag
    pub fn no_merge(mut self, no_merge: bool) -> Self {
        self.no_merge = no_merge;
        self
    }

    /// Set ignore configuration
    pub fn ignore_config(mut self, config: IgnoreConfig) -> Self {
        self.ignore_config = config;
        self
    }

    /// Set file callback
    pub fn on_file(mut self, callback: FileCallback<'a>) -> Self {
        self.on_file = callback;
        self
    }

    /// Set target platform for filtering
    pub fn platform(mut self, platform: Platform) -> Self {
        self.platform = Some(platform);
        self
    }

    /// Set conflict resolver strategy
    pub fn conflict_resolver(mut self, resolver: &'a dyn ConflictResolver) -> Self {
        self.conflict_resolver = Some(resolver);
        self
    }

    /// Check if a path should be included for the target platform
    pub fn should_include_path(&self, path: &Path) -> bool {
        match self.platform {
            Some(platform) => platform.supports_path(path),
            None => true, // No platform filter, include everything
        }
    }
}

pub struct Installer {
    base_dir: PathBuf,
}

impl Installer {
    pub fn new(base_dir: PathBuf) -> Self {
        Self { base_dir }
    }

    /// Get target directory (either project/.claude or global ~/.claude)
    pub fn resolve_target(&self, target: Option<&Path>, global: bool) -> Result<PathBuf> {
        if global {
            let home = dirs::home_dir().ok_or(DotAgentError::HomeNotFound)?;
            Ok(home.join(".claude"))
        } else {
            let base = target
                .map(|p| p.to_path_buf())
                .unwrap_or_else(|| std::env::current_dir().unwrap());

            if !base.exists() {
                return Err(DotAgentError::TargetNotFound { path: base });
            }

            Ok(base.join(CLAUDE_DIR))
        }
    }

    /// Install a profile to target
    pub fn install(
        &self,
        profile: &Profile,
        target: &Path,
        opts: &InstallOptions<'_>,
    ) -> Result<InstallResult> {
        let mut result = InstallResult::default();
        let mut metadata = Metadata::load(target)?.unwrap_or_else(|| Metadata::new(&self.base_dir));

        // Ensure target directory exists
        if !opts.dry_run && !target.exists() {
            fs::create_dir_all(target)?;
        }

        let files = profile.list_files_with_config(&opts.ignore_config)?;

        for relative_path in files {
            // Platform filtering: skip files not supported by target platform
            if !opts.should_include_path(&relative_path) {
                if let Some(f) = opts.on_file {
                    f(
                        "SKIP",
                        &format!("{} (unsupported)", relative_path.display()),
                    );
                }
                result.skipped += 1;
                continue;
            }

            let src = profile.path.join(&relative_path);
            let prefixed_path = if opts.no_prefix {
                relative_path.clone()
            } else {
                prefix_path(&relative_path, &profile.name)
            };
            let dst = target.join(&prefixed_path);
            let relative_str = prefixed_path.to_string_lossy().to_string();

            let is_claude_md = relative_path.to_string_lossy() == CLAUDE_MD;
            let is_mergeable = is_mergeable_json(&relative_path);

            // Handle mergeable JSON files
            if is_mergeable && !opts.no_merge && dst.exists() {
                let merge_result = merge_json_file(&dst, &src, &profile.name)?;

                if !merge_result.changed {
                    if let Some(f) = opts.on_file {
                        f("SKIP", &relative_str);
                    }
                    result.skipped += 1;
                    continue;
                }

                if !opts.dry_run {
                    if let Some(parent) = dst.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::write(&dst, &merge_result.content)?;
                    metadata.add_merged(
                        &profile.name,
                        &relative_str,
                        merge_result.record.added_paths,
                    );
                }

                if let Some(f) = opts.on_file {
                    f("MERGE", &relative_str);
                }
                result.merged += 1;
                continue;
            }

            let src_content = fs::read(&src)?;
            let src_hash = compute_hash(&src_content);

            if dst.exists() {
                let dst_hash = compute_file_hash(&dst)?;

                if src_hash == dst_hash {
                    // Same content - skip
                    if let Some(f) = opts.on_file {
                        f("SKIP", &relative_str);
                    }
                    result.skipped += 1;
                    continue;
                }

                // CLAUDE.md is never overwritten
                if is_claude_md {
                    if let Some(f) = opts.on_file {
                        f("WARN", &relative_str);
                    }
                    result.skipped += 1;
                    continue;
                }

                // Different content - for JSON files with no_merge, this is a conflict
                if !opts.force {
                    if let Some(resolver) = opts.conflict_resolver {
                        let local_content = fs::read(&dst)?;
                        match resolver.resolve(&prefixed_path, &local_content, &src_content)? {
                            Resolution::KeepLocal => {
                                if let Some(f) = opts.on_file {
                                    f("KEEP", &relative_str);
                                }
                                result.skipped += 1;
                                continue;
                            }
                            Resolution::OverwriteWithProfile => {
                                // Fall through to write logic below
                            }
                            Resolution::Abort => {
                                return Err(DotAgentError::Aborted);
                            }
                        }
                    } else {
                        if let Some(f) = opts.on_file {
                            f("CONFLICT", &relative_str);
                        }
                        result.conflicts += 1;
                        continue;
                    }
                }
            }

            // Copy file (or write merged JSON for new files)
            if !opts.dry_run {
                if let Some(parent) = dst.parent() {
                    fs::create_dir_all(parent)?;
                }

                // For new mergeable JSON files, add profile marker
                if is_mergeable && !opts.no_merge {
                    let merge_result = merge_json_file(&dst, &src, &profile.name)?;
                    fs::write(&dst, &merge_result.content)?;
                    metadata.add_merged(
                        &profile.name,
                        &relative_str,
                        merge_result.record.added_paths,
                    );
                } else {
                    fs::write(&dst, &src_content)?;
                    let meta_key = make_meta_key(&profile.name, &relative_str);
                    metadata.add_file(&meta_key, &src_hash);
                }
            }

            if let Some(f) = opts.on_file {
                f("OK", &relative_str);
            }
            result.installed += 1;
        }

        if !opts.dry_run && result.conflicts == 0 {
            metadata.add_profile(&profile.name);
            metadata.save(target)?;
        }

        Ok(result)
    }

    /// Compare profile with installed files
    pub fn diff(
        &self,
        profile: &Profile,
        target: &Path,
        ignore_config: &IgnoreConfig,
    ) -> Result<DiffResult> {
        let mut result = DiffResult::default();

        if !target.exists() {
            // All files are missing
            for relative_path in profile.list_files_with_config(ignore_config)? {
                let prefixed_path = prefix_path(&relative_path, &profile.name);
                result.files.push(FileInfo {
                    relative_path: prefixed_path,
                    status: FileStatus::Missing,
                });
                result.missing += 1;
            }
            return Ok(result);
        }

        let metadata = Metadata::load(target)?;
        let profile_files = profile.list_files_with_config(ignore_config)?;

        // Build set of prefixed paths for comparison
        let prefixed_files: Vec<_> = profile_files
            .iter()
            .map(|p| prefix_path(p, &profile.name))
            .collect();

        // Check profile files against target
        for (idx, relative_path) in profile_files.iter().enumerate() {
            let src = profile.path.join(relative_path);
            let prefixed_path = &prefixed_files[idx];
            let dst = target.join(prefixed_path);

            if !dst.exists() {
                result.files.push(FileInfo {
                    relative_path: prefixed_path.clone(),
                    status: FileStatus::Missing,
                });
                result.missing += 1;
                continue;
            }

            let src_hash = compute_file_hash(&src)?;
            let dst_hash = compute_file_hash(&dst)?;

            if src_hash == dst_hash {
                result.files.push(FileInfo {
                    relative_path: prefixed_path.clone(),
                    status: FileStatus::Unchanged,
                });
                result.unchanged += 1;
            } else {
                result.files.push(FileInfo {
                    relative_path: prefixed_path.clone(),
                    status: FileStatus::Modified,
                });
                result.modified += 1;
            }
        }

        // Check for files in metadata that aren't in profile (user added)
        if let Some(meta) = &metadata {
            for file_path in meta.files.keys() {
                let path = PathBuf::from(file_path);
                if !prefixed_files.contains(&path) {
                    let full_path = target.join(&path);
                    if full_path.exists() {
                        result.files.push(FileInfo {
                            relative_path: path,
                            status: FileStatus::Added,
                        });
                        result.added += 1;
                    }
                }
            }
        }

        result
            .files
            .sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
        Ok(result)
    }

    /// Remove installed profile files
    pub fn remove(
        &self,
        profile: &Profile,
        target: &Path,
        opts: &InstallOptions<'_>,
    ) -> Result<(usize, usize, usize)> {
        if !target.exists() {
            return Ok((0, 0, 0));
        }

        let mut metadata = Metadata::load(target)?.unwrap_or_else(|| Metadata::new(&self.base_dir));
        let diff = self.diff(profile, target, &opts.ignore_config)?;

        // Check for local modifications
        // Skip mergeable JSON files - they are expected to differ due to profile markers
        if !opts.force {
            let modified: Vec<_> = diff
                .files
                .iter()
                .filter(|f| {
                    f.status == FileStatus::Modified
                        && (opts.no_merge || !is_mergeable_json(&f.relative_path))
                })
                .map(|f| f.relative_path.clone())
                .collect();

            if !modified.is_empty() {
                return Err(DotAgentError::LocalModifications { paths: modified });
            }
        }

        let mut removed = 0;
        let mut kept = 0;
        let mut unmerged = 0;

        // First, handle unmerging from JSON files
        if !opts.no_merge {
            if let Some(merged_files) = metadata.get_merged_files(&profile.name).cloned() {
                for (file_path, _json_paths) in merged_files {
                    let dst = target.join(&file_path);
                    if !dst.exists() {
                        continue;
                    }

                    if let Some(result) = unmerge_json_file(&dst, &profile.name)? {
                        if result.changed {
                            if !opts.dry_run {
                                fs::write(&dst, &result.content)?;
                            }
                            if let Some(f) = opts.on_file {
                                f("UNMERGE", &file_path);
                            }
                            unmerged += 1;
                        }
                    }
                }
            }
        }

        for file_info in &diff.files {
            let dst = target.join(&file_info.relative_path);
            let relative_str = file_info.relative_path.to_string_lossy().to_string();

            // Never remove CLAUDE.md
            if relative_str == CLAUDE_MD {
                if let Some(f) = opts.on_file {
                    f("KEEP", &relative_str);
                }
                kept += 1;
                continue;
            }

            // Skip user-added files
            if file_info.status == FileStatus::Added {
                if let Some(f) = opts.on_file {
                    f("KEEP", &relative_str);
                }
                kept += 1;
                continue;
            }

            // Skip missing files
            if file_info.status == FileStatus::Missing {
                continue;
            }

            // Skip merged JSON files (already handled above)
            if !opts.no_merge && is_mergeable_json(&file_info.relative_path) {
                // Only delete if we own this file entirely (not merged)
                if metadata.get_merged(&profile.name, &relative_str).is_some() {
                    continue;
                }
            }

            // Remove file
            if !opts.dry_run && dst.exists() {
                fs::remove_file(&dst)?;
                let meta_key = make_meta_key(&profile.name, &relative_str);
                metadata.remove_file(&meta_key);

                // Remove empty parent directories
                if let Some(parent) = dst.parent() {
                    let _ = remove_empty_dirs(parent, target);
                }
            }

            if let Some(f) = opts.on_file {
                f("DEL", &relative_str);
            }
            removed += 1;
        }

        if !opts.dry_run {
            metadata.remove_profile(&profile.name);
            metadata.remove_merged(&profile.name);
            if metadata.installed.profiles.is_empty()
                && metadata.files.is_empty()
                && metadata.merged.is_empty()
            {
                // Remove metadata file if no profiles left
                let meta_path = target.join(".dot-agent-meta.toml");
                let _ = fs::remove_file(meta_path);
            } else {
                metadata.save(target)?;
            }
        }

        Ok((removed, kept, unmerged))
    }

    /// Upgrade profile files
    pub fn upgrade(
        &self,
        profile: &Profile,
        target: &Path,
        opts: &InstallOptions<'_>,
    ) -> Result<(usize, usize, usize, usize)> {
        // updated, new, skipped, unchanged
        if !target.exists() {
            // Just install everything
            let result = self.install(profile, target, opts)?;
            return Ok((0, result.installed, 0, 0));
        }

        let mut metadata = Metadata::load(target)?.unwrap_or_else(|| Metadata::new(&self.base_dir));
        let mut updated = 0;
        let mut new = 0;
        let mut skipped = 0;
        let mut unchanged = 0;

        let files = profile.list_files_with_config(&opts.ignore_config)?;

        for relative_path in files {
            let src = profile.path.join(&relative_path);
            let prefixed_path = if opts.no_prefix {
                relative_path.clone()
            } else {
                prefix_path(&relative_path, &profile.name)
            };
            let dst = target.join(&prefixed_path);
            let relative_str = prefixed_path.to_string_lossy().to_string();
            let is_claude_md = relative_path.to_string_lossy() == CLAUDE_MD;

            let src_content = fs::read(&src)?;
            let src_hash = compute_hash(&src_content);

            let meta_key = make_meta_key(&profile.name, &relative_str);

            if !dst.exists() {
                // New file
                if !opts.dry_run {
                    if let Some(parent) = dst.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::write(&dst, &src_content)?;
                    metadata.add_file(&meta_key, &src_hash);
                }
                if let Some(f) = opts.on_file {
                    f("NEW", &relative_str);
                }
                new += 1;
                continue;
            }

            let dst_hash = compute_file_hash(&dst)?;

            if src_hash == dst_hash {
                if let Some(f) = opts.on_file {
                    f("OK", &relative_str);
                }
                unchanged += 1;
                continue;
            }

            // CLAUDE.md is never overwritten
            if is_claude_md {
                if let Some(f) = opts.on_file {
                    f("WARN", &relative_str);
                }
                skipped += 1;
                continue;
            }

            // Check if file was modified locally
            let original_hash = metadata.get_file_hash(&meta_key);
            let locally_modified = original_hash.map(|h| h != &dst_hash).unwrap_or(false);

            if locally_modified && !opts.force {
                if let Some(f) = opts.on_file {
                    f("SKIP", &relative_str);
                }
                skipped += 1;
                continue;
            }

            // Update file
            if !opts.dry_run {
                fs::write(&dst, &src_content)?;
                metadata.add_file(&meta_key, &src_hash);
            }
            if let Some(f) = opts.on_file {
                f("UPDATE", &relative_str);
            }
            updated += 1;
        }

        if !opts.dry_run {
            metadata.add_profile(&profile.name);
            metadata.save(target)?;
        }

        Ok((updated, new, skipped, unchanged))
    }

    /// Sync modified installed files back to the profile directory.
    ///
    /// Detects files that were modified locally (compared to the profile),
    /// and copies them back into the profile, removing the profile-name prefix.
    pub fn sync_back(
        &self,
        profile: &Profile,
        target: &Path,
        ignore_config: &IgnoreConfig,
        dry_run: bool,
        on_file: FileCallback<'_>,
    ) -> Result<SyncBackResult> {
        let mut result = SyncBackResult::default();
        let profile_files = profile.list_files_with_config(ignore_config)?;

        for original_path in &profile_files {
            let prefixed_path = prefix_path(original_path, &profile.name);
            let src_profile = profile.path.join(original_path);
            let dst_installed = target.join(&prefixed_path);

            if !dst_installed.exists() {
                continue;
            }

            let profile_hash = compute_file_hash(&src_profile)?;
            let installed_hash = compute_file_hash(&dst_installed)?;

            if profile_hash == installed_hash {
                result.unchanged += 1;
                continue;
            }

            // File was modified locally — copy back to profile
            if !dry_run {
                if let Some(parent) = src_profile.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::copy(&dst_installed, &src_profile)?;
            }

            if let Some(f) = on_file {
                f("SYNC", &original_path.to_string_lossy());
            }
            result.synced += 1;
            result.files.push(original_path.clone());
        }

        Ok(result)
    }
}

fn remove_empty_dirs(dir: &Path, root: &Path) -> std::io::Result<()> {
    if dir == root {
        return Ok(());
    }

    if dir.is_dir() && fs::read_dir(dir)?.next().is_none() {
        fs::remove_dir(dir)?;
        if let Some(parent) = dir.parent() {
            remove_empty_dirs(parent, root)?;
        }
    }

    Ok(())
}

/// Transform relative path to add profile prefix where needed
/// Examples:
///   agents/code-reviewer.md → agents/{profile}-code-reviewer.md
///   skills/my-skill/SKILL.md → skills/{profile}-my-skill/SKILL.md
///   rules/testing.md → rules/{profile}-testing.md
///   commands/profile:cmd.md → commands/profile:cmd.md (already prefixed)
///   CLAUDE.md → CLAUDE.md (no change)
fn prefix_path(relative_path: &Path, profile_name: &str) -> PathBuf {
    let components: Vec<_> = relative_path.components().collect();

    if components.is_empty() {
        return relative_path.to_path_buf();
    }

    // Get first component (top-level directory)
    let first = components[0].as_os_str().to_string_lossy();

    // Check if this is a directory where we prefix files directly
    if PREFIXED_DIRS.contains(&first.as_ref()) && components.len() >= 2 {
        let filename = components[1].as_os_str().to_string_lossy();

        // Skip if already prefixed (contains ':' or starts with profile name)
        if filename.contains(':') || filename.starts_with(&format!("{}-", profile_name)) {
            return relative_path.to_path_buf();
        }

        // agents/code-reviewer.md → agents/{profile}-code-reviewer.md
        let mut result = PathBuf::from(components[0].as_os_str());
        result.push(format!("{}-{}", profile_name, filename));

        // Add remaining components if any
        for comp in &components[2..] {
            result.push(comp.as_os_str());
        }
        return result;
    }

    // Check if this is a directory where we prefix subdirectories
    if PREFIXED_SUBDIRS.contains(&first.as_ref()) && components.len() >= 2 {
        let subdir = components[1].as_os_str().to_string_lossy();

        // Skip if already prefixed
        if subdir.contains(':') || subdir.starts_with(&format!("{}-", profile_name)) {
            return relative_path.to_path_buf();
        }

        // skills/my-skill/SKILL.md → skills/{profile}-my-skill/SKILL.md
        let mut result = PathBuf::from(components[0].as_os_str());
        result.push(format!("{}-{}", profile_name, subdir));

        // Add remaining components
        for comp in &components[2..] {
            result.push(comp.as_os_str());
        }
        return result;
    }

    // No transformation needed
    relative_path.to_path_buf()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::profile::Profile;
    use std::fs;
    use tempfile::TempDir;

    /// A mock ConflictResolver that always returns a fixed Resolution.
    struct MockResolver {
        resolution: Resolution,
    }

    impl ConflictResolver for MockResolver {
        fn resolve(&self, _: &Path, _: &[u8], _: &[u8]) -> Result<Resolution> {
            Ok(self.resolution)
        }
    }

    /// Build a minimal Profile pointing at `profile_dir` with `name`.
    fn make_profile(name: &str, profile_dir: &Path) -> Profile {
        Profile::new(name.to_string(), profile_dir.to_path_buf())
    }

    /// Write `content` to `dir/filename`, creating parent dirs as needed.
    fn write_file(dir: &Path, filename: &str, content: &[u8]) {
        let path = dir.join(filename);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, content).unwrap();
    }

    /// Create an Installer whose base_dir is `base`.
    fn make_installer(base: &Path) -> Installer {
        Installer::new(base.to_path_buf())
    }

    // -----------------------------------------------------------------------
    // Test: ConflictResolver::KeepLocal — existing file must be unchanged
    // -----------------------------------------------------------------------
    #[test]
    fn test_install_with_conflict_resolver_keep_local() {
        let base = TempDir::new().unwrap();
        let profile_dir = base.path().join("profile");
        let target_dir = base.path().join("target");

        // Profile has "rules/test-rule.md" with profile content
        write_file(&profile_dir, "rules/test-rule.md", b"profile content");

        // Target already has the file with different (local) content
        fs::create_dir_all(&target_dir).unwrap();
        write_file(&target_dir, "rules/test-rule.md", b"local content");

        let installer = make_installer(base.path());
        let profile = make_profile("test", &profile_dir);
        let resolver = MockResolver {
            resolution: Resolution::KeepLocal,
        };
        let opts = InstallOptions::new()
            .no_prefix(true)
            .conflict_resolver(&resolver);

        let result = installer.install(&profile, &target_dir, &opts).unwrap();

        // File was kept (skipped), not overwritten
        assert_eq!(result.skipped, 1);
        assert_eq!(result.installed, 0);
        let content = fs::read(target_dir.join("rules/test-rule.md")).unwrap();
        assert_eq!(content, b"local content");
    }

    // -----------------------------------------------------------------------
    // Test: ConflictResolver::OverwriteWithProfile — file must be replaced
    // -----------------------------------------------------------------------
    #[test]
    fn test_install_with_conflict_resolver_overwrite() {
        let base = TempDir::new().unwrap();
        let profile_dir = base.path().join("profile");
        let target_dir = base.path().join("target");

        write_file(&profile_dir, "rules/test-rule.md", b"profile content");

        fs::create_dir_all(&target_dir).unwrap();
        write_file(&target_dir, "rules/test-rule.md", b"local content");

        let installer = make_installer(base.path());
        let profile = make_profile("test", &profile_dir);
        let resolver = MockResolver {
            resolution: Resolution::OverwriteWithProfile,
        };
        let opts = InstallOptions::new()
            .no_prefix(true)
            .conflict_resolver(&resolver);

        let result = installer.install(&profile, &target_dir, &opts).unwrap();

        // File was overwritten with profile content
        assert_eq!(result.installed, 1);
        assert_eq!(result.skipped, 0);
        let content = fs::read(target_dir.join("rules/test-rule.md")).unwrap();
        assert_eq!(content, b"profile content");
    }

    // -----------------------------------------------------------------------
    // Test: ConflictResolver::Abort — operation must return DotAgentError::Aborted
    // -----------------------------------------------------------------------
    #[test]
    fn test_install_with_conflict_resolver_abort() {
        let base = TempDir::new().unwrap();
        let profile_dir = base.path().join("profile");
        let target_dir = base.path().join("target");

        write_file(&profile_dir, "rules/test-rule.md", b"profile content");

        fs::create_dir_all(&target_dir).unwrap();
        write_file(&target_dir, "rules/test-rule.md", b"local content");

        let installer = make_installer(base.path());
        let profile = make_profile("test", &profile_dir);
        let resolver = MockResolver {
            resolution: Resolution::Abort,
        };
        let opts = InstallOptions::new()
            .no_prefix(true)
            .conflict_resolver(&resolver);

        let err = installer.install(&profile, &target_dir, &opts).unwrap_err();

        assert!(
            matches!(err, DotAgentError::Aborted),
            "expected DotAgentError::Aborted, got: {err:?}"
        );
    }

    // -----------------------------------------------------------------------
    // Test: No resolver — conflict is reported and file is skipped (existing behaviour)
    // -----------------------------------------------------------------------
    #[test]
    fn test_install_without_resolver_preserves_existing_behavior() {
        let base = TempDir::new().unwrap();
        let profile_dir = base.path().join("profile");
        let target_dir = base.path().join("target");

        write_file(&profile_dir, "rules/test-rule.md", b"profile content");

        fs::create_dir_all(&target_dir).unwrap();
        write_file(&target_dir, "rules/test-rule.md", b"local content");

        let installer = make_installer(base.path());
        let profile = make_profile("test", &profile_dir);
        // No conflict_resolver set
        let opts = InstallOptions::new().no_prefix(true);

        let result = installer.install(&profile, &target_dir, &opts).unwrap();

        // Existing behaviour: conflicting file is counted as conflict and skipped
        assert_eq!(result.conflicts, 1);
        assert_eq!(result.installed, 0);
        // Local file must remain unchanged
        let content = fs::read(target_dir.join("rules/test-rule.md")).unwrap();
        assert_eq!(content, b"local content");
    }

    // -----------------------------------------------------------------------
    // Tests: sync_back
    // -----------------------------------------------------------------------
    #[test]
    fn test_sync_back_modified_files() {
        let base = TempDir::new().unwrap();
        let profile_dir = base.path().join("profile");
        let target_dir = base.path().join("target");

        write_file(&profile_dir, "rules/my-rule.md", b"original");

        let installer = make_installer(base.path());
        let profile = make_profile("prof", &profile_dir);
        let opts = InstallOptions::new();
        installer.install(&profile, &target_dir, &opts).unwrap();

        // User edits the installed (prefixed) file
        write_file(&target_dir, "rules/prof-my-rule.md", b"user edited");

        let ignore_config = IgnoreConfig::with_defaults();
        let result = installer
            .sync_back(&profile, &target_dir, &ignore_config, false, None)
            .unwrap();

        assert_eq!(result.synced, 1);
        let content = fs::read(profile_dir.join("rules/my-rule.md")).unwrap();
        assert_eq!(content, b"user edited");
    }

    #[test]
    fn test_sync_back_unchanged_files() {
        let base = TempDir::new().unwrap();
        let profile_dir = base.path().join("profile");
        let target_dir = base.path().join("target");

        write_file(&profile_dir, "rules/my-rule.md", b"same content");

        let installer = make_installer(base.path());
        let profile = make_profile("prof", &profile_dir);
        let opts = InstallOptions::new();
        installer.install(&profile, &target_dir, &opts).unwrap();

        let ignore_config = IgnoreConfig::with_defaults();
        let result = installer
            .sync_back(&profile, &target_dir, &ignore_config, false, None)
            .unwrap();

        assert_eq!(result.synced, 0);
    }

    #[test]
    fn test_sync_back_dry_run() {
        let base = TempDir::new().unwrap();
        let profile_dir = base.path().join("profile");
        let target_dir = base.path().join("target");

        write_file(&profile_dir, "rules/my-rule.md", b"original");

        let installer = make_installer(base.path());
        let profile = make_profile("prof", &profile_dir);
        let opts = InstallOptions::new();
        installer.install(&profile, &target_dir, &opts).unwrap();

        write_file(&target_dir, "rules/prof-my-rule.md", b"user edited");

        let ignore_config = IgnoreConfig::with_defaults();
        let result = installer
            .sync_back(&profile, &target_dir, &ignore_config, true, None)
            .unwrap();

        assert_eq!(result.synced, 1);
        // Profile file should remain original (dry run)
        let content = fs::read(profile_dir.join("rules/my-rule.md")).unwrap();
        assert_eq!(content, b"original");
    }
}