tier 0.1.7

Rust configuration library for layered TOML, env, and CLI settings
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
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::{self, Display, Formatter};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use crate::ConfigError;
use crate::report::{canonicalize_path_with_aliases, normalize_path, path_matches_pattern};

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Structured metadata describing configuration fields.
///
/// `ConfigMetadata` is the manual metadata API behind `tier`'s higher-level
/// derive support. It can describe:
///
/// - field-level behavior such as env names, aliases, secret paths, examples,
///   merge policies, and declared validation rules
/// - cross-field validation checks such as mutually exclusive or required-if
///   relationships
///
/// # Examples
///
/// ```
/// use tier::{ConfigMetadata, FieldMetadata};
///
/// let metadata = ConfigMetadata::from_fields([
///     FieldMetadata::new("db.url").env("DATABASE_URL"),
///     FieldMetadata::new("db.password").secret(),
/// ])
/// .required_with("tls.enabled", ["tls.cert", "tls.key"]);
///
/// assert_eq!(
///     metadata
///         .env_overrides()
///         .expect("valid metadata")
///         .get("DATABASE_URL")
///         .map(String::as_str),
///     Some("db.url")
/// );
/// assert_eq!(metadata.secret_paths(), vec!["db.password".to_owned()]);
/// assert_eq!(metadata.checks().len(), 1);
/// ```
pub struct ConfigMetadata {
    fields: Vec<FieldMetadata>,
    checks: Vec<ValidationCheck>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct MetadataMatchScore {
    segment_count: usize,
    specificity: usize,
    positional_specificity: Vec<bool>,
}

impl ConfigMetadata {
    /// Creates an empty metadata set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates metadata from a list of field entries.
    #[must_use]
    pub fn from_fields<I>(fields: I) -> Self
    where
        I: IntoIterator<Item = FieldMetadata>,
    {
        let mut metadata = Self::default();
        metadata.extend_fields(fields);
        metadata
    }

    /// Returns all merged field metadata entries.
    #[must_use]
    pub fn fields(&self) -> &[FieldMetadata] {
        &self.fields
    }

    /// Returns all normalized cross-field validation checks.
    #[must_use]
    pub fn checks(&self) -> &[ValidationCheck] {
        &self.checks
    }

    /// Returns the metadata entry for a normalized configuration path or alias.
    #[must_use]
    pub fn field(&self, path: &str) -> Option<&FieldMetadata> {
        let normalized = normalize_path(path);
        let mut best = None::<(MetadataMatchScore, &FieldMetadata)>;
        for field in &self.fields {
            for candidate in
                std::iter::once(field.path.as_str()).chain(field.aliases.iter().map(String::as_str))
            {
                let Some(score) = metadata_match_score(&normalized, candidate) else {
                    continue;
                };

                match &mut best {
                    Some((best_score, best_field)) if score > *best_score => {
                        *best_score = score;
                        *best_field = field;
                    }
                    None => best = Some((score, field)),
                    _ => {}
                }
            }
        }

        best.map(|(_, field)| field)
    }

    /// Returns metadata entries keyed by normalized path.
    #[must_use]
    pub fn fields_by_path(&self) -> BTreeMap<String, FieldMetadata> {
        self.fields
            .iter()
            .cloned()
            .map(|field| (field.path.clone(), field))
            .collect()
    }

    /// Adds a field metadata entry and merges duplicates by path.
    pub fn push(&mut self, field: FieldMetadata) {
        self.fields.push(field);
        self.normalize();
    }

    /// Extends the metadata with additional field entries.
    pub fn extend_fields<I>(&mut self, fields: I)
    where
        I: IntoIterator<Item = FieldMetadata>,
    {
        self.fields.extend(fields);
        self.normalize();
    }

    /// Extends the metadata with another metadata set.
    pub fn extend(&mut self, other: Self) {
        self.fields.extend(other.fields);
        self.checks.extend(other.checks);
        self.normalize();
    }

    /// Adds a cross-field validation check.
    pub fn push_check(&mut self, check: ValidationCheck) {
        self.checks.push(check);
        self.normalize();
    }

    /// Extends the metadata with additional cross-field validation checks.
    pub fn extend_checks<I>(&mut self, checks: I)
    where
        I: IntoIterator<Item = ValidationCheck>,
    {
        self.checks.extend(checks);
        self.normalize();
    }

    /// Adds a cross-field validation check in builder style.
    #[must_use]
    pub fn check(mut self, check: ValidationCheck) -> Self {
        self.push_check(check);
        self
    }

    /// Requires that at least one of the given paths is configured.
    #[must_use]
    pub fn at_least_one_of<I, S>(self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.check(ValidationCheck::AtLeastOneOf {
            paths: paths.into_iter().map(Into::into).collect(),
        })
    }

    /// Requires that exactly one of the given paths is configured.
    #[must_use]
    pub fn exactly_one_of<I, S>(self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.check(ValidationCheck::ExactlyOneOf {
            paths: paths.into_iter().map(Into::into).collect(),
        })
    }

