deepmerge 0.1.0

Deep merge functionality with policy-driven merging 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
//! Policy system for configuring merge behavior
//!
//! Policies define default behaviors for different types during merging.
//! They can be overridden at struct, field, or type level.


/// Scalar merge action for primitive types and structs.
///
/// This enum determines the fundamental merge strategy for scalar values
/// and can be used to configure whether structs should be recursively merged
/// or replaced entirely.
///
/// # Examples
///
/// ```rust
/// use deepmerge::prelude::*;
///
/// // ScalarAction enum demonstrates merge strategies
/// let replace_action = ScalarAction::Replace;
/// let keep_action = ScalarAction::Keep;
/// let merge_action = ScalarAction::Merge;
///
/// // Simple demonstration with basic merge
/// #[derive(DeepMerge, Debug, PartialEq)]
/// struct Config {
///     name: String,
///     value: i32,
/// }
///
/// let mut config1 = Config { name: "app".to_string(), value: 10 };
/// let config2 = Config { name: "service".to_string(), value: 20 };
///
/// // Default merge behavior - recursively merge fields
/// config1.merge_with_policy(config2, &DefaultPolicy);
/// assert_eq!(config1.name, "service"); // String uses Replace by default
/// assert_eq!(config1.value, 20); // i32 uses Replace by default
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScalarAction {
    /// Replace left with right (default for scalars)
    Replace,
    /// Keep left, ignore right
    Keep,
    /// Recursively merge (default for structs with `DeepMerge`)
    Merge,
}

/// Sequence merge behavior for collections like `Vec<T>`, arrays, and slices.
///
/// This enum defines how two sequences should be combined during merging.
/// Different strategies are useful for different use cases like configuration
/// merging, data aggregation, or collection operations.
///
/// # Examples
///
/// ```rust
/// use deepmerge::prelude::*;
///
/// let mut tags1 = vec!["rust", "web"];
/// let tags2 = vec!["api", "server"];
///
/// // Append: add right elements to the end (default)
/// let policy = ComposedPolicy::new(DefaultPolicy)
///     .with_sequence_merge(SequenceMerge::Append);
/// let mut test = tags1.clone();
/// test.merge_with_policy(tags2.clone(), &policy);
/// assert_eq!(test, vec!["rust", "web", "api", "server"]);
///
/// // Prepend: add right elements to the beginning
/// let policy = ComposedPolicy::new(DefaultPolicy)
///     .with_sequence_merge(SequenceMerge::Prepend);
/// let mut test = tags1.clone();
/// test.merge_with_policy(tags2.clone(), &policy);
/// assert_eq!(test, vec!["api", "server", "rust", "web"]);
///
/// // Extend: same as Append but optimized for performance
/// let policy = ComposedPolicy::new(DefaultPolicy)
///     .with_sequence_merge(SequenceMerge::Extend);
/// let mut test = tags1.clone();
/// test.merge_with_policy(tags2.clone(), &policy);
/// assert_eq!(test, vec!["rust", "web", "api", "server"]);
/// ```
///
/// # Note
/// 
/// `Union` and `Intersect` operations may require additional trait bounds
/// or special handling depending on the element type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SequenceMerge {
    /// Append right to left (default)
    Append,
    /// Prepend right to left
    Prepend,
    /// Extend left with right (like `HashMap::extend`)
    Extend,
    /// Union of left and right (dedupe)
    Union,
    /// Intersection of left and right
    Intersect,
}

/// Option merge behavior for `Option<T>` types.
///
/// This enum defines how two `Option` values should be combined,
/// providing different strategies for handling `Some` and `None` values.
///
/// # Examples
///
/// ```rust
/// use deepmerge::prelude::*;
///
/// // Take: use right if Some, otherwise keep left (default)
/// let policy = ComposedPolicy::new(DefaultPolicy)
///     .with_option_merge(OptionMerge::Take);
/// let mut left = Some(42);
/// left.merge_with_policy(Some(100), &policy);
/// assert_eq!(left, Some(100));
/// 
/// let mut left = Some(42);
/// left.merge_with_policy(None, &policy);
/// assert_eq!(left, Some(42));
///
/// // Preserve: always keep left, ignore right
/// let policy = ComposedPolicy::new(DefaultPolicy)
///     .with_option_merge(OptionMerge::Preserve);
/// let mut left = Some(42);
/// left.merge_with_policy(Some(100), &policy);
/// assert_eq!(left, Some(42));
///
/// // OrLeft: use left if Some, otherwise use right
/// let policy = ComposedPolicy::new(DefaultPolicy)
///     .with_option_merge(OptionMerge::OrLeft);
/// let mut left: Option<i32> = None;
/// left.merge_with_policy(Some(100), &policy);
/// assert_eq!(left, Some(100));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OptionMerge {
    /// Take right if Some, else keep left (default)
    Take,
    /// Always keep left, ignore right
    Preserve,
    /// Take left if Some, else take right
    OrLeft,
}

