oximedia-dedup 0.1.8

Media deduplication and duplicate detection for OxiMedia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! Merge strategies for resolving duplicate file groups.
//!
//! When duplicates are found, this module decides which files to keep and
//! which to remove (or link). Strategies include:
//! - **`KeepNewest`**: keep the file with the latest modification time
//! - **`KeepOldest`**: keep the earliest file
//! - **`KeepLargest`**: keep the largest file (e.g. highest-quality encode)
//! - **`KeepSmallest`**: keep the smallest (e.g. most efficient encode)
//! - **`KeepByPath`**: keep the file in a preferred directory hierarchy
//! - **`Custom`**: user-supplied scoring function

#![allow(dead_code)]
#![allow(clippy::cast_precision_loss)]

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

// ---------------------------------------------------------------------------
// FileCandidate
// ---------------------------------------------------------------------------

/// Metadata about a duplicate file candidate.
#[derive(Debug, Clone)]
pub struct FileCandidate {
    /// Path to the file.
    pub path: PathBuf,
    /// File size in bytes.
    pub size: u64,
    /// Modification timestamp (Unix seconds).
    pub modified: u64,
    /// Creation timestamp (Unix seconds).
    pub created: u64,
    /// Optional quality score (0.0 - 1.0).
    pub quality_score: Option<f64>,
}

impl FileCandidate {
    /// Create a new candidate.
    pub fn new(path: PathBuf, size: u64, modified: u64, created: u64) -> Self {
        Self {
            path,
            size,
            modified,
            created,
            quality_score: None,
        }
    }

    /// Builder: set an optional quality score.
    #[must_use]
    pub fn with_quality(mut self, score: f64) -> Self {
        self.quality_score = Some(score);
        self
    }
}

// ---------------------------------------------------------------------------
// MergeStrategy
// ---------------------------------------------------------------------------

/// Strategy for choosing which duplicate to keep.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeStrategy {
    /// Keep the most recently modified file.
    KeepNewest,
    /// Keep the oldest modified file.
    KeepOldest,
    /// Keep the largest file.
    KeepLargest,
    /// Keep the smallest file.
    KeepSmallest,
    /// Keep the file with the highest quality score.
    KeepHighestQuality,
}

impl MergeStrategy {
    /// Return a human-readable label.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::KeepNewest => "keep-newest",
            Self::KeepOldest => "keep-oldest",
            Self::KeepLargest => "keep-largest",
            Self::KeepSmallest => "keep-smallest",
            Self::KeepHighestQuality => "keep-highest-quality",
        }
    }
}

// ---------------------------------------------------------------------------
// MergeAction
// ---------------------------------------------------------------------------

/// Action to perform on a file after merge resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergeAction {
    /// Keep this file as the canonical copy.
    Keep,
    /// Remove this file.
    Remove,
    /// Replace this file with a symlink to the kept file.
    Symlink {
        /// Target of the symlink (the kept file).
        target: PathBuf,
    },
    /// Replace this file with a hardlink to the kept file.
    Hardlink {
        /// Target of the hardlink (the kept file).
        target: PathBuf,
    },
}

impl MergeAction {
    /// Return `true` if this action keeps the file.
    #[must_use]
    pub fn is_keep(&self) -> bool {
        matches!(self, Self::Keep)
    }

    /// Return `true` if this action removes the file.
    #[must_use]
    pub fn is_remove(&self) -> bool {
        matches!(self, Self::Remove)
    }
}

// ---------------------------------------------------------------------------
// MergeResolution
// ---------------------------------------------------------------------------

/// A single file's resolution after merge.
#[derive(Debug, Clone)]
pub struct FileResolution {
    /// The candidate file.
    pub candidate: FileCandidate,
    /// The action to take.
    pub action: MergeAction,
}

/// The full resolution of a duplicate group.
#[derive(Debug, Clone)]
pub struct MergeResolution {
    /// Per-file resolutions.
    pub files: Vec<FileResolution>,
    /// The strategy used.
    pub strategy: MergeStrategy,
    /// Estimated bytes recoverable by removing duplicates.
    pub bytes_saved: u64,
}

// ---------------------------------------------------------------------------
// Resolver
// ---------------------------------------------------------------------------