    /// Requires that at most one of the given paths is configured.
    #[must_use]
    pub fn mutually_exclusive<I, S>(self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.check(ValidationCheck::MutuallyExclusive {
            paths: paths.into_iter().map(Into::into).collect(),
        })
    }

    /// Requires one or more paths whenever `path` is configured.
    #[must_use]
    pub fn required_with<I, S>(self, path: impl Into<String>, requires: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.check(ValidationCheck::RequiredWith {
            path: path.into(),
            requires: requires.into_iter().map(Into::into).collect(),
        })
    }

    /// Requires one or more paths whenever `path` equals `equals`.
    #[must_use]
    pub fn required_if<I, S, V>(self, path: impl Into<String>, equals: V, requires: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
        V: Into<ValidationValue>,
    {
        self.check(ValidationCheck::RequiredIf {
            path: path.into(),
            equals: equals.into(),
            requires: requires.into_iter().map(Into::into).collect(),
        })
    }

    /// Returns all normalized secret paths.
    #[must_use]
    pub fn secret_paths(&self) -> Vec<String> {
        self.fields
            .iter()
            .filter(|field| field.secret)
            .map(|field| field.path.clone())
            .collect()
    }

    /// Returns explicit environment variable name overrides keyed by env name.
    pub fn env_overrides(&self) -> Result<BTreeMap<String, String>, ConfigError> {
        let mut envs = BTreeMap::new();
        for field in &self.fields {
            let Some(env) = &field.env else {
                continue;
            };
            if field.path.split('.').any(|segment| segment == "*") {
                return Err(ConfigError::MetadataInvalid {
                    path: field.path.clone(),
                    message: "explicit environment variable names cannot target wildcard paths"
                        .to_owned(),
                });
            }
            if let Some(first_path) = envs.insert(env.clone(), field.path.clone())
                && first_path != field.path
            {
                return Err(ConfigError::MetadataConflict {
                    kind: "environment variable",
                    name: env.clone(),
                    first_path,
                    second_path: field.path.clone(),
                });
            }
        }
        Ok(envs)
    }

    /// Returns explicit path aliases keyed by alias path.
    pub fn alias_overrides(&self) -> Result<BTreeMap<String, String>, ConfigError> {
        let mut aliases = BTreeMap::<String, String>::new();
        let canonical_paths = self
            .fields
            .iter()
            .map(|field| field.path.clone())
            .collect::<BTreeSet<_>>();

        for field in &self.fields {
            for alias in &field.aliases {
                if !alias_mapping_is_lossless(alias, &field.path) {
                    return Err(ConfigError::MetadataInvalid {
                        path: alias.clone(),
                        message: format!(
                            "alias `{alias}` must preserve wildcard positions and cannot be deeper than canonical path `{}`",
                            field.path
                        ),
                    });
                }
                if canonical_paths.contains(alias) && alias != &field.path {
                    return Err(ConfigError::MetadataConflict {
                        kind: "alias",
                        name: alias.clone(),
                        first_path: alias.clone(),
                        second_path: field.path.clone(),
                    });
                }
                if let Some(first_path) = aliases.get(alias)
                    && first_path != &field.path
                {
                    return Err(ConfigError::MetadataConflict {
                        kind: "alias",
                        name: alias.clone(),
                        first_path: first_path.clone(),
                        second_path: field.path.clone(),
                    });
                }
                if let Some((other_alias, sample_path)) =
                    aliases.iter().find_map(|(other_alias, other_canonical)| {
                        alias_patterns_are_ambiguous(
                            alias,
                            &field.path,
                            other_alias,
                            other_canonical,
                        )
                        .then(|| {
                            (
                                other_alias.clone(),
                                alias_overlap_sample_path(alias, other_alias),
                            )
                        })
                    })
                {
                    return Err(ConfigError::MetadataInvalid {
                        path: alias.clone(),
                        message: format!(
                            "alias `{alias}` overlaps ambiguously with `{other_alias}` for concrete path `{sample_path}`"
                        ),
                    });
                }
                aliases.insert(alias.clone(), field.path.clone());
            }
        }
        Ok(aliases)
    }

    /// Returns field merge strategies keyed by normalized path.
    #[must_use]
    pub fn merge_strategies(&self) -> BTreeMap<String, MergeStrategy> {
        self.fields
            .iter()
            .map(|field| (field.path.clone(), field.merge))
            .collect()
    }

    /// Resolves the effective merge strategy for a concrete configuration path.
    #[must_use]
    pub fn merge_strategy_for(&self, path: &str) -> Option<MergeStrategy> {
        let normalized = normalize_path(path);
        if normalized.is_empty() {
            return None;
        }

        let mut best = None::<(MetadataMatchScore, MergeStrategy)>;
        for field in &self.fields {
            for candidate in
                std::iter::once(field.path.as_str()).chain(field.aliases.iter().map(String::as_str))
            {
                let Some(score) = metadata_match_score(&normalized, candidate) else {
                    continue;
                };

                match &mut best {
                    Some((best_score, best_merge)) if score > *best_score => {
                        *best_score = score;
                        *best_merge = field.merge;
                    }
                    None => best = Some((score, field.merge)),
                    _ => {}
                }
            }
        }

        best.map(|(_, merge)| merge)
    }

    pub(crate) fn canonicalize_env_decoder_paths(&mut self) -> Result<(), ConfigError> {
        let alias_source_fields = self
            .fields
            .iter()
            .filter(|field| !field.is_env_decoder_only())
            .cloned()
            .collect::<Vec<_>>();
        let aliases = ConfigMetadata {
            fields: alias_source_fields,
            checks: Vec::new(),
        }
        .alias_overrides()?;

        let mut seen = BTreeMap::<String, (String, EnvDecoder)>::new();
        for field in &mut self.fields {
            if !field.is_env_decoder_only() {
                continue;
            }

            let original_path = field.path.clone();
            let canonical = canonicalize_path_with_aliases(&original_path, &aliases);
            let decoder = field
                .env_decode
                .expect("decoder-only fields must have a decoder");
            if let Some((first_path, first_decoder)) = seen.get(&canonical)
                && (first_path != &original_path || *first_decoder != decoder)
            {
                return Err(ConfigError::MetadataConflict {
                    kind: "environment decoder",
                    name: canonical,
                    first_path: first_path.clone(),
                    second_path: original_path,
                });
            }

            seen.insert(canonical.clone(), (original_path, decoder));
            field.path = canonical;
        }

        self.normalize();
        Ok(())
    }

    fn normalize(&mut self) {
        let mut merged = BTreeMap::<String, FieldMetadata>::new();
        for mut field in self.fields.drain(..) {
            field.path = normalize_path(&field.path);
            field.aliases = field
                .aliases
                .into_iter()
                .map(|alias| normalize_path(&alias))
                .filter(|alias| !alias.is_empty() && alias != &field.path)
                .collect();
            field.aliases.sort();
            field.aliases.dedup();
            match merged.get_mut(&field.path) {
                Some(existing) => existing.merge_from(field),
                None => {
                    merged.insert(field.path.clone(), field);
                }
            }
        }
        self.fields = merged.into_values().collect();
        self.checks = normalize_checks(self.checks.drain(..));
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Metadata for a single configuration path.
pub struct FieldMetadata {
    /// Dot-delimited configuration path.
    pub path: String,
    /// Alternate dot-delimited paths accepted by serde during deserialization.
    pub aliases: Vec<String>,
    /// Whether values at this path should be treated as sensitive.
    pub secret: bool,
    /// Exact environment variable name to map to this path.
    pub env: Option<String>,
    /// Decoder applied to environment variable values before deserialization.
    pub env_decode: Option<EnvDecoder>,
    /// Human-readable field documentation.
    pub doc: Option<String>,
    /// Example value rendered in generated docs.
    pub example: Option<String>,
    /// Deprecation note shown in generated docs and runtime warnings.
    pub deprecated: Option<String>,
    /// Whether the field accepts omission via `serde(default)`.
    pub has_default: bool,
    /// Strategy used when merging layered values into this field.
    pub merge: MergeStrategy,
    /// Declarative validation rules applied after normalization.
    pub validations: Vec<ValidationRule>,
}

impl FieldMetadata {
    /// Creates metadata for a single configuration path.
    #[must_use]
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: normalize_path(&path.into()),
            aliases: Vec::new(),
            secret: false,
            env: None,
            env_decode: None,
            doc: None,
            example: None,
            deprecated: None,
            has_default: false,
            merge: MergeStrategy::Merge,
            validations: Vec::new(),
        }
    }

    /// Adds an alternate serde path for this field.
    #[must_use]
    pub fn alias(mut self, alias: impl Into<String>) -> Self {
        self.aliases.push(alias.into());
        self
    }

    /// Marks this path as sensitive.
    #[must_use]
    pub fn secret(mut self) -> Self {
        self.secret = true;
        self
    }

    /// Overrides the environment variable name for this path.
    #[must_use]
    pub fn env(mut self, env: impl Into<String>) -> Self {
        self.env = Some(env.into());
        self
    }

    /// Decodes environment variables for this path with a built-in decoder.
    ///
    /// This can be used together with [`ConfigMetadata`] when metadata is
    /// built manually instead of derived.
    #[must_use]
    pub fn env_decoder(mut self, decoder: EnvDecoder) -> Self {
        self.env_decode = Some(decoder);
        self
    }

    /// Adds human-readable field documentation.
    #[must_use]
    pub fn doc(mut self, doc: impl Into<String>) -> Self {
        self.doc = Some(doc.into());
        self
    }

    /// Adds an example value used by generated docs.
    #[must_use]
    pub fn example(mut self, example: impl Into<String>) -> Self {
        self.example = Some(example.into());
        self
    }

    /// Marks the field as deprecated with an optional note.
    #[must_use]
    pub fn deprecated(mut self, note: impl Into<String>) -> Self {
        self.deprecated = Some(note.into());
        self
    }

    /// Marks the field as accepting omission via `serde(default)`.
    #[must_use]
    pub fn defaulted(mut self) -> Self {
        self.has_default = true;
        self
    }

    /// Sets the field-level merge strategy.
    #[must_use]
    pub fn merge_strategy(mut self, merge: MergeStrategy) -> Self {
        self.merge = merge;
        self
    }

    /// Appends a declarative validation rule.
    #[must_use]
    pub fn validate(mut self, rule: ValidationRule) -> Self {
        self.validations.push(rule);
        self
    }

    /// Requires the field to be non-empty.
    #[must_use]
    pub fn non_empty(self) -> Self {
        self.validate(ValidationRule::NonEmpty)
    }

    /// Requires the field to be greater than or equal to `min`.
    #[must_use]
    pub fn min(self, min: impl Into<ValidationNumber>) -> Self {
        self.validate(ValidationRule::Min(min.into()))
    }

    /// Requires the field to be less than or equal to `max`.
    #[must_use]
    pub fn max(self, max: impl Into<ValidationNumber>) -> Self {
        self.validate(ValidationRule::Max(max.into()))
    }

    /// Requires the field length to be greater than or equal to `min`.
    #[must_use]
    pub fn min_length(self, min: usize) -> Self {
        self.validate(ValidationRule::MinLength(min))
    }

    /// Requires the field length to be less than or equal to `max`.
    #[must_use]
    pub fn max_length(self, max: usize) -> Self {
        self.validate(ValidationRule::MaxLength(max))
    }

    /// Requires the field to match one of the provided scalar values.
    #[must_use]
    pub fn one_of<I, V>(self, values: I) -> Self
    where
        I: IntoIterator<Item = V>,
        V: Into<ValidationValue>,
    {
        self.validate(ValidationRule::OneOf(
            values.into_iter().map(Into::into).collect(),
        ))
    }

    /// Requires the field to be a valid hostname.
    #[must_use]
    pub fn hostname(self) -> Self {
        self.validate(ValidationRule::Hostname)
    }

    /// Requires the field to be a valid IP address.
    #[must_use]
    pub fn ip_addr(self) -> Self {
        self.validate(ValidationRule::IpAddr)
    }

    /// Requires the field to be a valid socket address.
    #[must_use]
    pub fn socket_addr(self) -> Self {
        self.validate(ValidationRule::SocketAddr)
    }

    /// Requires the field to be an absolute filesystem path.
    #[must_use]
    pub fn absolute_path(self) -> Self {
        self.validate(ValidationRule::AbsolutePath)
    }

    fn merge_from(&mut self, other: Self) {
        self.aliases.extend(other.aliases);
        self.aliases.sort();
        self.aliases.dedup();
        self.secret |= other.secret;
        if let Some(env) = other.env {
            self.env = Some(env);
        }
        if let Some(env_decode) = other.env_decode {
            self.env_decode = Some(env_decode);
        }
        if let Some(doc) = other.doc {
            self.doc = Some(doc);
        }
        if let Some(example) = other.example {
            self.example = Some(example);
        }
        if let Some(deprecated) = other.deprecated {
            self.deprecated = Some(deprecated);
        }
        self.has_default |= other.has_default;
        if other.merge != MergeStrategy::Merge || self.merge == MergeStrategy::Merge {
            self.merge = other.merge;
        }
        for rule in other.validations {
            if !self.validations.contains(&rule) {
                self.validations.push(rule);
            }
        }
    }

    fn is_env_decoder_only(&self) -> bool {
        self.env_decode.is_some()
            && self.aliases.is_empty()
            && !self.secret
            && self.env.is_none()
            && self.doc.is_none()
            && self.example.is_none()
            && self.deprecated.is_none()
            && !self.has_default
            && self.merge == MergeStrategy::Merge
            && self.validations.is_empty()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Built-in decoders for structured environment variable values.
///
/// These decoders are intended for operational formats that are common in
/// deployments but inconvenient to express as JSON.
///
/// # Examples
///
/// ```
/// use tier::{ConfigMetadata, EnvDecoder, FieldMetadata};
///
/// let mut metadata = ConfigMetadata::new();
/// metadata.push(FieldMetadata::new("no_proxy").env_decoder(EnvDecoder::Csv));
/// metadata.push(FieldMetadata::new("labels").env_decoder(EnvDecoder::KeyValueMap));
///
/// assert_eq!(metadata.fields().len(), 2);
/// ```
pub enum EnvDecoder {
    /// Comma-separated values such as `a,b,c`.
    Csv,
    /// Platform-native path list syntax such as `PATH`.
    PathList,
    /// Comma-separated `key=value` pairs such as `a=1,b=2`.
    KeyValueMap,
    /// Whitespace-separated values such as `a b c`.
    Whitespace,
}

impl Display for EnvDecoder {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Csv => write!(f, "csv"),
            Self::PathList => write!(f, "path_list"),
            Self::KeyValueMap => write!(f, "key_value_map"),
            Self::Whitespace => write!(f, "whitespace"),
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Strategy applied when multiple layers write to the same configuration path.
pub enum MergeStrategy {
    /// Recursively merge objects and replace non-object values.
    #[default]
    Merge,
    /// Replace the current value at this path with the overlay value.
    Replace,
    /// Append array overlays while still recursively merging nested objects.
    Append,
}

impl Display for MergeStrategy {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Merge => write!(f, "merge"),
            Self::Replace => write!(f, "replace"),
            Self::Append => write!(f, "append"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
/// Numeric bound used by declarative validation rules.
pub enum ValidationNumber {
    /// A finite JSON-compatible number.
    Finite(serde_json::Number),
    /// An invalid non-finite value such as `NaN` or `inf`.
    Invalid(String),
}

impl ValidationNumber {
    /// Returns the numeric value as `f64`, when representable.
    #[must_use]
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Finite(number) => number.as_f64(),
            Self::Invalid(_) => None,
        }
    }

    /// Returns `true` when the bound is a finite JSON-compatible number.
    #[must_use]
    pub fn is_finite(&self) -> bool {
        matches!(self, Self::Finite(_))
    }

    /// Returns the bound rendered as a JSON value.
    #[must_use]
    pub fn as_json_value(&self) -> serde_json::Value {
        match self {
            Self::Finite(number) => serde_json::Value::Number(number.clone()),
            Self::Invalid(value) => serde_json::Value::String(value.clone()),
        }
    }
}

impl Display for ValidationNumber {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Finite(number) => Display::fmt(number, f),
            Self::Invalid(value) => Display::fmt(value, f),
        }
    }
}

impl From<i8> for ValidationNumber {
    fn from(value: i8) -> Self {
        Self::Finite(serde_json::Number::from(value))
    }
}

impl From<i16> for ValidationNumber {
    fn from(value: i16) -> Self {
        Self::Finite(serde_json::Number::from(value))
    }
}

impl From<i32> for ValidationNumber {
    fn from(value: i32) -> Self {
        Self::Finite(serde_json::Number::from(value))
    }
}

impl From<i64> for ValidationNumber {
    fn from(value: i64) -> Self {
        Self::Finite(serde_json::Number::from(value))
    }
}

impl From<isize> for ValidationNumber {
    fn from(value: isize) -> Self {
        Self::Finite(serde_json::Number::from(value as i64))
    }
}

impl From<u8> for ValidationNumber {
    fn from(value: u8) -> Self {
        Self::Finite(serde_json::Number::from(value))
    }
}

impl From<u16> for ValidationNumber {
    fn from(value: u16) -> Self {
        Self::Finite(serde_json::Number::from(value))
    }
}

impl From<u32> for ValidationNumber {
    fn from(value: u32) -> Self {
        Self::Finite(serde_json::Number::from(value))
    }
}

impl From<u64> for ValidationNumber {
    fn from(value: u64) -> Self {
        Self::Finite(serde_json::Number::from(value))
    }
}

impl From<usize> for ValidationNumber {
    fn from(value: usize) -> Self {
        Self::Finite(serde_json::Number::from(value as u64))
    }
}

impl From<f32> for ValidationNumber {
    fn from(value: f32) -> Self {
        match serde_json::Number::from_f64(value as f64) {
            Some(number) => Self::Finite(number),
            None => Self::Invalid(value.to_string()),
        }
    }
}

impl From<f64> for ValidationNumber {
    fn from(value: f64) -> Self {
        match serde_json::Number::from_f64(value) {
            Some(number) => Self::Finite(number),
            None => Self::Invalid(value.to_string()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
/// Scalar value used by declarative validation rules and conditions.
pub struct ValidationValue(pub serde_json::Value);

impl Display for ValidationValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self.0 {
            serde_json::Value::String(value) => write!(f, "{value:?}"),
            value => Display::fmt(value, f),
        }
    }
}

impl From<bool> for ValidationValue {
    fn from(value: bool) -> Self {
        Self(serde_json::Value::Bool(value))
    }
}

impl From<String> for ValidationValue {
    fn from(value: String) -> Self {
        Self(serde_json::Value::String(value))
    }
}

impl From<&str> for ValidationValue {
    fn from(value: &str) -> Self {
        Self(serde_json::Value::String(value.to_owned()))
    }
}

impl From<f32> for ValidationValue {
    fn from(value: f32) -> Self {
        match serde_json::Number::from_f64(value as f64) {
            Some(number) => Self(serde_json::Value::Number(number)),
            None => Self(serde_json::Value::String(value.to_string())),
        }
    }
}

impl From<f64> for ValidationValue {
    fn from(value: f64) -> Self {
        match serde_json::Number::from_f64(value) {
            Some(number) => Self(serde_json::Value::Number(number)),
            None => Self(serde_json::Value::String(value.to_string())),
        }
    }
}

macro_rules! impl_validation_value_from_number {
    ($($ty:ty),* $(,)?) => {
        $(
            impl From<$ty> for ValidationValue {
                fn from(value: $ty) -> Self {
                    Self(serde_json::to_value(value).expect("validation values must serialize"))
                }
            }
        )*
    };
}

impl_validation_value_from_number!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Declarative validation rule applied to a single configuration path.
pub enum ValidationRule {
    /// The field must not be empty.
    NonEmpty,
    /// The field must be greater than or equal to the given numeric bound.
    Min(ValidationNumber),
    /// The field must be less than or equal to the given numeric bound.
    Max(ValidationNumber),
    /// The field length must be at least the given number of units.
    MinLength(usize),
    /// The field length must be at most the given number of units.
    MaxLength(usize),
    /// The field must equal one of the provided scalar values.
    OneOf(Vec<ValidationValue>),
    /// The field must be a valid hostname.
    Hostname,
    /// The field must be a valid IP address.
    IpAddr,
    /// The field must be a valid socket address.
    SocketAddr,
    /// The field must be an absolute filesystem path.
    AbsolutePath,
}

impl ValidationRule {
    /// Returns a stable machine-readable rule identifier.
    #[must_use]
    pub fn code(&self) -> &'static str {
        match self {
            Self::NonEmpty => "non_empty",
            Self::Min(_) => "min",
            Self::Max(_) => "max",
            Self::MinLength(_) => "min_length",
            Self::MaxLength(_) => "max_length",
            Self::OneOf(_) => "one_of",
            Self::Hostname => "hostname",
            Self::IpAddr => "ip_addr",
            Self::SocketAddr => "socket_addr",
            Self::AbsolutePath => "absolute_path",
        }
    }
}

impl Display for ValidationRule {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::NonEmpty => write!(f, "non_empty"),
            Self::Min(value) => write!(f, "min={value}"),
            Self::Max(value) => write!(f, "max={value}"),
            Self::MinLength(value) => write!(f, "min_length={value}"),
            Self::MaxLength(value) => write!(f, "max_length={value}"),
            Self::OneOf(values) => write!(
                f,
                "one_of=[{}]",
                values
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Self::Hostname => write!(f, "hostname"),
            Self::IpAddr => write!(f, "ip_addr"),
            Self::SocketAddr => write!(f, "socket_addr"),
            Self::AbsolutePath => write!(f, "absolute_path"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Cross-field declarative validation applied to the final normalized configuration.
pub enum ValidationCheck {
    /// Requires that at least one of the given paths is configured.
    AtLeastOneOf { paths: Vec<String> },
    /// Requires that exactly one of the given paths is configured.
    ExactlyOneOf { paths: Vec<String> },
    /// Requires that no more than one of the given paths is configured.
    MutuallyExclusive { paths: Vec<String> },
    /// Requires one or more paths whenever `path` is configured.
    RequiredWith { path: String, requires: Vec<String> },
    /// Requires one or more paths whenever `path` equals `equals`.
    RequiredIf {
        /// Path whose value is inspected.
        path: String,
        /// Value that triggers the requirement.
        equals: ValidationValue,
        /// Paths that must be configured when the condition matches.
        requires: Vec<String>,
    },
}

impl ValidationCheck {
    /// Returns a stable machine-readable rule identifier.
    #[must_use]
    pub fn code(&self) -> &'static str {
        match self {
            Self::AtLeastOneOf { .. } => "at_least_one_of",
            Self::ExactlyOneOf { .. } => "exactly_one_of",
            Self::MutuallyExclusive { .. } => "mutually_exclusive",
            Self::RequiredWith { .. } => "required_with",
            Self::RequiredIf { .. } => "required_if",
        }
    }

    fn normalize(self) -> Option<Self> {
        match self {
            Self::AtLeastOneOf { paths } => {
                normalize_path_group(paths).map(|paths| Self::AtLeastOneOf { paths })
            }
            Self::ExactlyOneOf { paths } => {
                normalize_path_group(paths).map(|paths| Self::ExactlyOneOf { paths })
            }
            Self::MutuallyExclusive { paths } => {
                normalize_path_group(paths).map(|paths| Self::MutuallyExclusive { paths })
            }
            Self::RequiredWith { path, requires } => {
                let path = normalize_path(&path);
                let requires = normalize_path_group(requires)?;
                (!path.is_empty()).then_some(Self::RequiredWith { path, requires })
            }
            Self::RequiredIf {
                path,
                equals,
                requires,
            } => {
                let path = normalize_path(&path);
                let requires = normalize_path_group(requires)?;
                (!path.is_empty()).then_some(Self::RequiredIf {
                    path,
                    equals,
                    requires,
                })
            }
        }
    }

    fn prefixed(self, prefix: &str) -> Option<Self> {
        let prefix = normalize_path(prefix);
        if prefix.is_empty() {
            return self.normalize();
        }

        let join = |path: String| {
            if path.is_empty() {
                prefix.clone()
            } else {
                format!("{prefix}.{path}")
            }
        };

        match self {
            Self::AtLeastOneOf { paths } => Some(Self::AtLeastOneOf {
                paths: paths.into_iter().map(join).collect(),
            })
            .and_then(Self::normalize),
            Self::ExactlyOneOf { paths } => Some(Self::ExactlyOneOf {
                paths: paths.into_iter().map(join).collect(),
            })
            .and_then(Self::normalize),
            Self::MutuallyExclusive { paths } => Some(Self::MutuallyExclusive {
                paths: paths.into_iter().map(join).collect(),
            })
            .and_then(Self::normalize),
            Self::RequiredWith { path, requires } => Some(Self::RequiredWith {
                path: join(path),
                requires: requires.into_iter().map(join).collect(),
            })
            .and_then(Self::normalize),
            Self::RequiredIf {
                path,
                equals,
                requires,
            } => Some(Self::RequiredIf {
                path: join(path),
                equals,
                requires: requires.into_iter().map(join).collect(),
            })
            .and_then(Self::normalize),
        }
    }
}

impl Display for ValidationCheck {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::AtLeastOneOf { paths } => {
                write!(f, "at_least_one_of({})", paths.join(", "))
            }
            Self::ExactlyOneOf { paths } => {
                write!(f, "exactly_one_of({})", paths.join(", "))
            }
            Self::MutuallyExclusive { paths } => {
                write!(f, "mutually_exclusive({})", paths.join(", "))
            }
            Self::RequiredWith { path, requires } => {
                write!(f, "required_with({path} -> {})", requires.join(", "))
            }
            Self::RequiredIf {
                path,
                equals,
                requires,
            } => write!(
                f,
                "required_if({path} == {equals} -> {})",
                requires.join(", ")
            ),
        }
    }
}

/// Metadata produced for a configuration type.
pub trait TierMetadata {
    /// Returns metadata for the configuration type.
    #[must_use]
    fn metadata() -> ConfigMetadata {
        ConfigMetadata::default()
    }

    /// Returns configuration paths that should be treated as secrets.
    #[must_use]
    fn secret_paths() -> Vec<String> {
        Self::metadata().secret_paths()
    }
}

impl<T> TierMetadata for super::Secret<T> {
    fn metadata() -> ConfigMetadata {
        ConfigMetadata::from_fields([FieldMetadata::new("").secret()])
    }
}
impl TierMetadata for String {}
impl TierMetadata for bool {}
impl TierMetadata for char {}
impl TierMetadata for u8 {}
impl TierMetadata for u16 {}
impl TierMetadata for u32 {}
impl TierMetadata for u64 {}
impl TierMetadata for u128 {}
impl TierMetadata for usize {}
impl TierMetadata for i8 {}
impl TierMetadata for i16 {}
impl TierMetadata for i32 {}
impl TierMetadata for i64 {}
impl TierMetadata for i128 {}
impl TierMetadata for isize {}
impl TierMetadata for f32 {}
impl TierMetadata for f64 {}
impl TierMetadata for Duration {}
impl TierMetadata for SystemTime {}
impl TierMetadata for PathBuf {}
impl TierMetadata for IpAddr {}
impl TierMetadata for Ipv4Addr {}
impl TierMetadata for Ipv6Addr {}
impl TierMetadata for SocketAddr {}
impl TierMetadata for SocketAddrV4 {}
impl TierMetadata for SocketAddrV6 {}

impl<T> TierMetadata for Option<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        T::metadata()
    }
}

impl<T> TierMetadata for Vec<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), T::metadata())
    }
}