/// Number merge behavior for numeric types.
///
/// This enum defines different strategies for combining two numeric values,
/// supporting arithmetic operations and comparisons.
///
/// # Examples
///
/// ```rust
/// use deepmerge::prelude::*;
///
/// // Sum: add values together
/// #[derive(DeepMerge)]
/// #[merge(policy(number = sum))]
/// struct Config { score: i32 }
///
/// let mut config = Config { score: 10 };
/// config.merge_with_policy(Config { score: 25 }, &DefaultPolicy);
/// assert_eq!(config.score, 35);
///
/// // Max: keep the larger value  
/// #[derive(DeepMerge)]
/// #[merge(policy(number = max))]
/// struct MaxConfig { value: i32 }
///
/// let mut config = MaxConfig { value: 10 };
/// config.merge_with_policy(MaxConfig { value: 5 }, &DefaultPolicy);
/// assert_eq!(config.value, 10);
/// config.merge_with_policy(MaxConfig { value: 15 }, &DefaultPolicy);
/// assert_eq!(config.value, 15);
///
/// // Min: keep the smaller value
/// #[derive(DeepMerge)]
/// #[merge(policy(number = min))]
/// struct MinConfig { value: i32 }
///
/// let mut config = MinConfig { value: 10 };
/// config.merge_with_policy(MinConfig { value: 5 }, &DefaultPolicy);
/// assert_eq!(config.value, 5);
/// config.merge_with_policy(MinConfig { value: 15 }, &DefaultPolicy);
/// assert_eq!(config.value, 5);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NumberMerge {
    /// Replace with right (default)
    Replace,
    /// Keep left, ignore right
    Keep,
    /// Take maximum of left and right
    Max,
    /// Take minimum of left and right
    Min,
    /// Sum left and right
    Sum,
}

/// Map merge behavior for `HashMap` and `BTreeMap` types.
///
/// This enum defines strategies for combining two maps, handling key conflicts
/// and nested value merging in different ways.
///
/// # Examples
///
/// ```rust
/// use std::collections::HashMap;
/// use deepmerge::prelude::*;
///
/// // Overlay: merge recursively, right wins on conflicts (default)
/// #[derive(DeepMerge)]
/// #[merge(policy(map = overlay))]
/// struct Config {
///     settings: HashMap<String, i32>,
/// }
///
/// let mut config = Config {
///     settings: [("a".to_string(), 1), ("b".to_string(), 2)].into(),
/// };
/// let update = Config {
///     settings: [("b".to_string(), 3), ("c".to_string(), 4)].into(),
/// };
/// config.merge_with_policy(update, &DefaultPolicy);
/// // Result: {"a": 1, "b": 3, "c": 4}
/// assert_eq!(config.settings.get("a"), Some(&1));
/// assert_eq!(config.settings.get("b"), Some(&3)); // right wins
/// assert_eq!(config.settings.get("c"), Some(&4));
///
/// // Left: keep only left entries
/// #[derive(DeepMerge)]
/// #[merge(policy(map = left))]
/// struct LeftConfig {
///     data: HashMap<String, i32>,
/// }
///
/// let mut config = LeftConfig {
///     data: [("a".to_string(), 1), ("b".to_string(), 2)].into(),
/// };
/// let update = LeftConfig {
///     data: [("b".to_string(), 3), ("c".to_string(), 4)].into(),
/// };
/// config.merge_with_policy(update, &DefaultPolicy);
/// // Result: {"a": 1, "b": 2} (unchanged)
/// assert_eq!(config.data.len(), 2);
/// assert_eq!(config.data.get("c"), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MapMerge {
    /// Overlay right entries, merge values recursively (default)
    Overlay,
    /// Union of keys, prefer right on conflicts
    Union,
    /// Keep only left entries
    Left,
    /// Replace with right entries
    Right,
}