/// Resolve a group of duplicate candidates using a strategy.
///
/// Returns a [`MergeResolution`] specifying which file to keep and what
/// to do with the rest.
pub fn resolve(
    candidates: &[FileCandidate],
    strategy: MergeStrategy,
    link_mode: LinkMode,
) -> MergeResolution {
    if candidates.is_empty() {
        return MergeResolution {
            files: Vec::new(),
            strategy,
            bytes_saved: 0,
        };
    }

    let winner_idx = pick_winner(candidates, strategy);
    let winner_path = candidates[winner_idx].path.clone();
    let mut bytes_saved = 0u64;

    let files = candidates
        .iter()
        .enumerate()
        .map(|(i, c)| {
            if i == winner_idx {
                FileResolution {
                    candidate: c.clone(),
                    action: MergeAction::Keep,
                }
            } else {
                bytes_saved += c.size;
                let action = match link_mode {
                    LinkMode::Delete => MergeAction::Remove,
                    LinkMode::Symlink => MergeAction::Symlink {
                        target: winner_path.clone(),
                    },
                    LinkMode::Hardlink => MergeAction::Hardlink {
                        target: winner_path.clone(),
                    },
                };
                FileResolution {
                    candidate: c.clone(),
                    action,
                }
            }
        })
        .collect();

    MergeResolution {
        files,
        strategy,
        bytes_saved,
    }
}

/// How to handle non-winner files.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkMode {
    /// Delete non-winner files.
    Delete,
    /// Replace with symlinks.
    Symlink,
    /// Replace with hardlinks.
    Hardlink,
}

/// Pick the winner index based on strategy.
fn pick_winner(candidates: &[FileCandidate], strategy: MergeStrategy) -> usize {
    match strategy {
        MergeStrategy::KeepNewest => candidates
            .iter()
            .enumerate()
            .max_by_key(|(_, c)| c.modified)
            .map(|(i, _)| i)
            .unwrap_or(0),
        MergeStrategy::KeepOldest => candidates
            .iter()
            .enumerate()
            .min_by_key(|(_, c)| c.modified)
            .map(|(i, _)| i)
            .unwrap_or(0),
        MergeStrategy::KeepLargest => candidates
            .iter()
            .enumerate()
            .max_by_key(|(_, c)| c.size)
            .map(|(i, _)| i)
            .unwrap_or(0),
        MergeStrategy::KeepSmallest => candidates
            .iter()
            .enumerate()
            .min_by_key(|(_, c)| c.size)
            .map(|(i, _)| i)
            .unwrap_or(0),
        MergeStrategy::KeepHighestQuality => candidates
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| {
                let qa = a.quality_score.unwrap_or(0.0);
                let qb = b.quality_score.unwrap_or(0.0);
                qa.partial_cmp(&qb).unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|(i, _)| i)
            .unwrap_or(0),
    }
}

/// Check if a path is under a preferred directory prefix.
#[must_use]
pub fn is_preferred_path(path: &Path, preferred_prefix: &Path) -> bool {
    path.starts_with(preferred_prefix)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn candidates() -> Vec<FileCandidate> {
        vec![
            FileCandidate::new(PathBuf::from("/a.mp4"), 1000, 100, 90),
            FileCandidate::new(PathBuf::from("/b.mp4"), 2000, 200, 80),
            FileCandidate::new(PathBuf::from("/c.mp4"), 500, 50, 100),
        ]
    }

    #[test]
    fn test_keep_newest() {
        let res = resolve(&candidates(), MergeStrategy::KeepNewest, LinkMode::Delete);
        assert_eq!(res.files.len(), 3);
        assert!(res.files[1].action.is_keep()); // /b.mp4 has modified=200
    }

    #[test]
    fn test_keep_oldest() {
        let res = resolve(&candidates(), MergeStrategy::KeepOldest, LinkMode::Delete);
        assert!(res.files[2].action.is_keep()); // /c.mp4 has modified=50
    }

    #[test]
    fn test_keep_largest() {
        let res = resolve(&candidates(), MergeStrategy::KeepLargest, LinkMode::Delete);
        assert!(res.files[1].action.is_keep()); // /b.mp4 has size=2000
    }

    #[test]
    fn test_keep_smallest() {
        let res = resolve(&candidates(), MergeStrategy::KeepSmallest, LinkMode::Delete);
        assert!(res.files[2].action.is_keep()); // /c.mp4 has size=500
    }

    #[test]
    fn test_keep_highest_quality() {
        let cs = vec![
            FileCandidate::new(PathBuf::from("/a.mp4"), 100, 10, 10).with_quality(0.6),
            FileCandidate::new(PathBuf::from("/b.mp4"), 100, 10, 10).with_quality(0.9),
            FileCandidate::new(PathBuf::from("/c.mp4"), 100, 10, 10).with_quality(0.3),
        ];
        let res = resolve(&cs, MergeStrategy::KeepHighestQuality, LinkMode::Delete);
        assert!(res.files[1].action.is_keep()); // 0.9 is highest
    }

    #[test]
    fn test_bytes_saved() {
        let res = resolve(&candidates(), MergeStrategy::KeepLargest, LinkMode::Delete);
        // keep /b.mp4 (2000), remove /a.mp4 (1000) and /c.mp4 (500) => saved 1500
        assert_eq!(res.bytes_saved, 1500);
    }

    #[test]
    fn test_symlink_mode() {
        let res = resolve(&candidates(), MergeStrategy::KeepNewest, LinkMode::Symlink);
        for f in &res.files {
            if !f.action.is_keep() {
                match &f.action {
                    MergeAction::Symlink { target } => {
                        assert_eq!(target, &PathBuf::from("/b.mp4"));
                    }
                    _ => panic!("expected symlink action"),
                }
            }
        }
    }

    #[test]
    fn test_hardlink_mode() {
        let res = resolve(&candidates(), MergeStrategy::KeepNewest, LinkMode::Hardlink);
        for f in &res.files {
            if !f.action.is_keep() {
                match &f.action {
                    MergeAction::Hardlink { target } => {
                        assert_eq!(target, &PathBuf::from("/b.mp4"));
                    }
                    _ => panic!("expected hardlink action"),
                }
            }
        }
    }

    #[test]
    fn test_empty_candidates() {
        let res = resolve(&[], MergeStrategy::KeepNewest, LinkMode::Delete);
        assert!(res.files.is_empty());
        assert_eq!(res.bytes_saved, 0);
    }

    #[test]
    fn test_single_candidate() {
        let cs = vec![FileCandidate::new(PathBuf::from("/only.mp4"), 999, 10, 10)];
        let res = resolve(&cs, MergeStrategy::KeepNewest, LinkMode::Delete);
        assert_eq!(res.files.len(), 1);
        assert!(res.files[0].action.is_keep());
        assert_eq!(res.bytes_saved, 0);
    }

    #[test]
    fn test_is_preferred_path() {
        assert!(is_preferred_path(
            Path::new("/archive/media/a.mp4"),
            Path::new("/archive")
        ));
        assert!(!is_preferred_path(
            Path::new("/other/a.mp4"),
            Path::new("/archive")
        ));
    }

    #[test]
    fn test_strategy_label() {
        assert_eq!(MergeStrategy::KeepNewest.label(), "keep-newest");
        assert_eq!(MergeStrategy::KeepSmallest.label(), "keep-smallest");
    }
}