impl<T, const N: usize> TierMetadata for [T; N]
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), T::metadata())
    }
}

impl<T> TierMetadata for BTreeSet<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), T::metadata())
    }
}

impl<T> TierMetadata for HashSet<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), T::metadata())
    }
}

impl<K, V> TierMetadata for BTreeMap<K, V>
where
    V: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), V::metadata())
    }
}

impl<K, V, S> TierMetadata for HashMap<K, V, S>
where
    V: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        prefixed_metadata("*", Vec::new(), V::metadata())
    }
}

impl<T> TierMetadata for Box<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        T::metadata()
    }
}

impl<T> TierMetadata for Arc<T>
where
    T: TierMetadata,
{
    fn metadata() -> ConfigMetadata {
        T::metadata()
    }
}

/// Prefixes child metadata paths with a parent field name.
#[must_use]
pub fn prefixed_metadata(
    prefix: &str,
    prefix_aliases: Vec<String>,
    metadata: ConfigMetadata,
) -> ConfigMetadata {
    let prefix = normalize_path(prefix);
    if prefix.is_empty() {
        return metadata;
    }

    let mut prefixed = ConfigMetadata::from_fields(metadata.fields.into_iter().map(|field| {
        let canonical_suffix = field.path.clone();
        let alias_suffixes = if field.aliases.is_empty() {
            vec![canonical_suffix.clone()]
        } else {
            let mut suffixes = vec![canonical_suffix.clone()];
            suffixes.extend(field.aliases.iter().cloned());
            suffixes
        };

        let path = if canonical_suffix.is_empty() {
            prefix.clone()
        } else {
            format!("{prefix}.{}", canonical_suffix)
        };

        let mut aliases = field
            .aliases
            .into_iter()
            .map(|alias| {
                if alias.is_empty() {
                    prefix.clone()
                } else {
                    format!("{prefix}.{}", alias)
                }
            })
            .collect::<Vec<_>>();

        for prefix_alias in &prefix_aliases {
            if canonical_suffix.is_empty() {
                aliases.push(prefix_alias.clone());
                continue;
            }
            for suffix in &alias_suffixes {
                aliases.push(format!("{prefix_alias}.{suffix}"));
            }
        }

        FieldMetadata {
            path,
            aliases,
            ..field
        }
    }));
    prefixed.extend_checks(
        metadata
            .checks
            .into_iter()
            .filter_map(|check| check.prefixed(&prefix)),
    );
    prefixed
}