/// Boolean merge behavior for `bool` types.
///
/// This enum defines logical operations for combining two boolean values,
/// supporting different prioritization strategies.
///
/// # Examples
///
/// ```rust
/// use deepmerge::prelude::*;
///
/// // TrueWins: logical OR behavior
/// #[derive(DeepMerge)]
/// #[merge(policy(bool = true_wins))]
/// struct Config { enabled: bool }
///
/// let mut config = Config { enabled: false };
/// config.merge_with_policy(Config { enabled: true }, &DefaultPolicy);
/// assert_eq!(config.enabled, true);
///
/// let mut config = Config { enabled: true };
/// config.merge_with_policy(Config { enabled: false }, &DefaultPolicy);
/// assert_eq!(config.enabled, true); // true wins
///
/// // FalseWins: logical NOR behavior  
/// #[derive(DeepMerge)]
/// #[merge(policy(bool = false_wins))]
/// struct FalseConfig { active: bool }
///
/// let mut config = FalseConfig { active: true };
/// config.merge_with_policy(FalseConfig { active: false }, &DefaultPolicy);
/// assert_eq!(config.active, false); // false wins
///
/// // Keep: ignore right value
/// #[derive(DeepMerge)]
/// #[merge(policy(bool = keep))]
/// struct KeepConfig { flag: bool }
///
/// let mut config = KeepConfig { flag: true };
/// config.merge_with_policy(KeepConfig { flag: false }, &DefaultPolicy);
/// assert_eq!(config.flag, true); // kept original
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BoolMerge {
    /// Replace with right (default)
    Replace,
    /// Keep left, ignore right
    Keep,
    /// Set to true if either is true
    TrueWins,
    /// Set to false if either is false
    FalseWins,
}

/// String merge behavior for `String` and `&str` types.
///
/// This enum defines different strategies for combining two string values,
/// including concatenation with optional separators.
///
/// # Examples
///
/// ```rust
/// use deepmerge::prelude::*;
///
/// // Concat: simple concatenation
/// #[derive(DeepMerge)]
/// #[merge(policy(string = concat))]
/// struct Config { text: String }
///
/// let mut config = Config { text: "Hello".to_string() };
/// config.merge_with_policy(Config { text: " World".to_string() }, &DefaultPolicy);
/// assert_eq!(config.text, "Hello World");
///
/// // ConcatWithSep: concatenation with separator
/// #[derive(DeepMerge)]
/// #[merge(policy(string = StringMerge::ConcatWithSep(", ")))]
/// struct ListConfig { items: String }
///
/// let mut config = ListConfig { items: "apple".to_string() };
/// config.merge_with_policy(ListConfig { items: "banana".to_string() }, &DefaultPolicy);
/// assert_eq!(config.items, "apple, banana");
///
/// // Keep: ignore right value
/// #[derive(DeepMerge)]
/// #[merge(policy(string = keep))]
/// struct KeepConfig { name: String }
///
/// let mut config = KeepConfig { name: "original".to_string() };
/// config.merge_with_policy(KeepConfig { name: "new".to_string() }, &DefaultPolicy);
/// assert_eq!(config.name, "original");
///
/// // Field-level override with path separator
/// #[derive(DeepMerge)]
/// struct PathConfig {
///     #[merge(string = StringMerge::ConcatWithSep(" -> "))]
///     path: String,
/// }
///
/// let mut config = PathConfig { path: "home".to_string() };
/// config.merge_with_policy(PathConfig { path: "user".to_string() }, &DefaultPolicy);
/// assert_eq!(config.path, "home -> user");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StringMerge {
    /// Replace left with right (default)
    Replace,
    /// Keep left, ignore right
    Keep,
    /// Concatenate right to left
    Concat,
    /// Concatenate with a separator
    ConcatWithSep(&'static str),
}

