rust-config-tree 0.1.5

Recursive include tree utilities for layered configuration files.
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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
//! High-level `confique` integration and config-template rendering.
//!
//! This module loads `.env` values, builds a Figment runtime source graph,
//! extracts it into a `confique` schema for defaults and validation, renders
//! example templates that mirror the same include tree, and writes JSON Schema
//! files that editors can use for completion and validation. YAML templates can
//! also be split across nested schema sections.

use std::{
    collections::{BTreeSet, HashMap},
    ffi::OsStr,
    fs,
    path::Component,
    path::{Path, PathBuf},
    sync::Arc,
};

use confique::{
    Config, FileFormat, Layer,
    meta::{Expr, FieldKind, LeafKind, MapKey, Meta},
};
use figment::{
    Figment, Metadata, Profile, Provider, Source,
    providers::{Env, Format, Json, Toml, Yaml},
    value::{Dict, Map, Uncased},
};
use schemars::{JsonSchema, generate::SchemaSettings};
use serde_json::Value;
use tracing::trace;

use crate::{
    ConfigError, ConfigSource, ConfigTree, ConfigTreeOptions, IncludeOrder, absolutize_lexical,
    collect_template_targets, normalize_lexical, select_template_source,
};

/// Result type used by the high-level configuration API.
///
/// The error type is [`ConfigError`].
pub type ConfigResult<T> = std::result::Result<T, ConfigError>;

/// A `confique` schema that can expose recursive include paths and template
/// section layout.
///
/// Implement this trait for the same type that derives `confique::Config`.
/// `include_paths` receives a partially loaded layer so the crate can discover
/// child config files before the final schema is merged.
pub trait ConfigSchema: Config + Sized {
    /// Returns include paths declared by a loaded config layer.
    ///
    /// Relative paths are resolved from the file that declared them. Empty paths
    /// are rejected before traversal continues.
    ///
    /// # Arguments
    ///
    /// - `layer`: Partially loaded `confique` layer for one config file.
    ///
    /// # Returns
    ///
    /// Returns include paths declared by `layer`.
    fn include_paths(layer: &<Self as Config>::Layer) -> Vec<PathBuf>;

    /// Overrides the generated template file path for a nested section.
    ///
    /// By default, top-level sections are generated as `config/<field>.yaml`
    /// and nested sections as children of their parent section file stem, e.g.
    /// `config/trading/risk.yaml`.
    ///
    /// # Arguments
    ///
    /// - `section_path`: Path of nested schema field names from the root schema
    ///   to the section being rendered.
    ///
    /// # Returns
    ///
    /// Returns `Some(path)` to override the generated file path, or `None` to
    /// use the default section path.
    fn template_path_for_section(section_path: &[&str]) -> Option<PathBuf> {
        let _ = section_path;
        None
    }
}

/// File format used when loading config files or rendering templates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigFormat {
    /// YAML format, selected for `.yaml`, `.yml`, unknown extensions, and paths
    /// without an extension.
    Yaml,
    /// TOML format, selected for `.toml`.
    Toml,
    /// JSON5-compatible format, selected for `.json` and `.json5`.
    Json,
}

impl ConfigFormat {
    /// Infers the config format from a path extension.
    ///
    /// Unknown extensions intentionally fall back to YAML.
    ///
    /// # Arguments
    ///
    /// - `path`: Config or template path whose extension should be inspected.
    ///
    /// # Returns
    ///
    /// Returns the inferred [`ConfigFormat`].
    pub fn from_path(path: impl AsRef<Path>) -> Self {
        match path.as_ref().extension().and_then(OsStr::to_str) {
            Some("toml") => Self::Toml,
            Some("json" | "json5") => Self::Json,
            Some("yaml" | "yml") | Some(_) | None => Self::Yaml,
        }
    }

    /// Converts this format into the `confique` file format used for loading.
    ///
    /// # Returns
    ///
    /// Returns the matching [`FileFormat`] value.
    pub fn as_file_format(self) -> FileFormat {
        match self {
            Self::Yaml => FileFormat::Yaml,
            Self::Toml => FileFormat::Toml,
            Self::Json => FileFormat::Json5,
        }
    }
}

/// Generated template content for one output path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigTemplateTarget {
    /// Path that should receive the generated content.
    pub path: PathBuf,
    /// Complete template content to write to `path`.
    pub content: String,
}

/// Generated JSON Schema content for one output path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigSchemaTarget {
    /// Path that should receive the generated schema.
    pub path: PathBuf,
    /// Complete JSON Schema content to write to `path`.
    pub content: String,
}

/// Figment provider that maps environment variables declared in `confique`
/// schema metadata onto their exact field paths.
///
/// This provider reads `#[config(env = "...")]` from [`Config::META`] and
/// avoids Figment's delimiter-based environment key splitting. Environment
/// variables such as `APP_DATABASE_POOL_SIZE` can therefore map to a Rust field
/// named `database.pool_size` without treating the single underscores as nested
/// separators.
#[derive(Clone)]
pub struct ConfiqueEnvProvider {
    env: Env,
    path_to_env: Arc<HashMap<String, String>>,
}

impl ConfiqueEnvProvider {
    /// Creates an environment provider for a `confique` schema.
    ///
    /// # Type Parameters
    ///
    /// - `S`: Config schema whose metadata declares environment variable names.
    ///
    /// # Returns
    ///
    /// Returns a provider that emits only environment variables declared by `S`.
    pub fn new<S>() -> Self
    where
        S: Config,
    {
        let mut env_to_path = HashMap::<String, String>::new();
        let mut path_to_env = HashMap::<String, String>::new();

        collect_env_mapping(&S::META, "", &mut env_to_path, &mut path_to_env);

        let env_to_path = Arc::new(env_to_path);
        let path_to_env = Arc::new(path_to_env);
        let map_for_filter = Arc::clone(&env_to_path);

        let env = Env::raw().filter_map(move |env_key| {
            let lookup_key = env_key.as_str().to_ascii_uppercase();

            map_for_filter
                .get(&lookup_key)
                .cloned()
                .map(Uncased::from_owned)
        });

        Self { env, path_to_env }
    }
}

impl Provider for ConfiqueEnvProvider {
    fn metadata(&self) -> Metadata {
        let path_to_env = Arc::clone(&self.path_to_env);

        Metadata::named("environment variable").interpolater(move |_profile, keys| {
            let path = keys.join(".");

            path_to_env.get(&path).cloned().unwrap_or(path)
        })
    }

    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
        self.env.data()
    }
}