impl IntoIterator for ConfigMetadata {
    type Item = FieldMetadata;
    type IntoIter = std::vec::IntoIter<FieldMetadata>;

    fn into_iter(self) -> Self::IntoIter {
        self.fields.into_iter()
    }
}

fn normalize_checks<I>(checks: I) -> Vec<ValidationCheck>
where
    I: IntoIterator<Item = ValidationCheck>,
{
    let mut normalized = Vec::new();
    for check in checks {
        let Some(check) = check.normalize() else {
            continue;
        };
        if !normalized.contains(&check) {
            normalized.push(check);
        }
    }
    normalized
}

fn normalize_path_group<I>(paths: I) -> Option<Vec<String>>
where
    I: IntoIterator<Item = String>,
{
    let mut normalized = Vec::new();
    for path in paths {
        let path = normalize_path(&path);
        if path.is_empty() || normalized.contains(&path) {
            continue;
        }
        normalized.push(path);
    }
    (!normalized.is_empty()).then_some(normalized)
}

fn metadata_match_score(path: &str, candidate: &str) -> Option<MetadataMatchScore> {
    if candidate != path && !path_matches_pattern(path, candidate) {
        return None;
    }

    let segments = candidate
        .split('.')
        .filter(|segment| !segment.is_empty())
        .collect::<Vec<_>>();
    let positional_specificity = segments
        .iter()
        .map(|segment| *segment != "*")
        .collect::<Vec<_>>();
    let specificity = positional_specificity
        .iter()
        .filter(|segment| **segment)
        .count();
    Some(MetadataMatchScore {
        segment_count: segments.len(),
        specificity,
        positional_specificity,
    })
}