/// When to apply merge operations (guards/conditions).
///
/// This enum provides conditional logic for determining whether a merge
/// operation should be performed, enabling fine-grained control over when
/// values are actually merged.
///
/// # Examples
///
/// ```rust
/// use deepmerge::prelude::*;
///
/// // NonEmpty: only merge when right value is non-empty
/// #[derive(DeepMerge)]
/// #[merge(policy(condition = non_empty))]
/// struct Config { text: String }
/// 
/// let mut config = Config { text: "original".to_string() };
/// config.merge_with_policy(Config { text: "".to_string() }, &DefaultPolicy);
/// assert_eq!(config.text, "original"); // empty string ignored
/// 
/// config.merge_with_policy(Config { text: "new".to_string() }, &DefaultPolicy);
/// assert_eq!(config.text, "new"); // non-empty string merged
///
/// // NonDefault: only merge when right is not default value
/// #[derive(DeepMerge)]
/// #[merge(policy(condition = non_default))]
/// struct DefaultConfig { value: i32 }
/// 
/// let mut config = DefaultConfig { value: 42 };
/// config.merge_with_policy(DefaultConfig { value: 0 }, &DefaultPolicy); // 0 is default for i32
/// assert_eq!(config.value, 42); // default ignored
/// 
/// config.merge_with_policy(DefaultConfig { value: 99 }, &DefaultPolicy);
/// assert_eq!(config.value, 99); // non-default merged
///
/// // Some: only merge when Option is Some
/// #[derive(DeepMerge)]
/// #[merge(policy(condition = some))]
/// struct OptConfig { data: Option<i32> }
/// 
/// let mut config = OptConfig { data: Some(42) };
/// config.merge_with_policy(OptConfig { data: None }, &DefaultPolicy);
/// assert_eq!(config.data, Some(42)); // None ignored
/// 
/// config.merge_with_policy(OptConfig { data: Some(99) }, &DefaultPolicy);
/// assert_eq!(config.data, Some(99)); // Some merged
///
/// // Changed: only merge when values differ
/// #[derive(DeepMerge)]
/// #[merge(policy(condition = changed))]
/// struct ChangeConfig { count: i32 }
/// 
/// let mut config = ChangeConfig { count: 42 };
/// config.merge_with_policy(ChangeConfig { count: 42 }, &DefaultPolicy);
/// assert_eq!(config.count, 42); // same value ignored
/// 
/// config.merge_with_policy(ChangeConfig { count: 99 }, &DefaultPolicy);
/// assert_eq!(config.count, 99); // different value merged
/// ```
#[derive(Debug)]
pub enum Condition {
    /// Always apply (default)
    Always,
    /// Only when right is non-empty (for collections/strings)
    NonEmpty,
    /// Only when right is not the default value
    NonDefault,
    /// Only when right is Some (for Options)
    Some,
    /// Only when right differs from left
    Changed,
    /// Only when right differs from left according to a custom key extractor function
    /// This stores a function that can extract comparable keys from values
    /// The function signature should be fn(&T) -> K where K: `PartialEq`
    ChangedBy(fn()),
}

impl Clone for Condition {
    fn clone(&self) -> Self {
        match self {
            Condition::Always => Condition::Always,
            Condition::NonEmpty => Condition::NonEmpty,
            Condition::NonDefault => Condition::NonDefault,
            Condition::Some => Condition::Some,
            Condition::Changed => Condition::Changed,
            Condition::ChangedBy(f) => Condition::ChangedBy(*f),
        }
    }
}

impl PartialEq for Condition {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Condition::Always, Condition::Always)
            | (Condition::NonEmpty, Condition::NonEmpty)
            | (Condition::NonDefault, Condition::NonDefault)
            | (Condition::Some, Condition::Some)
            | (Condition::Changed, Condition::Changed) => true,
            (Condition::ChangedBy(f1), Condition::ChangedBy(f2)) => core::ptr::eq(std::ptr::from_ref::<fn()>(f1), std::ptr::from_ref::<fn()>(f2)),
            _ => false,
        }
    }
}

impl Eq for Condition {}

/// Policy trait defining default merge behaviors
pub trait Policy: Clone {
    /// Default action for scalars
    fn scalar_action(&self) -> ScalarAction {
        ScalarAction::Replace
    }

    /// Default action for structs that implement `DeepMerge`
    fn struct_action(&self) -> ScalarAction {
        ScalarAction::Merge
    }

    /// Default strategy for Options
    fn option_merge(&self) -> OptionMerge {
        OptionMerge::Take
    }

    /// Default strategy for sequences (Vec, arrays, etc.)
    fn sequence_merge(&self) -> SequenceMerge {
        SequenceMerge::Append
    }

    /// Whether to deduplicate sequences by default
    fn sequence_dedupe(&self) -> bool {
        false
    }

    /// Default strategy for maps (`HashMap`, `BTreeMap`, etc.)
    fn map_merge(&self) -> MapMerge {
        MapMerge::Overlay
    }