// ---------------------------------------------------------------------------
// Real FS Executor — MergeExecutor
// ---------------------------------------------------------------------------

/// The concrete action that was applied (or would be applied in dry-run) to a
/// duplicate file during [`MergeExecutor::apply`] or [`MergeExecutor::dry_run`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppliedAction {
    /// The file was replaced with a symbolic link pointing to `target`.
    Symlinked {
        /// Canonical (primary) file the symlink points to.
        target: PathBuf,
    },
    /// The file was replaced with a hard link pointing to the same inode as `target`.
    Hardlinked {
        /// Canonical (primary) file that shares the inode.
        target: PathBuf,
    },
    /// The file was deleted.
    Deleted,
    /// The file was left untouched (it is the primary / canonical copy).
    Kept,
    /// The action was not performed; `reason` explains why.
    Skipped(String),
}

/// A per-file action record returned by [`MergeExecutor`].
#[derive(Debug, Clone)]
pub struct MergeReport {
    /// The file that was chosen as the canonical copy to retain.
    pub primary_path: PathBuf,
    /// Actions taken (or planned, in dry-run mode) for each duplicate file.
    ///
    /// The first element of each tuple is the duplicate path; the second is
    /// what was (or would be) done to it.
    pub actions: Vec<(PathBuf, AppliedAction)>,
}

impl MergeReport {
    /// Returns the number of files that were actually modified (not Kept/Skipped).
    #[must_use]
    pub fn modified_count(&self) -> usize {
        self.actions
            .iter()
            .filter(|(_, a)| !matches!(a, AppliedAction::Kept | AppliedAction::Skipped(_)))
            .count()
    }

    /// Returns `true` if any action was skipped.
    #[must_use]
    pub fn has_skipped(&self) -> bool {
        self.actions
            .iter()
            .any(|(_, a)| matches!(a, AppliedAction::Skipped(_)))
    }
}

/// Executes real filesystem mutations (symlink / hardlink / delete) for a set
/// of duplicate files.
///
/// ```rust
/// use oximedia_dedup::merge_strategy::{MergeExecutor, LinkMode};
/// use std::path::PathBuf;
///
/// // Build an executor that replaces duplicates with hard links.
/// let executor = MergeExecutor::new(LinkMode::Hardlink);
///
/// // Dry-run: returns what *would* happen without touching the filesystem.
/// let primary = PathBuf::from("/media/archive/original.mp4");
/// let dups = vec![PathBuf::from("/media/inbox/copy.mp4")];
/// let report = executor.dry_run(&primary, &dups);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct MergeExecutor {
    link_mode: LinkMode,
}

impl MergeExecutor {
    /// Create a new executor with the given [`LinkMode`].
    #[must_use]
    pub fn new(link_mode: LinkMode) -> Self {
        Self { link_mode }
    }