fn alias_mapping_is_lossless(alias: &str, canonical: &str) -> bool {
    let alias_segments = path_segments(alias);
    let canonical_segments = path_segments(canonical);
    if canonical_segments.len() < alias_segments.len() {
        return false;
    }

    for index in 0..alias_segments.len() {
        let alias_wildcard = alias_segments[index] == "*";
        let canonical_wildcard = canonical_segments[index] == "*";
        if alias_wildcard != canonical_wildcard {
            return false;
        }
    }

    !canonical_segments[alias_segments.len()..].contains(&"*")
}

fn alias_patterns_are_ambiguous(
    left_alias: &str,
    left_canonical: &str,
    right_alias: &str,
    right_canonical: &str,
) -> bool {
    if alias_rank(left_alias) != alias_rank(right_alias) {
        return false;
    }

    let left_segments = path_segments(left_alias);
    let right_segments = path_segments(right_alias);
    if left_segments.len() != right_segments.len() {
        return false;
    }

    if !left_segments
        .iter()
        .zip(right_segments.iter())
        .all(|(left, right)| *left == "*" || *right == "*" || left == right)
    {
        return false;
    }

    let sample_path = alias_overlap_sample_path(left_alias, right_alias);
    rewrite_alias_sample(&sample_path, left_alias, left_canonical)
        != rewrite_alias_sample(&sample_path, right_alias, right_canonical)
}