    /// Default strategy for numbers
    fn number_merge(&self) -> NumberMerge {
        NumberMerge::Replace
    }

    /// Default strategy for booleans
    fn bool_merge(&self) -> BoolMerge {
        BoolMerge::Replace
    }

    /// Default strategy for strings
    fn string_merge(&self) -> StringMerge {
        StringMerge::Replace
    }

    /// Default when condition
    fn when_condition(&self) -> Condition {
        Condition::Always
    }
}

/// Default policy with sensible defaults
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultPolicy;

impl Policy for DefaultPolicy {
    // Uses all the default implementations
}

/// Policy that always replaces (no merging)
#[derive(Debug, Clone, Copy, Default)]
pub struct StrictReplacePolicy;

impl Policy for StrictReplacePolicy {
    fn struct_action(&self) -> ScalarAction {
        ScalarAction::Replace
    }
    
    fn map_merge(&self) -> MapMerge {
        MapMerge::Right
    }
}

/// Policy that preserves left values
#[derive(Debug, Clone, Copy, Default)]
pub struct PreservePolicy;

impl Policy for PreservePolicy {
    fn scalar_action(&self) -> ScalarAction {
        ScalarAction::Keep
    }
    
    fn struct_action(&self) -> ScalarAction {
        ScalarAction::Keep
    }
    
    fn option_merge(&self) -> OptionMerge {
        OptionMerge::Preserve
    }
    
    fn sequence_merge(&self) -> SequenceMerge {
        SequenceMerge::Extend // Keep left, ignore right
    }
    
    fn map_merge(&self) -> MapMerge {
        MapMerge::Left
    }
    
    fn number_merge(&self) -> NumberMerge {
        NumberMerge::Keep // Preserve left values
    }
    
    fn bool_merge(&self) -> BoolMerge {
        BoolMerge::Keep
    }
    
    fn string_merge(&self) -> StringMerge {
        StringMerge::Keep
    }
    
    fn when_condition(&self) -> Condition {
        Condition::Always // But we'll ignore the merge anyway due to other settings
    }
}

/// Policy that deduplicates collections
#[derive(Debug, Clone, Copy, Default)]
pub struct DedupeCollectionsPolicy;

impl Policy for DedupeCollectionsPolicy {
    fn sequence_merge(&self) -> SequenceMerge {
        SequenceMerge::Union
    }
    
    fn sequence_dedupe(&self) -> bool {
        true
    }
}

/// Composed policy that overrides specific behaviors from a base policy
/// Used by the derive macro to implement field-level policy overrides
#[derive(Debug, Clone)]
pub struct ComposedPolicy<P: Policy> {
    /// The base policy to use when no override is specified
    pub base: P,
    /// Override for scalar merge behavior 
    pub scalar_action: Option<ScalarAction>,
    /// Override for struct merge behavior
    pub struct_action: Option<ScalarAction>,
    /// Override for Option<T> merge behavior
    pub option_merge: Option<OptionMerge>,
    /// Override for sequence (Vec, arrays) merge behavior
    pub sequence_merge: Option<SequenceMerge>,
    /// Whether to deduplicate sequences after merging
    pub sequence_dedupe: Option<bool>,
    /// Override for HashMap/BTreeMap merge behavior
    pub map_merge: Option<MapMerge>,
    /// Override for numeric type merge behavior
    pub number_merge: Option<NumberMerge>,
    /// Override for boolean merge behavior
    pub bool_merge: Option<BoolMerge>,
    /// Override for string merge behavior
    pub string_merge: Option<StringMerge>,
    /// Condition for when to apply the merge
    pub when_condition: Option<Condition>,
}

impl<P: Policy> ComposedPolicy<P> {
    /// Create a new composed policy with the given base policy and no overrides
    pub fn new(base: P) -> Self {
        Self {
            base,
            scalar_action: None,
            struct_action: None,
            option_merge: None,
            sequence_merge: None,
            sequence_dedupe: None,
            map_merge: None,
            number_merge: None,
            bool_merge: None,
            string_merge: None,
            when_condition: None,
        }
    }
    
    /// Set the scalar action for this policy
    #[must_use]
    pub fn with_scalar_action(mut self, action: ScalarAction) -> Self {
        self.scalar_action = Some(action);
        self
    }
    
    /// Set the struct action for this policy
    #[must_use]
    pub fn with_struct_action(mut self, action: ScalarAction) -> Self {
        self.struct_action = Some(action);
        self
    }
    