    /// Apply the configured action to every path in `duplicates`, treating
    /// `primary_path` as the canonical file to keep.
    ///
    /// The primary path itself is silently skipped if it appears in
    /// `duplicates` (path equality check using [`Path::canonicalize`] if both
    /// exist, falling back to byte comparison otherwise).
    ///
    /// # Errors
    ///
    /// Returns [`crate::DedupError::Io`] for unrecoverable I/O failures.
    /// Cross-device hardlink failures are NOT errors — they produce
    /// [`AppliedAction::Skipped`] instead.
    pub fn apply(
        &self,
        primary_path: &Path,
        duplicates: &[PathBuf],
    ) -> Result<MergeReport, crate::DedupError> {
        self.execute(primary_path, duplicates, false)
    }

    /// Preview what [`apply`](Self::apply) would do without touching the
    /// filesystem.
    ///
    /// The returned [`MergeReport`] describes the intended actions.  No files
    /// are created, removed, or modified.
    ///
    /// # Errors
    ///
    /// Currently infallible (always returns `Ok`), but uses the same error
    /// type as [`apply`](Self::apply) for API symmetry.
    pub fn dry_run(
        &self,
        primary_path: &Path,
        duplicates: &[PathBuf],
    ) -> Result<MergeReport, crate::DedupError> {
        self.execute(primary_path, duplicates, true)
    }

    /// Execute a pre-computed [`MergeResolution`] produced by [`MergeResolver`].
    ///
    /// This bridges the selection phase (which file to keep) with the
    /// execution phase (actually modifying the filesystem).
    ///
    /// # Errors
    ///
    /// Returns [`crate::DedupError::Io`] for unrecoverable I/O failures.
    pub fn apply_resolution(
        &self,
        resolution: &MergeResolution,
    ) -> Result<MergeReport, crate::DedupError> {
        // The primary is the one file whose action is Keep.
        let primary = resolution
            .files
            .iter()
            .find(|f| f.action.is_keep())
            .map(|f| f.candidate.path.clone());

        let Some(primary_path) = primary else {
            // Degenerate resolution (e.g., empty group) — nothing to do.
            return Ok(MergeReport {
                primary_path: PathBuf::new(),
                actions: Vec::new(),
            });
        };

        let duplicates: Vec<PathBuf> = resolution
            .files
            .iter()
            .filter(|f| !f.action.is_keep())
            .map(|f| f.candidate.path.clone())
            .collect();

        self.execute(&primary_path, &duplicates, false)
    }

    // --- internal ---

    fn execute(
        &self,
        primary_path: &Path,
        duplicates: &[PathBuf],
        dry: bool,
    ) -> Result<MergeReport, crate::DedupError> {
        let mut report = MergeReport {
            primary_path: primary_path.to_path_buf(),
            actions: Vec::new(),
        };

        for dup in duplicates {
            // Skip if `dup` and `primary_path` refer to the same file.
            if Self::same_path(primary_path, dup) {
                report.actions.push((dup.clone(), AppliedAction::Kept));
                continue;
            }

            let action = self.apply_to_one(primary_path, dup, dry)?;
            report.actions.push((dup.clone(), action));
        }

        Ok(report)
    }

    fn apply_to_one(
        &self,
        primary: &Path,
        dup: &Path,
        dry: bool,
    ) -> Result<AppliedAction, crate::DedupError> {
        match self.link_mode {
            LinkMode::Symlink => {
                if dry {
                    return Ok(AppliedAction::Symlinked {
                        target: primary.to_path_buf(),
                    });
                }
                // Remove the duplicate first.
                if dup.exists() || dup.symlink_metadata().is_ok() {
                    std::fs::remove_file(dup)?;
                }
                create_symlink(primary, dup)?;
                Ok(AppliedAction::Symlinked {
                    target: primary.to_path_buf(),
                })
            }

            LinkMode::Hardlink => {
                if dry {
                    return Ok(AppliedAction::Hardlinked {
                        target: primary.to_path_buf(),
                    });
                }
                if !primary.exists() {
                    return Ok(AppliedAction::Skipped(format!(
                        "primary does not exist: {}",
                        primary.display()
                    )));
                }
                // Remove the duplicate first.
                if dup.exists() || dup.symlink_metadata().is_ok() {
                    std::fs::remove_file(dup)?;
                }
                // hard_link fails with EXDEV on cross-device links — treat as
                // a graceful skip rather than a hard error.
                match std::fs::hard_link(primary, dup) {
                    Ok(()) => Ok(AppliedAction::Hardlinked {
                        target: primary.to_path_buf(),
                    }),
                    Err(e) => Ok(AppliedAction::Skipped(format!(
                        "hardlink failed (cross-device or permission?): {e}"
                    ))),
                }
            }

            LinkMode::Delete => {
                if dry {
                    return Ok(AppliedAction::Deleted);
                }
                if !primary.exists() {
                    return Ok(AppliedAction::Skipped(
                        "primary does not exist — refusing to delete duplicate".into(),
                    ));
                }
                std::fs::remove_file(dup)?;
                Ok(AppliedAction::Deleted)
            }
        }
    }