/// Loads a complete `confique` schema from a root config path.
///
/// The loader follows recursive include paths exposed by [`ConfigSchema`],
/// resolves relative include paths from the declaring file, detects include
/// cycles, loads the first `.env` file found from the root config directory
/// upward, builds a [`Figment`] from config files and schema-declared
/// environment variables, and then asks `confique` to apply defaults and
/// validation. Existing process environment variables take precedence over
/// values loaded from `.env`.
///
/// # Type Parameters
///
/// - `S`: Config schema type that derives [`Config`] and implements
///   [`ConfigSchema`].
///
/// # Arguments
///
/// - `path`: Root config file path.
///
/// # Returns
///
/// Returns the merged config schema after loading the root file, recursive
/// includes, `.env` values, and environment values.
pub fn load_config<S>(path: impl AsRef<Path>) -> ConfigResult<S>
where
    S: ConfigSchema,
{
    let (config, _) = load_config_with_figment::<S>(path)?;
    Ok(config)
}

/// Loads a config schema and returns the Figment graph used for runtime loading.
///
/// The returned [`Figment`] can be inspected with [`Figment::find_metadata`] to
/// determine which provider supplied a runtime value.
///
/// # Type Parameters
///
/// - `S`: Config schema type that derives [`Config`] and implements
///   [`ConfigSchema`].
///
/// # Arguments
///
/// - `path`: Root config file path.
///
/// # Returns
///
/// Returns the merged config schema and its runtime Figment source graph.
pub fn load_config_with_figment<S>(path: impl AsRef<Path>) -> ConfigResult<(S, Figment)>
where
    S: ConfigSchema,
{
    let figment = build_config_figment::<S>(path)?;
    let config = load_config_from_figment::<S>(&figment)?;

    Ok((config, figment))
}

/// Builds the Figment runtime source graph for a config tree.
///
/// Config files are merged in include order, then environment variables
/// declared by [`ConfiqueEnvProvider`] are merged with higher priority.
///
/// # Type Parameters
///
/// - `S`: Config schema type used to discover includes and environment names.
///
/// # Arguments
///
/// - `path`: Root config file path.
///
/// # Returns
///
/// Returns a Figment source graph with file and environment providers.
pub fn build_config_figment<S>(path: impl AsRef<Path>) -> ConfigResult<Figment>
where
    S: ConfigSchema,
{
    let path = path.as_ref();
    load_dotenv_for_path(path)?;

    let tree = load_layer_tree::<S>(path)?;
    let mut figment = Figment::new();

    for node in tree.nodes().iter().rev() {
        figment = merge_file_provider(figment, node.path());
    }

    Ok(figment.merge(ConfiqueEnvProvider::new::<S>()))
}

/// Extracts and validates a config schema from a Figment source graph.
///
/// Figment supplies runtime values. `confique` supplies code defaults and final
/// validation.
///
/// # Type Parameters
///
/// - `S`: Config schema type to extract and validate.
///
/// # Arguments
///
/// - `figment`: Runtime source graph.
///
/// # Returns
///
/// Returns the final config schema.
pub fn load_config_from_figment<S>(figment: &Figment) -> ConfigResult<S>
where
    S: ConfigSchema,
{
    let runtime_layer: <S as Config>::Layer = figment.extract()?;
    let config = S::from_layer(runtime_layer.with_fallback(S::Layer::default_values()))?;

    trace_config_sources::<S>(figment);

    Ok(config)
}

/// Loads one config layer from disk using the format inferred from the path.
///
/// # Type Parameters
///
/// - `S`: Config schema type whose intermediate `confique` layer should be
///   loaded.
///
/// # Arguments
///
/// - `path`: Config file path to load.
///
/// # Returns
///
/// Returns the loaded `confique` layer for `S`.
pub fn load_layer<S>(path: &Path) -> ConfigResult<<S as Config>::Layer>
where
    S: ConfigSchema,
{
    Ok(figment_for_file(path).extract()?)
}

fn load_layer_tree<S>(path: &Path) -> ConfigResult<ConfigTree<<S as Config>::Layer>>
where
    S: ConfigSchema,
{
    Ok(ConfigTreeOptions::default()
        .include_order(IncludeOrder::Reverse)
        .load(
            path,
            |path| -> ConfigResult<ConfigSource<<S as Config>::Layer>> {
                let layer = load_layer::<S>(path)?;
                let include_paths = S::include_paths(&layer);
                Ok(ConfigSource::new(layer, include_paths))
            },
        )?)
}

fn merge_file_provider(figment: Figment, path: &Path) -> Figment {
    match ConfigFormat::from_path(path) {
        ConfigFormat::Yaml => figment.merge(Yaml::file_exact(path)),
        ConfigFormat::Toml => figment.merge(Toml::file_exact(path)),
        ConfigFormat::Json => figment.merge(Json::file_exact(path)),
    }
}

fn figment_for_file(path: &Path) -> Figment {
    merge_file_provider(Figment::new(), path)
}

fn root_config_schema<S>() -> ConfigResult<Value>
where
    S: JsonSchema,
{
    let generator = SchemaSettings::draft07().into_generator();
    let schema = generator.into_root_schema_for::<S>();
    let mut schema = serde_json::to_value(schema)?;
    remove_required_recursively(&mut schema);

    Ok(schema)
}

fn schema_json(schema: &Value) -> ConfigResult<String> {
    let mut json = serde_json::to_string_pretty(schema)?;
    ensure_single_trailing_newline(&mut json);
    Ok(json)
}

fn remove_required_recursively(value: &mut Value) {
    match value {
        Value::Object(object) => {
            object.remove("required");

            for (key, child) in object.iter_mut() {
                if is_schema_map_key(key) {
                    remove_required_from_schema_map(child);
                } else {
                    remove_required_recursively(child);
                }
            }
        }
        Value::Array(items) => {
            for item in items {
                remove_required_recursively(item);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }
}

fn is_schema_map_key(key: &str) -> bool {
    matches!(
        key,
        "$defs" | "definitions" | "properties" | "patternProperties"
    )
}

fn remove_required_from_schema_map(value: &mut Value) {
    match value {
        Value::Object(object) => {
            for schema in object.values_mut() {
                remove_required_recursively(schema);
            }
        }
        _ => remove_required_recursively(value),
    }
}

fn section_schema_for_path(root_schema: &Value, section_path: &[&str]) -> Option<Value> {
    let mut current = root_schema;

    for section in section_path {
        current = current.get("properties")?.get(*section)?;
        current = resolve_schema_reference(root_schema, current).unwrap_or(current);
    }

    Some(standalone_section_schema(root_schema, current))
}

fn resolve_schema_reference<'a>(root_schema: &'a Value, schema: &'a Value) -> Option<&'a Value> {
    if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
        return resolve_json_pointer_ref(root_schema, reference);
    }

    schema
        .get("allOf")
        .and_then(Value::as_array)
        .and_then(|schemas| schemas.first())
        .and_then(|schema| schema.get("$ref"))
        .and_then(Value::as_str)
        .and_then(|reference| resolve_json_pointer_ref(root_schema, reference))
}

fn resolve_json_pointer_ref<'a>(root_schema: &'a Value, reference: &str) -> Option<&'a Value> {
    let pointer = reference.strip_prefix('#')?;
    root_schema.pointer(pointer)
}