    /// Set the option merge strategy
    #[must_use]
    pub fn with_option_merge(mut self, merge: OptionMerge) -> Self {
        self.option_merge = Some(merge);
        self
    }
    
    /// Set the sequence merge strategy
    #[must_use]
    pub fn with_sequence_merge(mut self, merge: SequenceMerge) -> Self {
        self.sequence_merge = Some(merge);
        self
    }
    
    /// Set whether to deduplicate sequences
    #[must_use]
    pub fn with_sequence_dedupe(mut self, dedupe: bool) -> Self {
        self.sequence_dedupe = Some(dedupe);
        self
    }
    
    /// Set the map merge strategy
    #[must_use]
    pub fn with_map_merge(mut self, merge: MapMerge) -> Self {
        self.map_merge = Some(merge);
        self
    }
    
    /// Set the number merge strategy
    #[must_use]
    pub fn with_number_merge(mut self, merge: NumberMerge) -> Self {
        self.number_merge = Some(merge);
        self
    }
    
    /// Set the boolean merge strategy
    #[must_use]
    pub fn with_bool_merge(mut self, merge: BoolMerge) -> Self {
        self.bool_merge = Some(merge);
        self
    }
    
    /// Set the string merge strategy
    #[must_use]
    pub fn with_string_merge(mut self, merge: StringMerge) -> Self {
        self.string_merge = Some(merge);
        self
    }
    
    /// Set the when condition
    #[must_use]
    pub fn with_when_condition(mut self, condition: Condition) -> Self {
        self.when_condition = Some(condition);
        self
    }
}

impl<P: Policy> Policy for ComposedPolicy<P> {
    fn scalar_action(&self) -> ScalarAction {
        self.scalar_action.unwrap_or_else(|| self.base.scalar_action())
    }
    
    fn struct_action(&self) -> ScalarAction {
        self.struct_action.unwrap_or_else(|| self.base.struct_action())
    }
    
    fn option_merge(&self) -> OptionMerge {
        self.option_merge.unwrap_or_else(|| self.base.option_merge())
    }
    
    fn sequence_merge(&self) -> SequenceMerge {
        self.sequence_merge.unwrap_or_else(|| self.base.sequence_merge())
    }
    
    fn sequence_dedupe(&self) -> bool {
        self.sequence_dedupe.unwrap_or_else(|| self.base.sequence_dedupe())
    }
    
    fn map_merge(&self) -> MapMerge {
        self.map_merge.unwrap_or_else(|| self.base.map_merge())
    }
    
    fn number_merge(&self) -> NumberMerge {
        self.number_merge.unwrap_or_else(|| self.base.number_merge())
    }
    
    fn bool_merge(&self) -> BoolMerge {
        self.bool_merge.unwrap_or_else(|| self.base.bool_merge())
    }
    
    fn string_merge(&self) -> StringMerge {
        self.string_merge.clone().unwrap_or_else(|| self.base.string_merge())
    }
    
    fn when_condition(&self) -> Condition {
        self.when_condition.clone().unwrap_or_else(|| self.base.when_condition())
    }
}

/// Result of a merge operation indicating what changed
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeOutcome {
    /// Nothing was changed during the merge
    Unchanged,
    /// Something was changed during the merge
    Changed,
}

impl MergeOutcome {
    /// Check if the merge changed anything
    #[must_use]
    pub fn is_changed(&self) -> bool {
        matches!(self, MergeOutcome::Changed)
    }
    
    /// Check if the merge left everything unchanged
    #[must_use]
    pub fn is_unchanged(&self) -> bool {
        matches!(self, MergeOutcome::Unchanged)
    }
}

/// Merge trait with policy parameter
pub trait DeepMerge<P: Policy = DefaultPolicy>: Sized {
    /// Merge another instance into this one using the specified policy
    fn merge_with_policy(&mut self, other: Self, policy: &P);
    
    /// Merge another instance by reference using the specified policy
    /// This avoids moving the source when possible
    fn merge_ref(&mut self, src: &Self, policy: &P)
    where
        Self: Clone,
    {
        self.merge_with_policy(src.clone(), policy);
    }
    
    /// Merge and report whether anything changed
    fn merge_with_policy_reporting(&mut self, other: Self, policy: &P) -> MergeOutcome {
        // Default implementation just merges and reports changed
        // Individual types can override for more precise change detection
        self.merge_with_policy(other, policy);
        MergeOutcome::Changed
    }
    