    /// Compare two paths for identity.  Tries canonicalization first (handles
    /// symlinks and `..` components); falls back to byte comparison.
    fn same_path(a: &Path, b: &Path) -> bool {
        if a == b {
            return true;
        }
        let ca = std::fs::canonicalize(a);
        let cb = std::fs::canonicalize(b);
        match (ca, cb) {
            (Ok(ca), Ok(cb)) => ca == cb,
            _ => false,
        }
    }
}

/// Platform-specific symlink creation.
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(target, link)
    }
    #[cfg(windows)]
    {
        std::os::windows::fs::symlink_file(target, link)
    }
    #[cfg(not(any(unix, windows)))]
    {
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            format!(
                "symlinks not supported on this platform (target={}, link={})",
                target.display(),
                link.display()
            ),
        ))
    }
}

// ---------------------------------------------------------------------------
// MergeExecutor tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod executor_tests {
    use super::*;
    use std::env::temp_dir;
    use std::fs;

    /// Create `n` temporary files under a unique subdirectory and return their
    /// paths.  Each file contains distinct content to avoid accidental sharing.
    fn make_temp_files(n: usize) -> Vec<PathBuf> {
        let unique = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .subsec_nanos();
        let base = temp_dir().join(format!("oxidedup_exec_{unique}_{n}"));
        fs::create_dir_all(&base).expect("create test dir");
        (0..n)
            .map(|i| {
                let p = base.join(format!("file_{i}.bin"));
                // Content must be non-trivial so files are not accidentally
                // sharing blocks at the filesystem level.
                let content = format!("oximedia-dedup-test-content-{i}-{unique}").repeat(100);
                fs::write(&p, content.as_bytes()).expect("write test file");
                p
            })
            .collect()
    }

    #[test]
    fn test_symlink_strategy_creates_symlinks() {
        let files = make_temp_files(3);
        let executor = MergeExecutor::new(LinkMode::Symlink);
        let report = executor
            .apply(&files[0], &files[1..])
            .expect("apply symlink");

        assert_eq!(report.primary_path, files[0]);
        assert_eq!(report.actions.len(), 2);

        for (path, action) in &report.actions {
            assert!(
                path.symlink_metadata()
                    .map(|m| m.file_type().is_symlink())
                    .unwrap_or(false),
                "expected symlink at {path:?}"
            );
            match action {
                AppliedAction::Symlinked { target } => {
                    assert_eq!(target, &files[0]);
                }
                other => panic!("unexpected action: {other:?}"),
            }
        }
    }

    #[test]
    fn test_hardlink_strategy_creates_hardlinks() {
        let files = make_temp_files(2);
        let executor = MergeExecutor::new(LinkMode::Hardlink);
        let report = executor
            .apply(&files[0], &files[1..])
            .expect("apply hardlink");

        assert_eq!(report.actions.len(), 1);

        let (path, action) = &report.actions[0];
        match action {
            AppliedAction::Hardlinked { target } => {
                assert_eq!(target, &files[0]);
                // On a single filesystem, nlink must be 2 after hard_link.
                #[cfg(unix)]
                {
                    use std::os::unix::fs::MetadataExt;
                    let meta = fs::metadata(path).expect("metadata after hardlink");
                    assert_eq!(meta.nlink(), 2, "hardlink count should be 2");
                }
            }
            // Cross-device: graceful skip is acceptable.
            AppliedAction::Skipped(_) => {}
            other => panic!("unexpected action: {other:?}"),
        }
    }

    #[test]
    fn test_delete_strategy_removes_duplicates() {
        let files = make_temp_files(3);
        let executor = MergeExecutor::new(LinkMode::Delete);
        executor
            .apply(&files[0], &files[1..])
            .expect("apply delete");

        assert!(files[0].exists(), "primary should still exist");
        assert!(!files[1].exists(), "dup 1 should be deleted");
        assert!(!files[2].exists(), "dup 2 should be deleted");
    }

    #[test]
    fn test_dry_run_changes_nothing() {
        let files = make_temp_files(2);
        let original_content = fs::read(&files[1]).expect("read original");

        let executor = MergeExecutor::new(LinkMode::Delete);
        let report = executor.dry_run(&files[0], &files[1..]).expect("dry_run");

        // File must still exist and be unchanged.
        assert!(files[1].exists(), "dry run must not delete");
        assert_eq!(
            fs::read(&files[1]).expect("read after dry_run"),
            original_content,
            "content must not change after dry_run"
        );

        // Report must still describe the intended action.
        assert_eq!(report.actions.len(), 1);
        assert!(matches!(report.actions[0].1, AppliedAction::Deleted));
    }

    #[test]
    fn test_cross_fs_hardlink_skipped_gracefully() {
        // In most CI environments tempdir is on the same filesystem, so the
        // hard link will succeed and return Hardlinked.  Either outcome must
        // not panic or return Err — only Ok(Hardlinked|Skipped) is valid.
        let files = make_temp_files(2);
        let executor = MergeExecutor::new(LinkMode::Hardlink);
        let result = executor.apply(&files[0], &files[1..]);
        assert!(
            result.is_ok(),
            "hardlink executor must not fail: {result:?}"
        );
        let report = result.expect("hardlink result");
        for (_, action) in &report.actions {
            assert!(
                matches!(
                    action,
                    AppliedAction::Hardlinked { .. } | AppliedAction::Skipped(_)
                ),
                "unexpected action: {action:?}"
            );
        }
    }

    #[test]
    fn test_primary_skipped_when_in_duplicates_list() {
        let files = make_temp_files(1);
        // Pass primary as its own duplicate — must produce Kept, not delete itself.
        let executor = MergeExecutor::new(LinkMode::Delete);
        let report = executor
            .apply(&files[0], &[files[0].clone()])
            .expect("apply self-dup");
        assert!(files[0].exists(), "primary must not be deleted");
        assert_eq!(report.actions.len(), 1);
        assert!(matches!(report.actions[0].1, AppliedAction::Kept));
    }

    #[test]
    fn test_dry_run_symlink_returns_intended_action() {
        let files = make_temp_files(2);
        let executor = MergeExecutor::new(LinkMode::Symlink);
        let report = executor
            .dry_run(&files[0], &files[1..])
            .expect("dry_run symlink");

        // File must NOT have been replaced with a symlink.
        assert!(
            !files[1]
                .symlink_metadata()
                .map(|m| m.file_type().is_symlink())
                .unwrap_or(false),
            "dry_run must not create a symlink"
        );
        assert!(matches!(
            report.actions[0].1,
            AppliedAction::Symlinked { .. }
        ));
    }

    #[test]
    fn test_merge_report_modified_count() {
        let files = make_temp_files(3);
        let executor = MergeExecutor::new(LinkMode::Delete);
        let report = executor.apply(&files[0], &files[1..]).expect("apply");
        assert_eq!(report.modified_count(), 2);
    }

    #[test]
    fn test_apply_resolution_integrates_with_resolver() {
        let files = make_temp_files(3);
        // Build candidates: file 0 is smallest, file 1 is largest, file 2 is middle.
        let candidates = vec![
            FileCandidate::new(files[0].clone(), 100, 100, 100),
            FileCandidate::new(files[1].clone(), 9000, 200, 200),
            FileCandidate::new(files[2].clone(), 500, 50, 50),
        ];
        let resolver = MergeResolver::new(MergeStrategy::KeepLargest, LinkMode::Delete);
        let resolution = resolve(&candidates, resolver.strategy(), resolver.link_mode());

        let executor = MergeExecutor::new(LinkMode::Delete);
        let report = executor
            .apply_resolution(&resolution)
            .expect("apply_resolution");

        // Primary should be files[1] (largest); files[0] and [2] deleted.
        assert_eq!(report.primary_path, files[1]);
        assert!(!files[0].exists(), "dup 0 should be deleted");
        assert!(files[1].exists(), "primary should survive");
        assert!(!files[2].exists(), "dup 2 should be deleted");
        assert_eq!(report.modified_count(), 2);
    }
}