fn standalone_section_schema(root_schema: &Value, section_schema: &Value) -> Value {
    let mut section_schema = section_schema.clone();
    let Some(object) = section_schema.as_object_mut() else {
        return section_schema;
    };

    if let Some(schema_uri) = root_schema.get("$schema") {
        object
            .entry("$schema".to_owned())
            .or_insert_with(|| schema_uri.clone());
    }

    if let Some(definitions) = root_schema.get("definitions") {
        object
            .entry("definitions".to_owned())
            .or_insert_with(|| definitions.clone());
    }

    if let Some(defs) = root_schema.get("$defs") {
        object
            .entry("$defs".to_owned())
            .or_insert_with(|| defs.clone());
    }

    section_schema
}

fn schema_path_for_section(root_schema_path: &Path, section_path: &[&str]) -> PathBuf {
    let Some((last, parents)) = section_path.split_last() else {
        return root_schema_path.to_path_buf();
    };

    let mut path = root_schema_path
        .parent()
        .unwrap_or_else(|| Path::new("."))
        .to_path_buf();

    for parent in parents {
        path.push(*parent);
    }

    path.push(format!("{}.schema.json", *last));
    path
}

fn schema_for_output_path<S>(
    full_schema: &Value,
    section_path: &[&'static str],
) -> ConfigResult<Value>
where
    S: ConfigSchema,
{
    let mut schema = if section_path.is_empty() {
        full_schema.clone()
    } else {
        section_schema_for_path(full_schema, section_path).ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "failed to extract JSON Schema for config section {}",
                    section_path.join(".")
                ),
            )
        })?
    };

    remove_child_section_properties::<S>(&mut schema, section_path);
    prune_unused_schema_maps(&mut schema);

    Ok(schema)
}