    /// Merge by reference and report whether anything changed
    fn merge_ref_reporting(&mut self, src: &Self, policy: &P) -> MergeOutcome
    where
        Self: Clone,
    {
        self.merge_with_policy_reporting(src.clone(), policy)
    }
    
    /// Non-mutating merge using the specified policy
    #[must_use]
    fn merged_with_policy(mut self, other: Self, policy: &P) -> Self {
        self.merge_with_policy(other, policy);
        self
    }
}

/// Merge trait for merging from other types, including references
/// This allows merging from U into Self without requiring Clone on U
pub trait DeepMergeFrom<U, P: Policy = DefaultPolicy> {
    /// Merge from another type/reference using the specified policy
    fn merge_from_with_policy(&mut self, other: U, policy: &P);
    
    /// Merge from another type/reference and report whether anything changed
    fn merge_from_with_policy_reporting(&mut self, other: U, policy: &P) -> MergeOutcome {
        // Default implementation just merges and reports changed
        // Individual types can override for more precise change detection
        self.merge_from_with_policy(other, policy);
        MergeOutcome::Changed
    }
}

/// Extension trait for convenience methods when using `DefaultPolicy`
/// 
/// This trait provides shorthand methods for common merge operations
/// without requiring explicit policy arguments.
pub trait DeepMergeDefault: DeepMerge<DefaultPolicy> {
    /// Merge using the default policy
    fn merge(&mut self, other: Self) {
        self.merge_with_policy(other, &DefaultPolicy);
    }
    
    /// Merge by reference using the default policy
    fn merge_ref(&mut self, src: &Self)
    where
        Self: Clone,
    {
        DeepMerge::merge_ref(self, src, &DefaultPolicy);
    }
    
    /// Merge and report changes using the default policy
    fn merge_reporting(&mut self, other: Self) -> MergeOutcome {
        self.merge_with_policy_reporting(other, &DefaultPolicy)
    }
    
    /// Merge by reference and report changes using the default policy
    fn merge_ref_reporting(&mut self, src: &Self) -> MergeOutcome
    where
        Self: Clone,
    {
        DeepMerge::merge_ref_reporting(self, src, &DefaultPolicy)
    }
    
    /// Non-mutating merge using the default policy
    #[must_use]
    fn merged(self, other: Self) -> Self {
        self.merged_with_policy(other, &DefaultPolicy)
    }
}

// Blanket impl for all types that implement DeepMerge<DefaultPolicy>
impl<T: DeepMerge<DefaultPolicy>> DeepMergeDefault for T {}

/// Extension trait for `DeepMergeFrom` convenience methods when using `DefaultPolicy`
pub trait DeepMergeFromDefault<U>: DeepMergeFrom<U, DefaultPolicy> {
    /// Merge from another type/reference using the default policy
    fn merge_from(&mut self, other: U) {
        self.merge_from_with_policy(other, &DefaultPolicy);
    }
    
    /// Merge from another type/reference and report changes using the default policy
    fn merge_from_reporting(&mut self, other: U) -> MergeOutcome {
        self.merge_from_with_policy_reporting(other, &DefaultPolicy)
    }
}

// Blanket impl for all types that implement DeepMergeFrom<U, DefaultPolicy>
impl<T: DeepMergeFrom<U, DefaultPolicy>, U> DeepMergeFromDefault<U> for T {}

// Bridge implementation: DeepMerge -> DeepMergeFrom for owned types
impl<T: DeepMerge<P>, P: Policy> DeepMergeFrom<T, P> for T {
    fn merge_from_with_policy(&mut self, other: T, policy: &P) {
        self.merge_with_policy(other, policy);
    }
    
    fn merge_from_with_policy_reporting(&mut self, other: T, policy: &P) -> MergeOutcome {
        self.merge_with_policy_reporting(other, policy)
    }
}

// Bridge implementation: DeepMerge -> DeepMergeFrom for references (requires Clone)
impl<T: DeepMerge<P> + Clone, P: Policy> DeepMergeFrom<&T, P> for T {
    fn merge_from_with_policy(&mut self, other: &T, policy: &P) {
        self.merge_ref(other, policy);
    }
    
    fn merge_from_with_policy_reporting(&mut self, other: &T, policy: &P) -> MergeOutcome {
        self.merge_ref_reporting(other, policy)
    }
}