// ---------------------------------------------------------------------------
// DuplicateGroup
// ---------------------------------------------------------------------------

/// A group of files that have been identified as duplicates, with one
/// designated as the canonical representative to keep.
#[derive(Debug, Clone)]
pub struct DuplicateGroup {
    /// All files in this duplicate group (including the representative).
    pub files: Vec<PathBuf>,
    /// The representative (canonical) file to retain.
    pub representative: PathBuf,
}

impl DuplicateGroup {
    /// Create a new `DuplicateGroup`.
    ///
    /// `representative` does not have to be a member of `files`; the caller
    /// is responsible for consistency.
    #[must_use]
    pub fn new(files: Vec<PathBuf>, representative: PathBuf) -> Self {
        Self {
            files,
            representative,
        }
    }

    /// Number of files in this group.
    #[must_use]
    pub fn len(&self) -> usize {
        self.files.len()
    }

    /// Returns `true` if the group contains no files.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    /// Returns references to files that are NOT the representative.
    ///
    /// These are the duplicates that can be removed, linked, or otherwise
    /// disposed of according to a [`MergeStrategy`].
    #[must_use]
    pub fn duplicates(&self) -> Vec<&PathBuf> {
        self.files
            .iter()
            .filter(|p| p.as_path() != self.representative.as_path())
            .collect()
    }