fn remove_child_section_properties<S>(schema: &mut Value, section_path: &[&'static str])
where
    S: ConfigSchema,
{
    let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
        return;
    };

    for child_section_path in immediate_child_section_paths(&S::META, section_path) {
        if let Some(child_name) = child_section_path.last() {
            properties.remove(*child_name);
        }
    }
}

fn prune_unused_schema_maps(schema: &mut Value) {
    let mut definitions = BTreeSet::new();
    let mut defs = BTreeSet::new();

    collect_schema_refs(schema, false, &mut definitions, &mut defs);

    loop {
        let previous_len = definitions.len() + defs.len();
        collect_transitive_schema_refs(schema, &mut definitions, &mut defs);

        if definitions.len() + defs.len() == previous_len {
            break;
        }
    }

    retain_schema_map(schema, "definitions", &definitions);
    retain_schema_map(schema, "$defs", &defs);
}

fn collect_transitive_schema_refs(
    schema: &Value,
    definitions: &mut BTreeSet<String>,
    defs: &mut BTreeSet<String>,
) {
    let current_definitions = definitions.clone();
    let current_defs = defs.clone();
    let mut referenced_definitions = BTreeSet::new();
    let mut referenced_defs = BTreeSet::new();

    if let Some(schema_map) = schema.get("definitions").and_then(Value::as_object) {
        for name in &current_definitions {
            if let Some(schema) = schema_map.get(name) {
                collect_schema_refs(
                    schema,
                    true,
                    &mut referenced_definitions,
                    &mut referenced_defs,
                );
            }
        }
    }

    if let Some(schema_map) = schema.get("$defs").and_then(Value::as_object) {
        for name in &current_defs {
            if let Some(schema) = schema_map.get(name) {
                collect_schema_refs(
                    schema,
                    true,
                    &mut referenced_definitions,
                    &mut referenced_defs,
                );
            }
        }
    }

    definitions.extend(referenced_definitions);
    defs.extend(referenced_defs);
}

fn collect_schema_refs(
    value: &Value,
    include_schema_maps: bool,
    definitions: &mut BTreeSet<String>,
    defs: &mut BTreeSet<String>,
) {
    match value {
        Value::Object(object) => {
            if let Some(reference) = object.get("$ref").and_then(Value::as_str) {
                collect_schema_ref(reference, definitions, defs);
            }

            for (key, child) in object {
                if !include_schema_maps && matches!(key.as_str(), "definitions" | "$defs") {
                    continue;
                }

                collect_schema_refs(child, include_schema_maps, definitions, defs);
            }
        }
        Value::Array(items) => {
            for item in items {
                collect_schema_refs(item, include_schema_maps, definitions, defs);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }
}

fn collect_schema_ref(
    reference: &str,
    definitions: &mut BTreeSet<String>,
    defs: &mut BTreeSet<String>,
) {
    if let Some(name) = schema_ref_name(reference, "#/definitions/") {
        definitions.insert(name);
    } else if let Some(name) = schema_ref_name(reference, "#/$defs/") {
        defs.insert(name);
    }
}

fn schema_ref_name(reference: &str, prefix: &str) -> Option<String> {
    let name = reference.strip_prefix(prefix)?.split('/').next()?;
    Some(decode_json_pointer_token(name))
}

fn decode_json_pointer_token(token: &str) -> String {
    token.replace("~1", "/").replace("~0", "~")
}

fn retain_schema_map(schema: &mut Value, key: &str, used_names: &BTreeSet<String>) {
    let Some(object) = schema.as_object_mut() else {
        return;
    };

    let Some(schema_map) = object.get_mut(key).and_then(Value::as_object_mut) else {
        return;
    };

    schema_map.retain(|name, _| used_names.contains(name));

    if schema_map.is_empty() {
        object.remove(key);
    }
}

/// Writes a Draft 7 JSON Schema for the root config type.
///
/// The same generated schema can be referenced from TOML, YAML, and JSON
/// configuration files. TOML and YAML templates can bind it with editor
/// directives. JSON files should usually be bound through editor settings
/// rather than a runtime `$schema` field. Generated schemas omit JSON Schema
/// `required` constraints so editors provide completion without requiring every
/// config field to exist in each partial config file.
///
/// # Type Parameters
///
/// - `S`: Config schema type that derives [`JsonSchema`].
///
/// # Arguments
///
/// - `output_path`: Destination path for the generated JSON Schema.
///
/// # Returns
///
/// Returns `Ok(())` after the schema file has been written.
pub fn write_config_schema<S>(output_path: impl AsRef<Path>) -> ConfigResult<()>
where
    S: JsonSchema,
{
    let schema = root_config_schema::<S>()?;
    let json = schema_json(&schema)?;

    write_template(output_path.as_ref(), &json)
}

/// Collects the root schema and section schemas for a config type.
///
/// The root schema is written to `output_path`. Nested `confique` sections are
/// written next to it as `<section>.schema.json`; deeper sections are nested in
/// matching directories, for example `schemas/outer/inner.schema.json`. Each
/// generated schema contains only the fields for its own template file; child
/// section fields are omitted and completed by their own section schemas.
///
/// # Type Parameters
///
/// - `S`: Config schema type that derives [`JsonSchema`] and exposes section
///   metadata through [`ConfigSchema`].
///
/// # Arguments
///
/// - `output_path`: Destination path for the root JSON Schema.
///
/// # Returns
///
/// Returns all generated schema targets in traversal order.
pub fn config_schema_targets_for_path<S>(
    output_path: impl AsRef<Path>,
) -> ConfigResult<Vec<ConfigSchemaTarget>>
where
    S: ConfigSchema + JsonSchema,
{
    let output_path = output_path.as_ref();
    let full_schema = root_config_schema::<S>()?;
    let root_schema = schema_for_output_path::<S>(&full_schema, &[])?;
    let mut targets = vec![ConfigSchemaTarget {
        path: output_path.to_path_buf(),
        content: schema_json(&root_schema)?,
    }];

    for section_path in nested_section_paths(&S::META) {
        let schema_path = schema_path_for_section(output_path, &section_path);
        let section_schema = schema_for_output_path::<S>(&full_schema, &section_path)?;

        targets.push(ConfigSchemaTarget {
            path: schema_path,
            content: schema_json(&section_schema)?,
        });
    }

    Ok(targets)
}

/// Writes the root schema and section schemas for a config type.
///
/// Parent directories are created before each schema is written. Generated
/// schemas omit JSON Schema `required` constraints so they can be used for IDE
/// completion against partial config files. The root schema does not complete
/// nested section fields.
///
/// # Type Parameters
///
/// - `S`: Config schema type that derives [`JsonSchema`] and exposes section
///   metadata through [`ConfigSchema`].
///
/// # Arguments
///
/// - `output_path`: Destination path for the root JSON Schema.
///
/// # Returns
///
/// Returns `Ok(())` after all schema files have been written.
pub fn write_config_schemas<S>(output_path: impl AsRef<Path>) -> ConfigResult<()>
where
    S: ConfigSchema + JsonSchema,
{
    for target in config_schema_targets_for_path::<S>(output_path)? {
        write_template(&target.path, &target.content)?;
    }

    Ok(())
}

/// Renders the default template for one path.
///
/// The template format is inferred from the path extension.
///
/// # Type Parameters
///
/// - `S`: Config schema type used to render the template.
///
/// # Arguments
///
/// - `path`: Output path whose extension selects the template format.
///
/// # Returns
///
/// Returns the generated template content.
pub fn template_for_path<S>(path: impl AsRef<Path>) -> ConfigResult<String>
where
    S: ConfigSchema,
{
    let template = match ConfigFormat::from_path(path.as_ref()) {
        ConfigFormat::Yaml => confique::yaml::template::<S>(yaml_options()),
        ConfigFormat::Toml => confique::toml::template::<S>(toml_options()),
        ConfigFormat::Json => confique::json5::template::<S>(json5_options()),
    };

    Ok(template)
}

/// Collects all template targets that should be generated for a config tree.
///
/// The root template source is selected with [`select_template_source`]. Include
/// paths found in the source tree are mirrored under `output_path` for relative
/// includes. When a source node has no includes, nested `confique` sections are
/// used to derive child template files with paths from
/// [`ConfigSchema::template_path_for_section`].
///
/// # Type Parameters
///
/// - `S`: Config schema type used to discover includes and render templates.
///
/// # Arguments
///
/// - `config_path`: Root config path preferred as the template source when it
///   exists.
/// - `output_path`: Root output path for generated templates.
///
/// # Returns
///
/// Returns all generated template targets in traversal order.
pub fn template_targets_for_paths<S>(
    config_path: impl AsRef<Path>,
    output_path: impl AsRef<Path>,
) -> ConfigResult<Vec<ConfigTemplateTarget>>
where
    S: ConfigSchema,
{
    let output_path = output_path.as_ref();
    let source_path = select_template_source(config_path, output_path);
    let root_source_path = absolutize_lexical(source_path)?;
    let output_base_dir = output_path.parent().unwrap_or_else(|| Path::new("."));

    let template_targets = collect_template_targets(
        &root_source_path,
        output_path,
        |node_source_path| -> ConfigResult<Vec<PathBuf>> {
            let mut include_paths = template_source_include_paths::<S>(node_source_path)?;

            if include_paths.is_empty() {
                include_paths =
                    default_child_include_paths::<S>(&root_source_path, node_source_path);
            }

            Ok(include_paths)
        },
    )?;

    let split_paths = template_targets
        .iter()
        .filter_map(|target| {
            section_path_for_target::<S>(output_base_dir, target.target_path())
                .filter(|section_path| !section_path.is_empty())
        })
        .collect::<Vec<_>>();

    template_targets
        .into_iter()
        .map(|target| {
            let (_, target_path, include_paths) = target.into_parts();
            let section_path =
                section_path_for_target::<S>(output_base_dir, &target_path).unwrap_or_default();
            Ok(ConfigTemplateTarget {
                content: template_for_target::<S>(
                    &target_path,
                    &include_paths,
                    &section_path,
                    &split_paths,
                )?,
                path: target_path,
            })
        })
        .collect()
}

/// Collects template targets and binds TOML/YAML templates to JSON Schemas.
///
/// TOML targets receive a `#:schema` directive. YAML targets receive a YAML
/// Language Server modeline. JSON and JSON5 targets are left unchanged so the
/// runtime configuration is not polluted with a `$schema` field. Root targets
/// bind `schema_path`; nested section targets bind their generated section
/// schema path.
///
/// # Type Parameters
///
/// - `S`: Config schema type used to discover includes and render templates.
///
/// # Arguments
///
/// - `config_path`: Root config path preferred as the template source when it
///   exists.
/// - `output_path`: Root output path for generated templates.
/// - `schema_path`: Root JSON Schema path to reference from root TOML/YAML
///   templates.
///
/// # Returns
///
/// Returns all generated template targets in traversal order.
pub fn template_targets_for_paths_with_schema<S>(
    config_path: impl AsRef<Path>,
    output_path: impl AsRef<Path>,
    schema_path: impl AsRef<Path>,
) -> ConfigResult<Vec<ConfigTemplateTarget>>
where
    S: ConfigSchema,
{
    let output_path = output_path.as_ref();
    let output_base_dir = output_path.parent().unwrap_or_else(|| Path::new("."));
    let schema_path = schema_path.as_ref();

    template_targets_for_paths::<S>(config_path, output_path)?
        .into_iter()
        .map(|mut target| {
            let schema_path =
                schema_path_for_template_target::<S>(output_base_dir, &target.path, schema_path);
            target.content =
                template_with_schema_directive(&target.path, &schema_path, &target.content)?;
            Ok(target)
        })
        .collect()
}

/// Writes all generated config templates for a config tree.
///
/// Parent directories are created before each target is written.
///
/// # Type Parameters
///
/// - `S`: Config schema type used to discover includes and render templates.
///
/// # Arguments
///
/// - `config_path`: Root config path preferred as the template source when it
///   exists.
/// - `output_path`: Root output path for generated templates.
///
/// # Returns
///
/// Returns `Ok(())` after all template files have been written.
pub fn write_config_templates<S>(
    config_path: impl AsRef<Path>,
    output_path: impl AsRef<Path>,
) -> ConfigResult<()>
where
    S: ConfigSchema,
{
    for target in template_targets_for_paths::<S>(config_path, output_path)? {
        write_template(&target.path, &target.content)?;
    }

    Ok(())
}

/// Writes all generated config templates with editor schema bindings.
///
/// TOML targets receive `#:schema <path>`, YAML targets receive
/// `# yaml-language-server: $schema=<path>`, and JSON targets are left
/// unchanged. The schema path is rendered relative to each template file. Root
/// targets bind `schema_path`; nested section targets bind their generated
/// section schema path.
///
/// # Type Parameters
///
/// - `S`: Config schema type used to discover includes and render templates.
///
/// # Arguments
///
/// - `config_path`: Root config path preferred as the template source when it
///   exists.
/// - `output_path`: Root output path for generated templates.
/// - `schema_path`: Root JSON Schema path to reference from root TOML/YAML
///   templates.
///
/// # Returns
///
/// Returns `Ok(())` after all template files have been written.
pub fn write_config_templates_with_schema<S>(
    config_path: impl AsRef<Path>,
    output_path: impl AsRef<Path>,
    schema_path: impl AsRef<Path>,
) -> ConfigResult<()>
where
    S: ConfigSchema,
{
    for target in
        template_targets_for_paths_with_schema::<S>(config_path, output_path, schema_path)?
    {
        write_template(&target.path, &target.content)?;
    }

    Ok(())
}

/// Writes one generated template file, creating parent directories first.
///
/// # Arguments
///
/// - `path`: Destination file path.
/// - `content`: Complete template content to write.
///
/// # Returns
///
/// Returns `Ok(())` after the file has been written.
pub(crate) fn write_template(path: &Path, content: &str) -> ConfigResult<()> {
    if let Some(parent) = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        fs::create_dir_all(parent)?;
    }

    fs::write(path, content)?;
    Ok(())
}

/// Resolves the CLI template output path to a normalized absolute path.
///
/// # Arguments
///
/// - `output`: Optional user-provided output path. When omitted,
///   `config.example.yaml` is used.
///
/// # Returns
///
/// Returns a normalized absolute output path.
pub(crate) fn resolve_config_template_output(output: Option<PathBuf>) -> ConfigResult<PathBuf> {
    let current_dir = std::env::current_dir()?;
    let output = output.unwrap_or_else(|| PathBuf::from("config.example.yaml"));
    let output = if output.is_absolute() {
        output
    } else {
        current_dir.join(output)
    };

    Ok(normalize_lexical(output))
}

fn template_source_include_paths<S>(path: &Path) -> ConfigResult<Vec<PathBuf>>
where
    S: ConfigSchema,
{
    if !path.exists() {
        return Ok(Vec::new());
    }

    match load_layer::<S>(path) {
        Ok(layer) => Ok(S::include_paths(&layer)),
        Err(_) => load_include_paths_only(path),
    }
}

fn load_include_paths_only(path: &Path) -> ConfigResult<Vec<PathBuf>> {
    match figment_for_file(path).extract_inner::<Vec<PathBuf>>("include") {
        Ok(paths) => Ok(paths),
        Err(error) if error.missing() => Ok(Vec::new()),
        Err(error) => Err(error.into()),
    }
}

fn schema_path_for_template_target<S>(
    root_base_dir: &Path,
    target_path: &Path,
    root_schema_path: &Path,
) -> PathBuf
where
    S: ConfigSchema,
{
    section_path_for_target::<S>(root_base_dir, target_path)
        .filter(|section_path| !section_path.is_empty())
        .map(|section_path| schema_path_for_section(root_schema_path, &section_path))
        .unwrap_or_else(|| root_schema_path.to_path_buf())
}

fn template_with_schema_directive(
    template_path: &Path,
    schema_path: &Path,
    content: &str,
) -> ConfigResult<String> {
    let schema_ref = schema_reference_for_path(template_path, schema_path)?;
    let directive = match ConfigFormat::from_path(template_path) {
        ConfigFormat::Yaml => Some(format!("# yaml-language-server: $schema={schema_ref}")),
        ConfigFormat::Toml => Some(format!("#:schema {schema_ref}")),
        ConfigFormat::Json => None,
    };

    let Some(directive) = directive else {
        return Ok(content.to_owned());
    };

    Ok(format!("{directive}\n\n{content}"))
}

fn schema_reference_for_path(template_path: &Path, schema_path: &Path) -> ConfigResult<String> {
    let template_path = absolutize_lexical(template_path)?;
    let schema_path = absolutize_lexical(schema_path)?;
    let template_dir = template_path.parent().unwrap_or_else(|| Path::new("."));
    let relative_path = relative_path_from(&schema_path, template_dir);
    Ok(render_schema_reference(&relative_path))
}

fn relative_path_from(path: &Path, base: &Path) -> PathBuf {
    let path_components = path.components().collect::<Vec<_>>();
    let base_components = base.components().collect::<Vec<_>>();

    let mut common_len = 0;
    while common_len < path_components.len()
        && common_len < base_components.len()
        && path_components[common_len] == base_components[common_len]
    {
        common_len += 1;
    }

    if common_len == 0 {
        return path.to_path_buf();
    }

    let mut relative = PathBuf::new();
    for component in &base_components[common_len..] {
        if matches!(component, Component::Normal(_)) {
            relative.push("..");
        }
    }

    for component in &path_components[common_len..] {
        relative.push(component.as_os_str());
    }

    if relative.as_os_str().is_empty() {
        PathBuf::from(".")
    } else {
        relative
    }
}

fn render_schema_reference(path: &Path) -> String {
    let value = path.to_string_lossy().replace('\\', "/");
    if path.is_absolute() || value.starts_with("../") || value.starts_with("./") {
        value
    } else {
        format!("./{value}")
    }
}

fn template_for_target<S>(
    path: &Path,
    include_paths: &[PathBuf],
    section_path: &[&'static str],
    split_paths: &[Vec<&'static str>],
) -> ConfigResult<String>
where
    S: ConfigSchema,
{
    if ConfigFormat::from_path(path) != ConfigFormat::Yaml || split_paths.is_empty() {
        return template_for_path_with_includes::<S>(path, include_paths);
    }

    Ok(render_yaml_template(
        &S::META,
        include_paths,
        section_path,
        split_paths,
    ))
}

fn default_child_include_paths<S>(root_source_path: &Path, node_source_path: &Path) -> Vec<PathBuf>
where
    S: ConfigSchema,
{
    let root_base_dir = root_source_path.parent().unwrap_or_else(|| Path::new("."));
    let section_path =
        section_path_for_target::<S>(root_base_dir, node_source_path).unwrap_or_default();
    let source_base_dir = node_source_path.parent().unwrap_or_else(|| Path::new("."));

    immediate_child_section_paths(&S::META, &section_path)
        .into_iter()
        .map(|child_section_path| {
            let child_path =
                root_base_dir.join(template_path_for_section::<S>(&child_section_path));
            path_relative_to(&child_path, source_base_dir)
        })
        .collect()
}

fn collect_env_mapping(
    meta: &'static Meta,
    prefix: &str,
    env_to_path: &mut HashMap<String, String>,
    path_to_env: &mut HashMap<String, String>,
) {
    for field in meta.fields {
        let path = if prefix.is_empty() {
            field.name.to_owned()
        } else {
            format!("{prefix}.{}", field.name)
        };

        match field.kind {
            FieldKind::Leaf { env: Some(env), .. } => {
                env_to_path.insert(env.to_ascii_uppercase(), path.clone());
                path_to_env.insert(path, env.to_owned());
            }
            FieldKind::Leaf { env: None, .. } => {}
            FieldKind::Nested { meta } => {
                collect_env_mapping(meta, &path, env_to_path, path_to_env);
            }
        }
    }
}

fn load_dotenv_for_path(path: &Path) -> ConfigResult<()> {
    let path = absolutize_lexical(path)?;
    let mut current_dir = path.parent();

    while let Some(dir) = current_dir {
        let dotenv_path = dir.join(".env");
        if dotenv_path.try_exists()? {
            dotenvy::from_path(&dotenv_path)?;
            break;
        }
        current_dir = dir.parent();
    }

    Ok(())
}

fn section_path_for_target<S>(root_base_dir: &Path, target_path: &Path) -> Option<Vec<&'static str>>
where
    S: ConfigSchema,
{
    let normalized_target = normalize_lexical(target_path);

    for section_path in nested_section_paths(&S::META) {
        let section_target =
            normalize_lexical(root_base_dir.join(template_path_for_section::<S>(&section_path)));
        if section_target == normalized_target {
            return Some(section_path);
        }
    }

    infer_section_path_from_path::<S>(target_path)
}

fn template_path_for_section<S>(section_path: &[&str]) -> PathBuf
where
    S: ConfigSchema,
{
    if let Some(path) = S::template_path_for_section(section_path) {
        return path;
    }

    let Some((last, parent_path)) = section_path.split_last() else {
        return PathBuf::new();
    };

    if parent_path.is_empty() {
        return PathBuf::from("config").join(format!("{last}.yaml"));
    }

    let parent_template_path = template_path_for_section::<S>(parent_path);
    parent_template_path
        .with_extension("")
        .join(format!("{last}.yaml"))
}

fn path_relative_to(path: &Path, base: &Path) -> PathBuf {
    match path.strip_prefix(base) {
        Ok(relative) if !relative.as_os_str().is_empty() => relative.to_path_buf(),
        _ => path.to_path_buf(),
    }
}

fn nested_section_paths(meta: &'static Meta) -> Vec<Vec<&'static str>> {
    let mut paths = Vec::new();
    collect_nested_section_paths(meta, &mut Vec::new(), &mut paths);
    paths
}

fn collect_nested_section_paths(
    meta: &'static Meta,
    prefix: &mut Vec<&'static str>,
    paths: &mut Vec<Vec<&'static str>>,
) {
    for field in meta.fields {
        if let FieldKind::Nested { meta } = field.kind {
            prefix.push(field.name);
            paths.push(prefix.clone());
            collect_nested_section_paths(meta, prefix, paths);
            prefix.pop();
        }
    }
}

fn immediate_child_section_paths(
    meta: &'static Meta,
    section_path: &[&'static str],
) -> Vec<Vec<&'static str>> {
    let Some(section_meta) = meta_at_path(meta, section_path) else {
        return Vec::new();
    };

    section_meta
        .fields
        .iter()
        .filter_map(|field| match field.kind {
            FieldKind::Nested { .. } => {
                let mut path = section_path.to_vec();
                path.push(field.name);
                Some(path)
            }
            FieldKind::Leaf { .. } => None,
        })
        .collect()
}

/// Emits Figment source metadata for every leaf field at TRACE level.
///
/// This function returns immediately unless `tracing` has TRACE enabled. Callers
/// can invoke it after initializing their tracing subscriber from the loaded log
/// configuration.
///
/// # Type Parameters
///
/// - `S`: Config schema whose metadata declares the field paths to trace.
///
/// # Arguments
///
/// - `figment`: Runtime source graph used to load the config.
///
/// # Returns
///
/// This function only emits tracing events and returns no value.
pub fn trace_config_sources<S>(figment: &Figment)
where
    S: ConfigSchema,
{
    if !tracing::enabled!(tracing::Level::TRACE) {
        return;
    }

    for path in leaf_config_paths(&S::META) {
        let source = config_source_for_path(figment, &path);
        trace!(target: "rust_config_tree::config", config_key = %path, source = %source, "config source");
    }
}

fn config_source_for_path(figment: &Figment, path: &str) -> String {
    match figment.find_metadata(path) {
        Some(metadata) => render_metadata(metadata, path),
        None => "confique default or unset optional field".to_owned(),
    }
}

fn render_metadata(metadata: &Metadata, path: &str) -> String {
    match &metadata.source {
        Some(Source::File(path)) => format!("{} `{}`", metadata.name, path.display()),
        Some(Source::Custom(value)) => format!("{} `{value}`", metadata.name),
        Some(Source::Code(location)) => {
            format!("{} {}:{}", metadata.name, location.file(), location.line())
        }
        Some(_) => metadata.name.to_string(),
        None => {
            let parts = path.split('.').collect::<Vec<_>>();
            let native = metadata.interpolate(&Profile::Default, &parts);

            format!("{} `{native}`", metadata.name)
        }
    }
}

fn leaf_config_paths(meta: &'static Meta) -> Vec<String> {
    let mut paths = Vec::new();
    collect_leaf_config_paths(meta, "", &mut paths);
    paths
}

fn collect_leaf_config_paths(meta: &'static Meta, prefix: &str, paths: &mut Vec<String>) {
    for field in meta.fields {
        let path = if prefix.is_empty() {
            field.name.to_owned()
        } else {
            format!("{prefix}.{}", field.name)
        };

        match field.kind {
            FieldKind::Leaf { .. } => paths.push(path),
            FieldKind::Nested { meta } => collect_leaf_config_paths(meta, &path, paths),
        }
    }
}

fn infer_section_path_from_path<S>(path: &Path) -> Option<Vec<&'static str>>
where
    S: ConfigSchema,
{
    let path_tokens = normalized_path_tokens(path);
    let file_token = path
        .file_stem()
        .and_then(OsStr::to_str)
        .map(normalize_token)
        .unwrap_or_default();

    nested_section_paths(&S::META)
        .into_iter()
        .filter_map(|section_path| {
            let score = section_path_score(&section_path, &path_tokens, &file_token);
            (score > 0).then_some((score, section_path))
        })
        .max_by_key(|(score, section_path)| (*score, section_path.len()))
        .map(|(_, section_path)| section_path)
}

fn normalized_path_tokens(path: &Path) -> Vec<String> {
    path.components()
        .filter_map(|component| component.as_os_str().to_str())
        .map(|component| {
            Path::new(component)
                .file_stem()
                .and_then(OsStr::to_str)
                .unwrap_or(component)
        })
        .map(normalize_token)
        .filter(|component| !component.is_empty())
        .collect()
}

fn normalize_token(token: &str) -> String {
    token
        .chars()
        .filter_map(|character| match character {
            '-' | ' ' => Some('_'),
            '_' => Some('_'),
            character if character.is_ascii_alphanumeric() => Some(character.to_ascii_lowercase()),
            _ => None,
        })
        .collect()
}

fn section_path_score(section_path: &[&str], path_tokens: &[String], file_token: &str) -> usize {
    let section_tokens = section_path
        .iter()
        .map(|segment| normalize_token(segment))
        .collect::<Vec<_>>();

    if path_tokens.ends_with(&section_tokens) {
        return 1_000 + section_tokens.len();
    }

    let Some(last_section_token) = section_tokens.last() else {
        return 0;
    };

    if file_token == last_section_token {
        return 500 + section_tokens.len();
    }

    if file_token.starts_with(last_section_token) || last_section_token.starts_with(file_token) {
        return 100 + last_section_token.len().min(file_token.len());
    }

    0
}

fn meta_at_path(meta: &'static Meta, section_path: &[&str]) -> Option<&'static Meta> {
    let mut current_meta = meta;
    for section in section_path {
        current_meta = current_meta.fields.iter().find_map(|field| {
            if field.name != *section {
                return None;
            }

            match field.kind {
                FieldKind::Nested { meta } => Some(meta),
                FieldKind::Leaf { .. } => None,
            }
        })?;
    }

    Some(current_meta)
}

fn render_yaml_template(
    meta: &'static Meta,
    include_paths: &[PathBuf],
    section_path: &[&'static str],
    split_paths: &[Vec<&'static str>],
) -> String {
    let mut output = String::new();
    if !include_paths.is_empty() {
        output.push_str(&render_yaml_include(include_paths));
        output.push('\n');
    }

    if section_path.is_empty() {
        render_yaml_fields(
            meta,
            &mut Vec::new(),
            split_paths,
            0,
            !include_paths.is_empty(),
            &mut output,
        );
    } else {
        render_yaml_section(meta, section_path, split_paths, &mut output);
    }

    ensure_single_trailing_newline(&mut output);
    output
}

fn render_yaml_section(
    meta: &'static Meta,
    section_path: &[&'static str],
    split_paths: &[Vec<&'static str>],
    output: &mut String,
) {
    let mut current_meta = meta;
    let mut current_path = Vec::new();

    for (depth, section) in section_path.iter().enumerate() {
        write_yaml_indent(output, depth);
        output.push('#');
        output.push_str(section);
        output.push_str(":\n");
        current_path.push(*section);

        let Some(next_meta) = meta_at_path(current_meta, &[*section]) else {
            return;
        };
        current_meta = next_meta;
    }

    render_yaml_fields(
        current_meta,
        &mut current_path,
        split_paths,
        section_path.len(),
        false,
        output,
    );
}

fn render_yaml_fields(
    meta: &'static Meta,
    current_path: &mut Vec<&'static str>,
    split_paths: &[Vec<&'static str>],
    depth: usize,
    skip_include_field: bool,
    output: &mut String,
) {
    let mut emitted_anything = false;

    for field in meta.fields {
        let FieldKind::Leaf { env, kind } = field.kind else {
            continue;
        };

        if skip_include_field && current_path.is_empty() && field.name == "include" {
            continue;
        }

        if emitted_anything {
            output.push('\n');
        }
        emitted_anything = true;
        render_yaml_leaf(field.name, field.doc, env, kind, depth, output);
    }

    for field in meta.fields {
        let FieldKind::Nested { meta } = field.kind else {
            continue;
        };

        current_path.push(field.name);
        let split_exact = split_paths.iter().any(|path| path == current_path);
        let split_descendant = split_paths
            .iter()
            .any(|path| path.starts_with(current_path) && path.len() > current_path.len());

        if split_exact {
            current_path.pop();
            continue;
        }

        if emitted_anything {
            output.push('\n');
        }
        emitted_anything = true;

        for doc in field.doc {
            write_yaml_indent(output, depth);
            output.push('#');
            output.push_str(doc);
            output.push('\n');
        }
        write_yaml_indent(output, depth);
        output.push_str(field.name);
        output.push_str(":\n");

        let child_split_paths = if split_descendant { split_paths } else { &[] };
        render_yaml_fields(
            meta,
            current_path,
            child_split_paths,
            depth + 1,
            false,
            output,
        );
        current_path.pop();
    }
}

fn render_yaml_leaf(
    name: &str,
    doc: &[&str],
    env: Option<&str>,
    kind: LeafKind,
    depth: usize,
    output: &mut String,
) {
    let mut emitted_doc_comment = false;
    for doc in doc {
        write_yaml_indent(output, depth);
        output.push('#');
        output.push_str(doc);
        output.push('\n');
        emitted_doc_comment = true;
    }

    if let Some(env) = env {
        if emitted_doc_comment {
            write_yaml_indent(output, depth);
            output.push_str("#\n");
        }
        write_yaml_indent(output, depth);
        output.push_str("# Can also be specified via environment variable `");
        output.push_str(env);
        output.push_str("`.\n");
    }

    match kind {
        LeafKind::Optional => {
            write_yaml_indent(output, depth);
            output.push('#');
            output.push_str(name);
            output.push_str(":\n");
        }
        LeafKind::Required { default } => {
            write_yaml_indent(output, depth);
            match default {
                Some(default) => {
                    output.push_str("# Default value: ");
                    output.push_str(&render_yaml_expr(&default));
                    output.push('\n');
                    write_yaml_indent(output, depth);
                    output.push('#');
                    output.push_str(name);
                    output.push_str(": ");
                    output.push_str(&render_yaml_expr(&default));
                    output.push('\n');
                }
                None => {
                    output.push_str("# Required! This value must be specified.\n");
                    write_yaml_indent(output, depth);
                    output.push('#');
                    output.push_str(name);
                    output.push_str(":\n");
                }
            }
        }
    }
}

fn render_yaml_expr(expr: &Expr) -> String {
    match expr {
        Expr::Str(value) => render_plain_or_quoted_string(value),
        Expr::Float(value) => value.to_string(),
        Expr::Integer(value) => value.to_string(),
        Expr::Bool(value) => value.to_string(),
        Expr::Array(items) => {
            let items = items
                .iter()
                .map(render_yaml_expr)
                .collect::<Vec<_>>()
                .join(", ");
            format!("[{items}]")
        }
        Expr::Map(entries) => {
            let entries = entries
                .iter()
                .map(|entry| {
                    format!(
                        "{}: {}",
                        render_yaml_map_key(&entry.key),
                        render_yaml_expr(&entry.value)
                    )
                })
                .collect::<Vec<_>>()
                .join(", ");
            format!("{{ {entries} }}")
        }
        _ => String::new(),
    }
}

fn render_yaml_map_key(key: &MapKey) -> String {
    match key {
        MapKey::Str(value) => render_plain_or_quoted_string(value),
        MapKey::Float(value) => value.to_string(),
        MapKey::Integer(value) => value.to_string(),
        MapKey::Bool(value) => value.to_string(),
        _ => String::new(),
    }
}

fn render_plain_or_quoted_string(value: &str) -> String {
    let needs_quotes = value.is_empty()
        || value.starts_with([
            ' ', '#', '{', '}', '[', ']', ',', '&', '*', '!', '|', '>', '\'', '"',
        ])
        || value.contains([':', '\n', '\r', '\t']);

    if needs_quotes {
        quote_path(Path::new(value))
    } else {
        value.to_owned()
    }
}

fn write_yaml_indent(output: &mut String, depth: usize) {
    for _ in 0..depth {
        output.push_str("  ");
    }
}

fn ensure_single_trailing_newline(output: &mut String) {
    if output.ends_with('\n') {
        while output.ends_with("\n\n") {
            output.pop();
        }
    } else {
        output.push('\n');
    }
}

fn template_for_path_with_includes<S>(
    path: &Path,
    include_paths: &[PathBuf],
) -> ConfigResult<String>
where
    S: ConfigSchema,
{
    let template = template_for_path::<S>(path)?;
    if include_paths.is_empty() {
        return Ok(template);
    }

    let template = match ConfigFormat::from_path(path) {
        ConfigFormat::Yaml => {
            let template = strip_prefix_once(&template, "# Default value: []\n#include: []\n\n");
            format!("{}\n{template}", render_yaml_include(include_paths))
        }
        ConfigFormat::Toml => {
            let template = strip_prefix_once(&template, "# Default value: []\n#include = []\n\n");
            format!("{}\n{template}", render_toml_include(include_paths))
        }
        ConfigFormat::Json => {
            let body = template.strip_prefix("{\n").unwrap_or(&template);
            let body = strip_prefix_once(body, "  // Default value: []\n  //include: [],\n\n");
            format!("{{\n{}\n{body}", render_json5_include(include_paths))
        }
    };

    Ok(template)
}

fn render_yaml_include(paths: &[PathBuf]) -> String {
    let mut out = String::from("include:\n");
    for path in paths {
        out.push_str("  - ");
        out.push_str(&quote_path(path));
        out.push('\n');
    }
    out
}

fn render_toml_include(paths: &[PathBuf]) -> String {
    let entries = paths
        .iter()
        .map(|path| quote_path(path))
        .collect::<Vec<_>>()
        .join(", ");
    format!("include = [{entries}]\n")
}

fn render_json5_include(paths: &[PathBuf]) -> String {
    let mut out = String::from("  include: [\n");
    for path in paths {
        out.push_str("    ");
        out.push_str(&quote_path(path));
        out.push_str(",\n");
    }
    out.push_str("  ],\n");
    out
}

fn quote_path(path: &Path) -> String {
    serde_json::to_string(&path.to_string_lossy()).expect("path string serialization cannot fail")
}

fn strip_prefix_once<'a>(value: &'a str, prefix: &str) -> &'a str {
    value.strip_prefix(prefix).unwrap_or(value)
}

fn yaml_options() -> confique::yaml::FormatOptions {
    let mut options = confique::yaml::FormatOptions::default();
    options.indent = 2;
    options.general.comments = true;
    options.general.env_keys = true;
    options.general.nested_field_gap = 1;
    options
}

fn toml_options() -> confique::toml::FormatOptions {
    let mut options = confique::toml::FormatOptions::default();
    options.general.comments = true;
    options.general.env_keys = true;
    options.general.nested_field_gap = 1;
    options
}

fn json5_options() -> confique::json5::FormatOptions {
    let mut options = confique::json5::FormatOptions::default();
    options.indent = 2;
    options.general.comments = true;
    options.general.env_keys = true;
    options.general.nested_field_gap = 1;
    options
}

#[cfg(test)]
#[path = "unit_tests/config.rs"]
mod unit_tests;