fn alias_rank(alias: &str) -> (usize, usize) {
    let segments = path_segments(alias);
    let specificity = segments.iter().filter(|segment| **segment != "*").count();
    (segments.len(), specificity)
}

fn alias_overlap_sample_path(left: &str, right: &str) -> String {
    path_segments(left)
        .into_iter()
        .zip(path_segments(right))
        .map(|(left, right)| {
            if left == "*" && right == "*" {
                "item".to_owned()
            } else if left == "*" {
                right.to_owned()
            } else {
                left.to_owned()
            }
        })
        .collect::<Vec<_>>()
        .join(".")
}

fn rewrite_alias_sample(path: &str, alias: &str, canonical: &str) -> String {
    let concrete_segments = path_segments(path);
    let alias_segments = path_segments(alias);
    let canonical_segments = path_segments(canonical);

    let mut rewritten = canonical_segments
        .iter()
        .enumerate()
        .map(|(index, segment)| {
            if *segment == "*" && alias_segments.get(index) == Some(&"*") {
                concrete_segments[index].to_owned()
            } else {
                (*segment).to_owned()
            }
        })
        .collect::<Vec<_>>();
    rewritten.extend(
        concrete_segments[alias_segments.len()..]
            .iter()
            .map(|segment| (*segment).to_owned()),
    );
    normalize_path(&rewritten.join("."))
}

fn path_segments(path: &str) -> Vec<&str> {
    path.split('.')
        .filter(|segment| !segment.is_empty())
        .collect()
}