    /// Returns `true` if `path` is the representative of this group.
    #[must_use]
    pub fn is_representative(&self, path: &Path) -> bool {
        self.representative == path
    }
}

// ---------------------------------------------------------------------------
// MergeResolver
// ---------------------------------------------------------------------------

/// Resolves a [`DuplicateGroup`] to a single canonical file using a
/// configured [`MergeStrategy`] and [`LinkMode`].
///
/// Two resolution paths are provided:
/// 1. [`MergeResolver::resolve`] — reads filesystem metadata for scoring.
/// 2. [`MergeResolver::resolve_from_candidates`] — accepts pre-built
///    [`FileCandidate`] data (no filesystem access required).
#[derive(Debug, Clone)]
pub struct MergeResolver {
    strategy: MergeStrategy,
    link_mode: LinkMode,
}

impl MergeResolver {
    /// Create a new resolver.
    #[must_use]
    pub fn new(strategy: MergeStrategy, link_mode: LinkMode) -> Self {
        Self {
            strategy,
            link_mode,
        }
    }

    /// Create a resolver that deletes duplicates and keeps with `KeepLargest`.
    #[must_use]
    pub fn default_delete() -> Self {
        Self::new(MergeStrategy::KeepLargest, LinkMode::Delete)
    }

    /// Returns the configured strategy.
    #[must_use]
    pub fn strategy(&self) -> MergeStrategy {
        self.strategy
    }

    /// Returns the configured link mode.
    #[must_use]
    pub fn link_mode(&self) -> LinkMode {
        self.link_mode
    }

    /// Resolve which file to keep by reading filesystem metadata.
    ///
    /// For each file in `group.files`, attempts to read its metadata (size,
    /// mtime). Files whose metadata cannot be read are assigned zero values and
    /// will lose to files with valid metadata under most strategies.
    ///
    /// Returns the path of the file to keep. Falls back to the first file when
    /// `group.files` is empty.
    #[must_use]
    pub fn resolve(&self, group: &DuplicateGroup) -> PathBuf {
        if group.files.is_empty() {
            return group.representative.clone();
        }

        let candidates: Vec<FileCandidate> = group
            .files
            .iter()
            .map(|path| {
                let meta = std::fs::metadata(path);
                let (size, modified, created) = meta
                    .as_ref()
                    .map(|m| {
                        let size = m.len();
                        let modified = m
                            .modified()
                            .ok()
                            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                            .map(|d| d.as_secs())
                            .unwrap_or(0);
                        let created = m
                            .created()
                            .ok()
                            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                            .map(|d| d.as_secs())
                            .unwrap_or(0);
                        (size, modified, created)
                    })
                    .unwrap_or((0, 0, 0));
                FileCandidate::new(path.clone(), size, modified, created)
            })
            .collect();

        self.resolve_from_candidates(&candidates)
            .unwrap_or_else(|| group.files[0].clone())
    }

    /// Resolve from pre-built candidate metadata (no filesystem access).
    ///
    /// Returns the path of the winning candidate, or `None` if `candidates`
    /// is empty.
    #[must_use]
    pub fn resolve_from_candidates(&self, candidates: &[FileCandidate]) -> Option<PathBuf> {
        if candidates.is_empty() {
            return None;
        }
        let resolution = resolve(candidates, self.strategy, self.link_mode);
        resolution
            .files
            .iter()
            .find(|f| f.action.is_keep())
            .map(|f| f.candidate.path.clone())
    }
}

// ---------------------------------------------------------------------------
// DuplicateGroup + MergeResolver tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod group_resolver_tests {
    use super::*;

    fn paths(names: &[&str]) -> Vec<PathBuf> {
        names.iter().map(|n| PathBuf::from(n)).collect()
    }

    // ── DuplicateGroup ─────────────────────────────────────────────────────

    #[test]
    fn test_group_new_and_len() {
        let g = DuplicateGroup::new(
            paths(&["/a.mp4", "/b.mp4", "/c.mp4"]),
            PathBuf::from("/a.mp4"),
        );
        assert_eq!(g.len(), 3);
        assert!(!g.is_empty());
    }

    #[test]
    fn test_group_empty() {
        let g = DuplicateGroup::new(vec![], PathBuf::from("/none.mp4"));
        assert!(g.is_empty());
        assert_eq!(g.len(), 0);
    }

    #[test]
    fn test_group_duplicates_excludes_representative() {
        let g = DuplicateGroup::new(
            paths(&["/a.mp4", "/b.mp4", "/c.mp4"]),
            PathBuf::from("/a.mp4"),
        );
        let dups = g.duplicates();
        assert_eq!(dups.len(), 2);
        assert!(!dups.contains(&&PathBuf::from("/a.mp4")));
        assert!(dups.contains(&&PathBuf::from("/b.mp4")));
        assert!(dups.contains(&&PathBuf::from("/c.mp4")));
    }

    #[test]
    fn test_group_is_representative() {
        let g = DuplicateGroup::new(paths(&["/rep.mp4", "/dup.mp4"]), PathBuf::from("/rep.mp4"));
        assert!(g.is_representative(Path::new("/rep.mp4")));
        assert!(!g.is_representative(Path::new("/dup.mp4")));
    }

    #[test]
    fn test_group_duplicates_all_are_duplicates_when_representative_absent() {
        // Representative not in files list — all files are returned as duplicates.
        let g = DuplicateGroup::new(paths(&["/b.mp4", "/c.mp4"]), PathBuf::from("/a.mp4"));
        assert_eq!(g.duplicates().len(), 2);
    }

    // ── MergeResolver ──────────────────────────────────────────────────────

    fn make_candidates() -> Vec<FileCandidate> {
        vec![
            FileCandidate::new(PathBuf::from("/small.mp4"), 500, 100, 90),
            FileCandidate::new(PathBuf::from("/large.mp4"), 2000, 200, 80),
            FileCandidate::new(PathBuf::from("/oldest.mp4"), 1000, 50, 100),
        ]
    }

    #[test]
    fn test_resolver_keep_largest_from_candidates() {
        let r = MergeResolver::new(MergeStrategy::KeepLargest, LinkMode::Delete);
        let result = r.resolve_from_candidates(&make_candidates());
        assert_eq!(result, Some(PathBuf::from("/large.mp4")));
    }

    #[test]
    fn test_resolver_keep_newest_from_candidates() {
        let r = MergeResolver::new(MergeStrategy::KeepNewest, LinkMode::Delete);
        let result = r.resolve_from_candidates(&make_candidates());
        assert_eq!(result, Some(PathBuf::from("/large.mp4"))); // modified=200
    }

    #[test]
    fn test_resolver_keep_oldest_from_candidates() {
        let r = MergeResolver::new(MergeStrategy::KeepOldest, LinkMode::Delete);
        let result = r.resolve_from_candidates(&make_candidates());
        assert_eq!(result, Some(PathBuf::from("/oldest.mp4"))); // modified=50
    }

    #[test]
    fn test_resolver_keep_smallest_from_candidates() {
        let r = MergeResolver::new(MergeStrategy::KeepSmallest, LinkMode::Delete);
        let result = r.resolve_from_candidates(&make_candidates());
        assert_eq!(result, Some(PathBuf::from("/small.mp4"))); // size=500
    }

    #[test]
    fn test_resolver_keep_highest_quality_from_candidates() {
        let cs = vec![
            FileCandidate::new(PathBuf::from("/low.mp4"), 100, 10, 10).with_quality(0.3),
            FileCandidate::new(PathBuf::from("/high.mp4"), 100, 10, 10).with_quality(0.95),
        ];
        let r = MergeResolver::new(MergeStrategy::KeepHighestQuality, LinkMode::Delete);
        let result = r.resolve_from_candidates(&cs);
        assert_eq!(result, Some(PathBuf::from("/high.mp4")));
    }

    #[test]
    fn test_resolver_empty_candidates_returns_none() {
        let r = MergeResolver::new(MergeStrategy::KeepLargest, LinkMode::Delete);
        assert!(r.resolve_from_candidates(&[]).is_none());
    }

    #[test]
    fn test_resolver_strategy_and_link_mode_accessors() {
        let r = MergeResolver::new(MergeStrategy::KeepSmallest, LinkMode::Symlink);
        assert_eq!(r.strategy(), MergeStrategy::KeepSmallest);
        assert_eq!(r.link_mode(), LinkMode::Symlink);
    }

    #[test]
    fn test_resolver_default_delete() {
        let r = MergeResolver::default_delete();
        assert_eq!(r.strategy(), MergeStrategy::KeepLargest);
        assert_eq!(r.link_mode(), LinkMode::Delete);
    }

    #[test]
    fn test_resolver_resolve_filesystem_fallback() {
        // Files do not exist → metadata reads fail → fallback to first file.
        let group = DuplicateGroup::new(
            paths(&["/nonexistent_a.mp4", "/nonexistent_b.mp4"]),
            PathBuf::from("/nonexistent_a.mp4"),
        );
        let r = MergeResolver::new(MergeStrategy::KeepLargest, LinkMode::Delete);
        // With all sizes=0 (metadata unavailable), pick_winner returns 0 → first file
        let result = r.resolve(&group);
        assert!(!result.as_os_str().is_empty());
    }

    #[test]
    fn test_resolver_resolve_empty_group() {
        let group = DuplicateGroup::new(vec![], PathBuf::from("/rep.mp4"));
        let r = MergeResolver::new(MergeStrategy::KeepLargest, LinkMode::Delete);
        // Falls back to representative
        let result = r.resolve(&group);
        assert_eq!(result, PathBuf::from("/rep.mp4"));
    }
}