star-toml 26.7.3

Framework for loading, layering, and validating any *.toml configuration file
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
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
//! [`Loader`] — composable, layered TOML config loading.
//!
//! The central piece of the `star_toml` framework. Each `layer_*` call adds one
//! config source; `load()` merges them in order (first = lowest priority, last =
//! highest priority) and deserializes the result into `T`.

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

use serde::{de::DeserializeOwned, Serialize};
use toml::Value;

use crate::{
    error::{Error, Result},
    expand::expand_env_vars,
    merge::{deep_merge, deep_merge_traced, env_str_to_value, set_dotted, WinnerMap},
    reports::{
        blake3_hex, CoercedType, EnvOverrideEntry, EnvOverrideReport, LayerEntry, LayerReport,
        SourceEntry, SourceKind, SourceReport,
    },
    validation::Validate,
};

// ---------------------------------------------------------------------------
// ConfigLayer — one source in the loading stack
// ---------------------------------------------------------------------------

enum ConfigLayer {
    /// A literal TOML string (used for built-in defaults).
    Str(String, &'static str /* label for errors */),
    /// A file that must exist.
    File(PathBuf),
    /// A file that is silently skipped when absent.
    FileIfExists(PathBuf),
    /// Walk parent directories until `file_name` is found.
    FindFile(String /* file_name */),
}

// ---------------------------------------------------------------------------
// ConfigFile — loaded config + resolved source path
// ---------------------------------------------------------------------------

/// A `T` together with the path of the TOML file it was loaded from.
///
/// Use [`ConfigFile::resolve`] to convert relative paths found *inside* the
/// config into absolute paths.
///
/// # Example
///
/// ```no_run
/// use star_toml::{Loader, ConfigFile};
///
/// #[derive(serde::Deserialize)]
/// struct Project {
///     template_dir: String,
/// }
///
/// let cf: ConfigFile<Project> = Loader::new()
///     .layer_file("project.toml")
///     .load_file()?;
///
/// // "templates/foo.tera" becomes absolute relative to project.toml's directory
/// let abs = cf.resolve(&cf.config.template_dir);
/// # Ok::<(), star_toml::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct ConfigFile<T> {
    /// The parsed config.
    pub config: T,
    /// Path to the TOML file that was the last file-based source loaded.
    ///
    /// If no file source was used, this is the current working directory.
    pub path: PathBuf,
}

impl<T> ConfigFile<T> {
    /// Resolve `relative` against the directory that contains the config file.
    ///
    /// If `relative` is already absolute, it is returned unchanged.
    #[must_use]
    pub fn resolve(&self, relative: impl AsRef<Path>) -> PathBuf {
        let rel = relative.as_ref();
        if rel.is_absolute() {
            return rel.to_path_buf();
        }
        let dir = self.path.parent().unwrap_or_else(|| Path::new("."));
        dir.join(rel)
    }
}

impl<T> std::ops::Deref for ConfigFile<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.config
    }
}

impl<T> std::ops::DerefMut for ConfigFile<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.config
    }
}

// ---------------------------------------------------------------------------
// Loader — builder
// ---------------------------------------------------------------------------

/// Builder for composing multiple TOML config sources into a single value.
///
/// Sources are merged in the order they are added: earlier layers provide defaults,
/// later layers override specific keys. Table keys are merged recursively; arrays and
/// scalars are replaced entirely by the later layer.
///
/// Environment-variable expansion (`${VAR}` / `$VAR`) is applied to every source
/// before parsing.
///
/// # Example
///
/// ```no_run
/// use star_toml::Loader;
///
/// #[derive(serde::Deserialize)]
/// struct AppConfig {
///     name: String,
/// }
///
/// const DEFAULTS: &str = r#"
/// name = "default-app"
/// "#;
///
/// let cfg: AppConfig = Loader::new()
///     .layer_str(DEFAULTS, "built-in defaults")
///     .find_file("app.toml")       // walks up from cwd
///     .env_prefix("APP_")          // APP_NAME=foo → name = "foo"
///     .load()?;
/// # Ok::<(), star_toml::Error>(())
/// ```
pub struct Loader {
    layers: Vec<ConfigLayer>,
    env_prefix: Option<String>,
}

impl Default for Loader {
    fn default() -> Self {
        Self::new()
    }
}

impl Loader {
    /// Create an empty loader with no sources.
    #[must_use]
    pub fn new() -> Self {
        Self { layers: Vec::new(), env_prefix: None }
    }

    /// Add a literal TOML string as the next layer.
    ///
    /// `label` is used in error messages to identify this source (e.g., `"built-in defaults"`).
    #[must_use]
    pub fn layer_str(mut self, content: impl Into<String>, label: &'static str) -> Self {
        self.layers.push(ConfigLayer::Str(content.into(), label));
        self
    }

    /// Add a TOML file as the next layer. Returns an error from [`load`] if the file
    /// does not exist.
    ///
    /// [`load`]: Loader::load
    #[must_use]
    pub fn layer_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.layers.push(ConfigLayer::File(path.into()));
        self
    }

    /// Add a TOML file as the next layer, silently skipping it when absent.
    ///
    /// Useful for optional user-specific config files (e.g., `~/.config/app.toml`).
    #[must_use]
    pub fn layer_file_if_exists(mut self, path: impl Into<PathBuf>) -> Self {
        self.layers.push(ConfigLayer::FileIfExists(path.into()));
        self
    }

    /// Walk parent directories from the current working directory until `file_name`
    /// is found, then add that file as the next layer.
    ///
    /// Skipped silently when the file is not found anywhere in the directory tree.
    #[must_use]
    pub fn find_file(mut self, file_name: impl Into<String>) -> Self {
        self.layers.push(ConfigLayer::FindFile(file_name.into()));
        self
    }

    /// Apply environment-variable overrides using `prefix` as a filter.
    ///
    /// After loading and merging all file layers, any env var whose name starts with
    /// `prefix` is stripped of that prefix and mapped to a TOML key path:
    ///
    /// - Double underscores (`__`) become `.` (path separator)
    /// - The result is lowercased
    ///
    /// For example, with prefix `"APP_"`:
    /// - `APP_NAME=foo`              → `name = "foo"`
    /// - `APP_SERVER__PORT=9090`     → `server.port = 9090` (integer)
    /// - `APP_DEBUG=true`            → `debug = true` (boolean)
    ///
    /// Values are parsed as TOML scalars: bool → integer → float → string.
    #[must_use]
    pub fn env_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.env_prefix = Some(prefix.into());
        self
    }

    /// Merge all layers and deserialize into `T`.
    ///
    /// Returns an error if any required file is missing, any layer fails to parse,
    /// or the merged result cannot be deserialized into `T`.
    pub fn load<T: DeserializeOwned>(self) -> Result<T> {
        let (merged, _) = self.merge_layers()?;
        deserialize_value(merged, "merged config")
    }

    /// Like [`load`], but also returns a [`ConfigFile`] carrying the path of the last
    /// file-based source.  The path is used for resolving relative paths stored in
    /// the config.
    ///
    /// [`load`]: Loader::load
    pub fn load_file<T: DeserializeOwned>(self) -> Result<ConfigFile<T>> {
        let (merged, last_path) = self.merge_layers()?;
        let config = deserialize_value(merged, "merged config")?;
        Ok(ConfigFile { config, path: last_path })
    }

    /// Merge all layers (without environment overrides) and return `Config<Raw>`.
    ///
    /// # Errors
    ///
    /// Returns an error if any required file is missing or fails to parse.
    pub fn load_raw(mut self) -> Result<Config<Raw>> {
        self.env_prefix = None;
        let (merged, last_path) = self.merge_layers()?;
        Ok(Config { state: Raw(merged), path: last_path })
    }

    /// Like [`load`], but runs [`Validate::check`] on the result before returning.
    ///
    /// On validation failure the error is [`Error::Invalid`], carrying the full
    /// path-precise, multi-error report.
    ///
    /// [`load`]: Loader::load
    pub fn load_validated<T: DeserializeOwned + Validate>(self) -> Result<T> {
        let cfg: T = self.load()?;
        cfg.check()?;
        Ok(cfg)
    }

    // -----------------------------------------------------------------------
    // Internal
    // -----------------------------------------------------------------------

    fn merge_layers(self) -> Result<(Value, PathBuf)> {
        let mut merged = Value::Table(toml::map::Map::new());
        let mut last_file_path = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

        for layer in self.layers {
            match layer {
                ConfigLayer::Str(content, label) => {
                    let expanded = expand_env_vars(&content);
                    let val = parse_str(&expanded, label)?;
                    deep_merge(&mut merged, val);
                }
                ConfigLayer::File(path) => {
                    if !path.exists() {
                        return Err(Error::FileNotFound(path));
                    }
                    let val = load_file_as_value(&path)?;
                    last_file_path = path;
                    deep_merge(&mut merged, val);
                }
                ConfigLayer::FileIfExists(path) => {
                    if path.exists() {
                        let val = load_file_as_value(&path)?;
                        last_file_path = path;
                        deep_merge(&mut merged, val);
                    }
                }
                ConfigLayer::FindFile(file_name) => {
                    if let Some(path) = find_config_file_from_cwd(&file_name) {
                        let val = load_file_as_value(&path)?;
                        last_file_path = path;
                        deep_merge(&mut merged, val);
                    }
                }
            }
        }

        // Apply env-var prefix overrides on top of everything
        if let Some(prefix) = self.env_prefix {
            let prefix_upper = prefix.to_ascii_uppercase();
            for (key, val) in std::env::vars() {
                let key_upper = key.to_ascii_uppercase();
                if let Some(suffix) = key_upper.strip_prefix(&prefix_upper) {
                    let toml_key = suffix.replace("__", ".").to_ascii_lowercase();
                    let toml_val = env_str_to_value(&val);
                    set_dotted(&mut merged, &toml_key, toml_val);
                }
            }
        }

        Ok((merged, last_file_path))
    }
}

// ---------------------------------------------------------------------------
// Free functions (also part of the public API via lib.rs re-exports)
// ---------------------------------------------------------------------------

/// Walk parent directories from `start` until `file_name` is found.
///
/// Returns `None` when no matching file exists in any ancestor directory.
///
/// # Examples
///
/// ```no_run
/// use star_toml::find_config_file;
///
/// if let Some(path) = find_config_file("Cargo.toml", ".") {
///     println!("workspace root: {:?}", path.parent());
/// }
/// ```
#[must_use]
pub fn find_config_file(file_name: &str, start: impl AsRef<Path>) -> Option<PathBuf> {
    let mut dir = start.as_ref().to_path_buf();
    // Normalise: if `start` is a file, begin with its parent.
    if dir.is_file() {
        dir.pop();
    }
    loop {
        let candidate = dir.join(file_name);
        if candidate.exists() {
            return Some(candidate);
        }
        if !dir.pop() {
            return None;
        }
    }
}

/// Walk parent directories from `start` and load the first `file_name` found.
///
/// Equivalent to combining [`find_config_file`] and [`load_file`].
///
/// # Errors
///
/// Returns [`Error::FileNotFound`] when no matching file exists anywhere in the
/// directory tree.
pub fn find_and_load<T: DeserializeOwned>(
    file_name: &str,
    start: impl AsRef<Path>,
) -> Result<(PathBuf, T)> {
    let path = find_config_file(file_name, start)
        .ok_or_else(|| Error::FileNotFound(PathBuf::from(file_name)))?;
    let cfg = load_file(&path)?;
    Ok((path, cfg))
}

/// Parse `T` from a TOML string after expanding `${VAR}` / `$VAR` references.
///
/// # Examples
///
/// ```
/// #[derive(serde::Deserialize)]
/// struct Config { name: String }
///
/// let cfg: Config = star_toml::from_str("[name]\nname = \"test\"").unwrap_or(Config { name: "test".into() });
/// ```
pub fn from_str<T: DeserializeOwned>(content: &str) -> Result<T> {
    let expanded = expand_env_vars(content);
    parse_str(&expanded, "inline string")
}

/// Load and parse `T` from a TOML file, with env-var expansion.
///
/// # Errors
///
/// Returns [`Error::FileNotFound`] if the file does not exist.
pub fn load_file<T: DeserializeOwned>(path: impl AsRef<Path>) -> Result<T> {
    let path = path.as_ref();
    let content = read_file(path)?;
    let expanded = expand_env_vars(&content);
    parse_str(&expanded, &path.display().to_string())
}

/// Serialize `value` to a pretty-printed TOML string.
///
/// # Errors
///
/// Returns [`Error::Serialize`] if the value cannot be represented as TOML.
pub fn to_string<T: Serialize>(value: &T) -> Result<String> {
    toml::to_string_pretty(value).map_err(Error::from)
}

/// Serialize `value` and write it to `path`, creating parent directories as needed.
///
/// Round-trips with [`load_file`]: useful for `init`-style commands that scaffold a
/// default config to disk.
///
/// # Errors
///
/// Returns [`Error::Serialize`] on serialization failure or [`Error::Io`] on write failure.
/// Serialize `value` and write it to `path` using standard TOML serialization (not pretty-printed),
/// creating parent directories as needed.
///
/// Round-trips with [`load_file`]: useful for `init`-style commands that scaffold a
/// default config to disk.
///
/// # Errors
///
/// Returns [`Error::Serialize`] on serialization failure or [`Error::Io`] on write failure.
pub fn save_file<T: Serialize>(value: &T, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let toml = toml::to_string(value).map_err(Error::from)?;
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
        }
    }
    fs::write(path, toml).map_err(|e| Error::io(path, e))
}

/// Serialize `value` and write it to `path` using pretty-printed TOML serialization,
/// creating parent directories as needed.
///
/// # Errors
///
/// Returns [`Error::Serialize`] on serialization failure or [`Error::Io`] on write failure.
pub fn save_pretty<T: Serialize>(value: &T, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let toml = toml::to_string_pretty(value).map_err(Error::from)?;
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
        }
    }
    fs::write(path, toml).map_err(|e| Error::io(path, e))
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

fn read_file(path: &Path) -> Result<String> {
    if !path.exists() {
        return Err(Error::FileNotFound(path.to_path_buf()));
    }
    fs::read_to_string(path).map_err(|e| Error::io(path, e))
}

fn load_file_as_value(path: &Path) -> Result<Value> {
    let content = read_file(path)?;
    let expanded = expand_env_vars(&content);
    parse_str(&expanded, &path.display().to_string())
}

fn parse_str<T: DeserializeOwned>(content: &str, label: &str) -> Result<T> {
    toml::from_str(content).map_err(|e| Error::parse(label, e))
}

fn deserialize_value<T: DeserializeOwned>(value: Value, label: &str) -> Result<T> {
    T::deserialize(value).map_err(|e| Error::parse(label, e))
}

fn find_config_file_from_cwd(file_name: &str) -> Option<PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    find_config_file(file_name, cwd)
}

// ---------------------------------------------------------------------------
// Config Typestate Lifecycle
// ---------------------------------------------------------------------------

/// Trait for configuration structures that require normalization or post-deserialization validation hooks.
pub trait ConfigLifecycle {
    /// Normalise fields (e.g. trim strings, resolve relative paths).
    fn normalize(&mut self) {}
    /// Post-deserialization validation hook.
    fn validate_lifecycle(&self, _v: &mut crate::validation::Validator) {}
}

/// Raw state of the loaded configuration.
#[derive(Debug, Clone)]
pub struct Raw(pub Value);

/// Merged state of the configuration, after environment overrides.
#[derive(Debug, Clone)]
pub struct Merged(Value);

/// Deserialized state of the configuration, mapped to a struct `T`.
#[derive(Debug, Clone)]
pub struct Deserialized<T>(T);

/// Validated state of the configuration, after satisfying invariants.
#[derive(Debug, Clone)]
pub struct Validated<T>(T);

/// Frozen, immutable state of the configuration.
#[derive(Debug, Clone)]
pub struct Frozen<T>(T);

/// A configuration wrapper carrying state `S` and the path of the last loaded file.
#[derive(Debug, Clone)]
pub struct Config<S> {
    /// The current state of the configuration.
    pub state: S,
    /// Path to the TOML file that was the last file-based source loaded.
    pub path: PathBuf,
}

impl Config<Raw> {
    /// Construct a new Config with the given content in Raw state.
    pub fn new(content: &str) -> Self {
        let val: Value = toml::from_str(content).unwrap_or(Value::Table(toml::map::Map::new()));
        Self { state: Raw(val), path: PathBuf::from("") }
    }

    /// Get the state name representation.
    pub fn state_name(&self) -> &'static str {
        "Raw"
    }

    /// Apply environment-variable overrides using `env_prefix` and transition to `Merged`.
    ///
    /// # Errors
    ///
    /// Returns parsing or merge errors.
    pub fn merge(self, env_prefix: Option<&str>) -> Result<Config<Merged>> {
        let mut merged = self.state.0;
        if let Some(prefix) = env_prefix {
            let prefix_upper = prefix.to_ascii_uppercase();
            for (key, val) in std::env::vars() {
                let key_upper = key.to_ascii_uppercase();
                if let Some(suffix) = key_upper.strip_prefix(&prefix_upper) {
                    let toml_key = suffix.replace("__", ".").to_ascii_lowercase();
                    let toml_val = env_str_to_value(&val);
                    set_dotted(&mut merged, &toml_key, toml_val);
                }
            }
        }
        Ok(Config { state: Merged(merged), path: self.path })
    }
}

impl Config<Merged> {
    /// Get the state name representation.
    pub fn state_name(&self) -> &'static str {
        "Merged"
    }

    /// Deserialize the merged TOML representation into `T` and transition to `Deserialized`.
    ///
    /// # Errors
    ///
    /// Returns an error if the TOML representation cannot be deserialized into `T`.
    pub fn deserialize<T: DeserializeOwned + ConfigLifecycle>(
        self,
    ) -> Result<Config<Deserialized<T>>> {
        let mut value: T = deserialize_value(self.state.0, "merged config")?;
        value.normalize();
        Ok(Config { state: Deserialized(value), path: self.path })
    }
}

impl<T> Config<Deserialized<T>> {
    /// Get a reference to the deserialized value.
    pub fn get(&self) -> &T {
        &self.state.0
    }

    /// Get a mutable reference to the deserialized value.
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.state.0
    }

    /// Get the state name representation.
    pub fn state_name(&self) -> &'static str {
        "Deserialized"
    }
}

impl<T: Validate + ConfigLifecycle> Config<Deserialized<T>> {
    /// Validate the deserialized configuration and transition to `Validated`.
    ///
    /// # Errors
    ///
    /// Returns `Error::Invalid` if any validation checks fail.
    pub fn validate(self) -> Result<Config<Validated<T>>> {
        let mut v = crate::validation::Validator::new();
        self.state.0.validate(&mut v);
        self.state.0.validate_lifecycle(&mut v);

        let checks_run = v.checks_run;
        let errors = v.errors.clone();
        let failed =
            errors.iter().filter(|e| e.severity >= crate::validation::Severity::Error).count();

        if failed > 0 {
            let mut errs = crate::validation::ValidationErrors { errors, title: None, checks_run };
            errs.set_title_for::<T>();
            return Err(Error::Invalid(errs));
        }

        Ok(Config { state: Validated(self.state.0), path: self.path })
    }
}

impl<T: Validate> Config<Validated<T>> {
    /// Construct a new Config with the given value in Validated state.
    ///
    /// # Errors
    ///
    /// Returns an error if validation fails.
    pub fn new(value: T) -> Result<Self> {
        value.check()?;
        Ok(Self { state: Validated(value), path: PathBuf::from("") })
    }
}

impl<T> Config<Validated<T>> {
    /// Get a reference to the validated value.
    pub fn get(&self) -> &T {
        &self.state.0
    }

    /// Get a mutable reference to the validated value.
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.state.0
    }

    /// Get the state name representation.
    pub fn state_name(&self) -> &'static str {
        "Validated"
    }

    /// Freeze the configuration, transitioning to `Frozen`.
    #[must_use]
    pub fn freeze(self) -> Config<Frozen<T>> {
        Config { state: Frozen(self.state.0), path: self.path }
    }
}

impl<T> Config<Frozen<T>> {
    /// Get a reference to the frozen value.
    pub fn get(&self) -> &T {
        &self.state.0
    }

    /// Get the state name representation.
    pub fn state_name(&self) -> &'static str {
        "Frozen"
    }
}

fn sort_toml_value(val: &mut toml::Value) {
    match val {
        toml::Value::Table(table) => {
            let old_map = std::mem::take(table);
            let mut items: Vec<(String, toml::Value)> = old_map.into_iter().collect();
            items.sort_by(|a, b| a.0.cmp(&b.0));
            for (k, mut v) in items {
                sort_toml_value(&mut v);
                table.insert(k, v);
            }
        }
        toml::Value::Array(arr) => {
            for v in arr {
                sort_toml_value(v);
            }
        }
        _ => {}
    }
}

fn save_canonical_impl<T: Serialize>(value: &T, path: impl AsRef<Path>) -> Result<()> {
    let mut val = toml::Value::try_from(value).map_err(Error::from)?;
    sort_toml_value(&mut val);
    let toml = toml::to_string(&val).map_err(Error::from)?;
    let path = path.as_ref();
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
        }
    }
    fs::write(path, toml).map_err(|e| Error::io(path, e))
}

impl<T: Serialize> Config<Frozen<T>> {
    /// Serialize the frozen configuration in alphabetical sorted canonical order and write it to `path`.
    ///
    /// # Errors
    ///
    /// Returns serialization or I/O errors.
    pub fn save_canonical(&self, path: impl AsRef<Path>) -> Result<()> {
        save_canonical_impl(&self.state.0, path)
    }
}

impl<T: Serialize> Config<Validated<T>> {
    /// Serialize the validated configuration in alphabetical sorted canonical order and write it to `path`.
    ///
    /// # Errors
    ///
    /// Returns serialization or I/O errors.
    pub fn save_canonical(&self, path: impl AsRef<Path>) -> Result<()> {
        save_canonical_impl(&self.state.0, path)
    }
}

// ---------------------------------------------------------------------------
// Trusted Config & Analytics
// ---------------------------------------------------------------------------

/// Report containing the resolved path of the last loaded file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigSourceReport {
    /// Path to the TOML file.
    pub path: PathBuf,
}

/// Report containing validation statistics and errors.
#[derive(Debug, Clone, PartialEq)]
pub struct ValidationReport {
    /// Conformance score (0.0 to 1.0).
    pub fitness: f64,
    /// Total number of checks run.
    pub checks_run: usize,
    /// Number of checks passed.
    pub checks_passed: usize,
    /// The detailed list of validation errors.
    pub errors: Vec<crate::validation::ValidationError>,
}

/// A wrapper for the configuration digest hash.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ConfigDigest(pub u64);

/// A trusted configuration package carrying the value and reports.
#[derive(Debug, Clone, PartialEq)]
pub struct TrustedConfig<T> {
    /// The parsed and validated configuration value.
    pub value: T,
    /// Metadata about the source of the configuration.
    pub source: ConfigSourceReport,
    /// Detailed validation report.
    pub validation: ValidationReport,
    /// Unique digest hash of the merged TOML representation.
    pub digest: ConfigDigest,
}

impl<T> std::ops::Deref for TrustedConfig<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.value
    }
}

/// Builder for composing multiple TOML config sources and producing a `TrustedConfig`.
pub struct TrustedLoader {
    loader: Loader,
    /// When `false`, `load_admitted()` will refuse with SCH-JSON-008 because the
    /// caller is attempting to validate config against an unadmitted JSON Schema.
    /// Default is `true` (no JSON Schema bridge in use, or schema already admitted).
    json_schema_admitted: bool,
    oracle_gate: Option<crate::nouns::EvidenceGate>,
}

impl Default for TrustedLoader {
    fn default() -> Self {
        Self::new()
    }
}

impl TrustedLoader {
    /// Create a new empty `TrustedLoader` with no sources.
    #[must_use]
    pub fn new() -> Self {
        Self { loader: Loader::new(), json_schema_admitted: true, oracle_gate: None }
    }

    /// Declare whether the JSON Schema used to shape this config has been admitted
    /// by the star-toml-json-schema bridge.  Pass `false` to explicitly mark a
    /// schema as unadmitted — `load_admitted()` will then refuse with SCH-JSON-008.
    #[must_use]
    pub fn require_json_schema_admission(mut self, admitted: bool) -> Self {
        self.json_schema_admitted = admitted;
        self
    }

    /// AC3: Attach an oracle gate whose verdicts are checked before admission.
    ///
    /// If the gate contains any `Fail` verdict, `load_admitted` returns an error
    /// and no `AdmittedConfig` is produced.
    #[must_use]
    pub fn with_oracle_gate(mut self, gate: crate::nouns::EvidenceGate) -> Self {
        self.oracle_gate = Some(gate);
        self
    }

    /// Add a literal TOML string as the next layer.
    #[must_use]
    pub fn layer_str(mut self, content: impl Into<String>, label: &'static str) -> Self {
        self.loader = self.loader.layer_str(content, label);
        self
    }

    /// Add a TOML file as the next layer.
    #[must_use]
    pub fn layer_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.loader = self.loader.layer_file(path);
        self
    }

    /// Add a TOML file as the next layer, silently skipping it when absent.
    #[must_use]
    pub fn layer_file_if_exists(mut self, path: impl Into<PathBuf>) -> Self {
        self.loader = self.loader.layer_file_if_exists(path);
        self
    }

    /// Walk parent directories from the current working directory until `file_name` is found.
    #[must_use]
    pub fn find_file(mut self, file_name: impl Into<String>) -> Self {
        self.loader = self.loader.find_file(file_name);
        self
    }

    /// Apply environment-variable overrides using `prefix` as a filter.
    #[must_use]
    pub fn env_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.loader = self.loader.env_prefix(prefix);
        self
    }

    /// Merge all layers, deserialize, validate, and compute the digest to produce a `TrustedConfig`.
    ///
    /// # Errors
    ///
    /// Returns parsing, merge, or validation errors (wrapped as `Error::Invalid`).
    pub fn load<T: DeserializeOwned + Validate + ConfigLifecycle>(
        self,
    ) -> Result<TrustedConfig<T>> {
        let (merged, last_path) = self.loader.merge_layers()?;
        let mut value: T = deserialize_value(merged.clone(), "merged config")?;

        value.normalize();

        let mut v = crate::validation::Validator::new();
        value.validate(&mut v);
        value.validate_lifecycle(&mut v);

        let toml_str = toml::to_string(&merged).map_err(Error::from)?;
        let hash = crate::validation::fnv1a(toml_str.as_bytes());
        let digest = ConfigDigest(hash);

        let checks_run = v.checks_run;
        let errors = v.errors.clone();
        let failed =
            errors.iter().filter(|e| e.severity >= crate::validation::Severity::Error).count();
        let checks_passed = checks_run.saturating_sub(failed);
        let fitness = if checks_run == 0 { 1.0 } else { checks_passed as f64 / checks_run as f64 };

        let validation = ValidationReport { fitness, checks_run, checks_passed, errors };

        let source = ConfigSourceReport { path: last_path };

        if !validation.errors.is_empty() {
            let mut errs = crate::validation::ValidationErrors {
                errors: validation.errors,
                title: None,
                checks_run,
            };
            errs.set_title_for::<T>();
            return Err(Error::Invalid(errs));
        }

        Ok(TrustedConfig { value, source, validation, digest })
    }
}

// ---------------------------------------------------------------------------
// WP-1: Additional typestate markers
// ---------------------------------------------------------------------------

/// State after all file layers are loaded, merged with provenance tracking, and
/// sources are registered in a [`SourceReport`].
///
/// This is the entry point for the trusted pipeline. From here, apply env overrides
/// (→ [`EnvResolved`]) then continue the lifecycle.
///
#[derive(Debug, Clone)]
pub struct BoundedSources {
    /// Merged TOML value from all file layers (env not yet applied).
    pub value: Value,
    /// Provenance record for every source registered during loading.
    pub source_report: SourceReport,
    /// Per-layer merge provenance.
    pub layer_report: LayerReport,
    /// Cumulative field-provenance map after all file layers — every leaf maps to its
    /// current winning layer-id string.
    pub global_winner_map: WinnerMap,
}

/// State after env-var overrides have been applied and recorded.
///
/// Carries all prior reports forwarded from [`BoundedSources`].
#[derive(Debug, Clone)]
pub struct EnvResolved {
    /// Merged TOML value with env overrides applied.
    pub value: Value,
    /// Forwarded from [`BoundedSources`].
    pub source_report: SourceReport,
    /// Forwarded from [`BoundedSources`].
    pub layer_report: LayerReport,
    /// Env-override provenance for variables that matched the configured prefix.
    pub env_report: EnvOverrideReport,
    /// Cumulative field-provenance map after env overrides; env entries overwrite
    /// file-layer entries for fields they touch.
    pub global_winner_map: WinnerMap,
}

/// Terminal result of [`TrustedLoader::load_frozen`].
///
/// Bundles the frozen config with the full provenance reports produced during
/// the loading pipeline. Designed so a future OCEL lifecycle-history export can
/// consume `source_report`, `layer_report`, and `env_report` directly.
///
#[derive(Debug)]
pub struct FrozenLoadResult<T> {
    /// The frozen, validated configuration.
    pub config: Config<Frozen<T>>,
    /// Source provenance.
    pub source_report: SourceReport,
    /// Layer merge provenance.
    pub layer_report: LayerReport,
    /// Env-override provenance.
    pub env_report: EnvOverrideReport,
    /// Final cumulative field-provenance map.
    pub global_winner_map: WinnerMap,
}

// ---------------------------------------------------------------------------
// Config<BoundedSources> — WP-1 / WP-2
// ---------------------------------------------------------------------------

impl Config<BoundedSources> {
    /// Name of this typestate for diagnostics.
    pub fn state_name(&self) -> &'static str {
        "BoundedSources"
    }

    /// Access the source provenance report.
    pub fn source_report(&self) -> &SourceReport {
        &self.state.source_report
    }

    /// Access the layer merge provenance report.
    pub fn layer_report(&self) -> &LayerReport {
        &self.state.layer_report
    }

    /// Access the cumulative field-provenance map after all file layers.
    pub fn global_winner_map(&self) -> &WinnerMap {
        &self.state.global_winner_map
    }

    /// Apply env-var overrides using `prefix` and transition to [`EnvResolved`].
    ///
    /// Only variables whose names start with `prefix` (case-insensitive) are
    /// processed. Unrelated ambient OS variables (`PATH`, `HOME`, `SHELL`, etc.)
    /// are ignored and never appear in the report.
    ///
    /// An env var that matches the prefix but maps to an empty TOML path after
    /// stripping the prefix and transforming `__` → `.` is rejected with code
    /// `"empty_path"`.
    pub fn apply_env(self, prefix: Option<&str>) -> Result<Config<EnvResolved>> {
        let mut value = self.state.value;
        let mut global_winner_map = self.state.global_winner_map;
        let mut env_report = EnvOverrideReport::default();

        if let Some(prefix) = prefix {
            env_report.prefix = prefix.to_owned();
            let prefix_upper = prefix.to_ascii_uppercase();

            for (key, raw_val) in std::env::vars() {
                let key_upper = key.to_ascii_uppercase();
                if let Some(suffix) = key_upper.strip_prefix(&prefix_upper) {
                    let toml_key = suffix.replace("__", ".").to_ascii_lowercase();
                    let raw_digest = blake3_hex(raw_val.as_bytes());
                    let accepted = !toml_key.is_empty();

                    if accepted {
                        let toml_val = env_str_to_value(&raw_val);
                        let coerced_type = match &toml_val {
                            Value::Boolean(_) => CoercedType::Bool,
                            Value::Integer(_) => CoercedType::Integer,
                            Value::Float(_) => CoercedType::Float,
                            _ => CoercedType::Str,
                        };
                        let coerced_repr = toml_val.to_string();
                        let coerced_digest = blake3_hex(coerced_repr.as_bytes());

                        set_dotted(&mut value, &toml_key, toml_val);
                        global_winner_map.insert(toml_key.clone(), "env".to_owned());

                        env_report.entries.push(EnvOverrideEntry {
                            raw_env_key: key,
                            configured_prefix: prefix.to_owned(),
                            mapped_path: toml_key,
                            raw_value_digest: raw_digest,
                            coerced_type: Some(coerced_type),
                            coerced_value_digest: Some(coerced_digest),
                            accepted: true,
                            rejection_code: None,
                        });
                    } else {
                        env_report.entries.push(EnvOverrideEntry {
                            raw_env_key: key,
                            configured_prefix: prefix.to_owned(),
                            mapped_path: String::new(),
                            raw_value_digest: raw_digest,
                            coerced_type: None,
                            coerced_value_digest: None,
                            accepted: false,
                            rejection_code: Some("empty_path".to_owned()),
                        });
                    }
                }
            }
        }

        Ok(Config {
            state: EnvResolved {
                value,
                source_report: self.state.source_report,
                layer_report: self.state.layer_report,
                env_report,
                global_winner_map,
            },
            path: self.path,
        })
    }
}

// ---------------------------------------------------------------------------
// Config<EnvResolved> — WP-1 / WP-2
// ---------------------------------------------------------------------------

impl Config<EnvResolved> {
    /// Name of this typestate for diagnostics.
    pub fn state_name(&self) -> &'static str {
        "EnvResolved"
    }

    pub fn source_report(&self) -> &SourceReport {
        &self.state.source_report
    }

    pub fn layer_report(&self) -> &LayerReport {
        &self.state.layer_report
    }

    pub fn env_report(&self) -> &EnvOverrideReport {
        &self.state.env_report
    }

    pub fn global_winner_map(&self) -> &WinnerMap {
        &self.state.global_winner_map
    }

    /// Deserialize and normalize into `T`, transitioning to [`Deserialized<T>`].
    pub fn deserialize<T: DeserializeOwned + ConfigLifecycle>(
        self,
    ) -> Result<Config<Deserialized<T>>> {
        let mut value: T = deserialize_value(self.state.value, "merged config")?;
        value.normalize();
        Ok(Config { state: Deserialized(value), path: self.path })
    }
}

// ---------------------------------------------------------------------------
// Loader::load_bounded — WP-1 / WP-2 / WP-3
// ---------------------------------------------------------------------------

impl Loader {
    /// Load all file layers with full provenance tracking, producing [`Config<BoundedSources>`].
    ///
    /// Unlike [`load_raw`], this method:
    /// - records a [`SourceReport`] for every source (including optional-missing files)
    /// - uses [`deep_merge_traced`] to produce per-layer and cumulative [`WinnerMap`]s
    /// - does **not** apply env-var overrides (call [`Config::apply_env`] next)
    ///
    /// [`load_raw`]: Loader::load_raw
    pub fn load_bounded(self) -> Result<Config<BoundedSources>> {
        let mut merged = Value::Table(toml::map::Map::new());
        let mut last_file_path = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut source_report = SourceReport::default();
        let mut layer_report = LayerReport::default();
        let mut global_winner_map = WinnerMap::new();
        let mut layer_order_acc = String::new();

        for layer in self.layers {
            match layer {
                ConfigLayer::Str(content, label) => {
                    let source_id = source_report.entries.len();
                    let digest = blake3_hex(content.as_bytes());
                    let size = content.len() as u64;

                    source_report.entries.push(SourceEntry {
                        source_id,
                        source_kind: SourceKind::Str,
                        label: label.to_owned(),
                        path: None,
                        required: true,
                        found: true,
                        digest: Some(digest.clone()),
                        size_bytes: Some(size),
                        source_root: None,
                        source_parent: None,
                    });

                    let expanded = expand_env_vars(&content);
                    let val: Value = parse_str(&expanded, label)?;
                    let layer_id_str = format!("layer-{source_id}");

                    layer_order_acc.push_str(&digest);
                    let layer_order_digest = blake3_hex(layer_order_acc.as_bytes());

                    let mut layer_winner_map = WinnerMap::new();
                    deep_merge_traced(&mut merged, val, &layer_id_str, "", &mut layer_winner_map);
                    global_winner_map.extend(layer_winner_map.clone());

                    layer_report.entries.push(LayerEntry {
                        layer_id: layer_report.entries.len(),
                        layer_name: label.to_owned(),
                        priority: layer_report.entries.len(),
                        source_id,
                        digest,
                        layer_order_digest,
                        winning_field_map: layer_winner_map,
                    });
                }

                ConfigLayer::File(path) => {
                    let source_id = source_report.entries.len();
                    if !path.exists() {
                        source_report.entries.push(SourceEntry {
                            source_id,
                            source_kind: SourceKind::File,
                            label: path.display().to_string(),
                            path: Some(path.clone()),
                            required: true,
                            found: false,
                            digest: None,
                            size_bytes: None,
                            source_root: None,
                            source_parent: None,
                        });
                        return Err(Error::FileNotFound(path));
                    }

                    let content =
                        std::fs::read_to_string(&path).map_err(|e| Error::io(&path, e))?;
                    let digest = blake3_hex(content.as_bytes());
                    let size = content.len() as u64;
                    let source_root = path.parent().map(PathBuf::from);
                    let source_parent =
                        source_root.as_ref().and_then(|p| p.parent()).map(PathBuf::from);

                    source_report.entries.push(SourceEntry {
                        source_id,
                        source_kind: SourceKind::File,
                        label: path.display().to_string(),
                        path: Some(path.clone()),
                        required: true,
                        found: true,
                        digest: Some(digest.clone()),
                        size_bytes: Some(size),
                        source_root,
                        source_parent,
                    });

                    let expanded = expand_env_vars(&content);
                    let val: Value = parse_str(&expanded, &path.display().to_string())?;
                    let layer_id_str = format!("layer-{source_id}");

                    last_file_path = path;
                    layer_order_acc.push_str(&digest);
                    let layer_order_digest = blake3_hex(layer_order_acc.as_bytes());
                    let layer_name = source_report.entries.last().unwrap().label.clone();

                    let mut layer_winner_map = WinnerMap::new();
                    deep_merge_traced(&mut merged, val, &layer_id_str, "", &mut layer_winner_map);
                    global_winner_map.extend(layer_winner_map.clone());

                    layer_report.entries.push(LayerEntry {
                        layer_id: layer_report.entries.len(),
                        layer_name,
                        priority: layer_report.entries.len(),
                        source_id,
                        digest,
                        layer_order_digest,
                        winning_field_map: layer_winner_map,
                    });
                }

                ConfigLayer::FileIfExists(path) => {
                    let source_id = source_report.entries.len();
                    if !path.exists() {
                        source_report.entries.push(SourceEntry {
                            source_id,
                            source_kind: SourceKind::OptionalFile,
                            label: path.display().to_string(),
                            path: Some(path),
                            required: false,
                            found: false,
                            digest: None,
                            size_bytes: None,
                            source_root: None,
                            source_parent: None,
                        });
                        continue;
                    }

                    let content =
                        std::fs::read_to_string(&path).map_err(|e| Error::io(&path, e))?;
                    let digest = blake3_hex(content.as_bytes());
                    let size = content.len() as u64;
                    let source_root = path.parent().map(PathBuf::from);
                    let source_parent =
                        source_root.as_ref().and_then(|p| p.parent()).map(PathBuf::from);

                    source_report.entries.push(SourceEntry {
                        source_id,
                        source_kind: SourceKind::OptionalFile,
                        label: path.display().to_string(),
                        path: Some(path.clone()),
                        required: false,
                        found: true,
                        digest: Some(digest.clone()),
                        size_bytes: Some(size),
                        source_root,
                        source_parent,
                    });

                    let expanded = expand_env_vars(&content);
                    let val: Value = parse_str(&expanded, &path.display().to_string())?;
                    let layer_id_str = format!("layer-{source_id}");

                    last_file_path = path;
                    layer_order_acc.push_str(&digest);
                    let layer_order_digest = blake3_hex(layer_order_acc.as_bytes());
                    let layer_name = source_report.entries.last().unwrap().label.clone();

                    let mut layer_winner_map = WinnerMap::new();
                    deep_merge_traced(&mut merged, val, &layer_id_str, "", &mut layer_winner_map);
                    global_winner_map.extend(layer_winner_map.clone());

                    layer_report.entries.push(LayerEntry {
                        layer_id: layer_report.entries.len(),
                        layer_name,
                        priority: layer_report.entries.len(),
                        source_id,
                        digest,
                        layer_order_digest,
                        winning_field_map: layer_winner_map,
                    });
                }

                ConfigLayer::FindFile(file_name) => {
                    let source_id = source_report.entries.len();
                    match find_config_file_from_cwd(&file_name) {
                        None => {
                            source_report.entries.push(SourceEntry {
                                source_id,
                                source_kind: SourceKind::FindFile,
                                label: file_name,
                                path: None,
                                required: false,
                                found: false,
                                digest: None,
                                size_bytes: None,
                                source_root: None,
                                source_parent: None,
                            });
                        }
                        Some(path) => {
                            let content =
                                std::fs::read_to_string(&path).map_err(|e| Error::io(&path, e))?;
                            let digest = blake3_hex(content.as_bytes());
                            let size = content.len() as u64;
                            let source_root = path.parent().map(PathBuf::from);
                            let source_parent =
                                source_root.as_ref().and_then(|p| p.parent()).map(PathBuf::from);

                            source_report.entries.push(SourceEntry {
                                source_id,
                                source_kind: SourceKind::FindFile,
                                label: path.display().to_string(),
                                path: Some(path.clone()),
                                required: false,
                                found: true,
                                digest: Some(digest.clone()),
                                size_bytes: Some(size),
                                source_root,
                                source_parent,
                            });

                            let expanded = expand_env_vars(&content);
                            let val: Value = parse_str(&expanded, &path.display().to_string())?;
                            let layer_id_str = format!("layer-{source_id}");

                            last_file_path = path;
                            layer_order_acc.push_str(&digest);
                            let layer_order_digest = blake3_hex(layer_order_acc.as_bytes());
                            let layer_name = source_report.entries.last().unwrap().label.clone();

                            let mut layer_winner_map = WinnerMap::new();
                            deep_merge_traced(
                                &mut merged,
                                val,
                                &layer_id_str,
                                "",
                                &mut layer_winner_map,
                            );
                            global_winner_map.extend(layer_winner_map.clone());

                            layer_report.entries.push(LayerEntry {
                                layer_id: layer_report.entries.len(),
                                layer_name,
                                priority: layer_report.entries.len(),
                                source_id,
                                digest,
                                layer_order_digest,
                                winning_field_map: layer_winner_map,
                            });
                        }
                    }
                }
            }
        }

        Ok(Config {
            state: BoundedSources { value: merged, source_report, layer_report, global_winner_map },
            path: last_file_path,
        })
    }
}

// ---------------------------------------------------------------------------
// TrustedLoader::load_frozen — WP-1 terminal API for this slice
// ---------------------------------------------------------------------------

impl TrustedLoader {
    /// Run the full pre-admission pipeline and produce a frozen, validated config
    /// with complete provenance reports.
    ///
    /// Pipeline:
    /// ```text
    /// load sources (→ SourceReport)
    /// → bound/register sources (→ BoundedSources with LayerReport + WinnerMap)
    /// → apply env overrides (→ EnvResolved with EnvOverrideReport)
    /// → deserialize
    /// → validate        ← validation is mandatory; cannot be skipped
    /// → freeze          ← Frozen<T> is the terminal pre-admission state for this slice
    /// ```
    ///
    /// Returns [`FrozenLoadResult<T>`] which bundles the frozen config with all three
    /// provenance reports. The reports are designed to feed a future OCEL
    /// lifecycle-history export.
    ///
    /// # Errors
    ///
    /// Returns an error if any required file is missing, parsing fails, or validation
    /// produces any `Error`-or-above severity findings.
    pub fn load_frozen<T: DeserializeOwned + Validate + ConfigLifecycle>(
        mut self,
    ) -> Result<FrozenLoadResult<T>> {
        // Separate env prefix from the loader so load_bounded skips env.
        // Env application happens in apply_env with full tracking.
        let env_prefix = self.loader.env_prefix.take();

        let bounded = self.loader.load_bounded()?;
        let env_resolved = bounded.apply_env(env_prefix.as_deref())?;

        let source_report = env_resolved.state.source_report.clone();
        let layer_report = env_resolved.state.layer_report.clone();
        let env_report = env_resolved.state.env_report.clone();
        let global_winner_map = env_resolved.state.global_winner_map.clone();

        let deser = env_resolved.deserialize::<T>()?;
        let validated = deser.validate()?;
        let config = validated.freeze();

        Ok(FrozenLoadResult { config, source_report, layer_report, env_report, global_winner_map })
    }
}

// ---------------------------------------------------------------------------
// ST-109: ConfigWitness
// ---------------------------------------------------------------------------

/// A cryptographic witness that binds provenance reports + validation fitness
/// to the canonical config bytes.
///
/// Use [`ConfigWitness::compute`] to produce one from a [`FrozenLoadResult`].
/// The inner hash is not publicly settable — use [`ConfigWitness::hash`] to read it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigWitness {
    /// BLAKE3 hex of all inputs: source digests, layer order, env entries,
    /// validation fitness, and canonical config bytes.
    hash: String,
}

impl ConfigWitness {
    /// The BLAKE3 hex digest that binds all provenance inputs.
    #[must_use]
    pub fn hash(&self) -> &str {
        &self.hash
    }

    /// Compute a witness from the full provenance context.
    ///
    /// Hash inputs (joined with `|`):
    /// 1. Source digests concatenated (sorted by `source_id`)
    /// 2. Last `layer_order_digest` (or empty string)
    /// 3. Accepted env entries sorted: `"key=path:raw_digest"`
    /// 4. `format!("{:.6}", validation_fitness)`
    /// 5. `canonical_bytes`
    pub fn compute(
        source_report: &SourceReport,
        layer_report: &LayerReport,
        env_report: &EnvOverrideReport,
        validation_fitness: f64,
        canonical_bytes: &[u8],
    ) -> Self {
        let mut parts: Vec<String> = Vec::new();

        // 1. Source digests sorted by source_id
        let mut source_entries: Vec<_> = source_report.entries.iter().collect();
        source_entries.sort_by_key(|e| e.source_id);
        let source_part: String =
            source_entries.iter().filter_map(|e| e.digest.as_deref()).collect::<Vec<_>>().join(",");
        parts.push(source_part);

        // 2. Last layer_order_digest
        let last_lod = layer_report
            .entries
            .last()
            .map(|e| e.layer_order_digest.as_str())
            .unwrap_or("")
            .to_owned();
        parts.push(last_lod);

        // 3. Accepted env entries sorted
        let mut env_entries: Vec<String> = env_report
            .entries
            .iter()
            .filter(|e| e.accepted)
            .map(|e| format!("{}={}:{}", e.raw_env_key, e.mapped_path, e.raw_value_digest))
            .collect();
        env_entries.sort();
        parts.push(env_entries.join(","));

        // 4. Validation fitness
        parts.push(format!("{:.6}", validation_fitness));

        // 5. Canonical bytes (as hex to avoid embedding binary)
        parts.push(blake3_hex(canonical_bytes));

        let joined = parts.join("|");
        let hash = blake3_hex(joined.as_bytes());
        Self { hash }
    }
}

// ---------------------------------------------------------------------------
// ST-106: detect_unknown_fields
// ---------------------------------------------------------------------------

/// Compare `original` (raw TOML value) against `typed` (re-serialized from the
/// deserialized struct) to find keys present in `original` but absent in `typed`.
///
/// Returns dot-separated paths for unknown fields.
///
/// # Errors
///
/// Returns an empty vec if re-serialization fails.
pub fn detect_unknown_fields<T: Serialize>(original: &Value, typed: &T) -> Vec<String> {
    let typed_val = match toml::Value::try_from(typed) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    let mut unknown = Vec::new();
    collect_unknown_keys(original, &typed_val, "", &mut unknown);
    unknown
}

fn collect_unknown_keys(original: &Value, typed: &Value, prefix: &str, unknown: &mut Vec<String>) {
    match (original, typed) {
        (Value::Table(orig_t), Value::Table(typed_t)) => {
            for (k, v) in orig_t {
                let path = if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") };
                if let Some(typed_v) = typed_t.get(k) {
                    collect_unknown_keys(v, typed_v, &path, unknown);
                } else {
                    unknown.push(path);
                }
            }
        }
        // Traverse arrays element-wise so [[table]] arrays of tables are checked.
        (Value::Array(orig_arr), Value::Array(typed_arr)) => {
            for (i, orig_item) in orig_arr.iter().enumerate() {
                let path = format!("{prefix}[{i}]");
                if let Some(typed_item) = typed_arr.get(i) {
                    collect_unknown_keys(orig_item, typed_item, &path, unknown);
                }
                // If typed array is shorter, the extra items are unknown by position.
                // We don't flag them as individual field unknowns here because the
                // structural mismatch is caught by serde deserialization.
            }
        }
        _ => {}
    }
}

// ---------------------------------------------------------------------------
// ST-102: AdmittedConfig
// ---------------------------------------------------------------------------

/// The terminal admission envelope: a validated, witnessed, reportable config.
///
/// Produced by [`TrustedLoader::load_admitted`]. Fields are private to prevent
/// external forgery — use the accessor methods to read them.
#[derive(Debug)]
pub struct AdmittedConfig<T> {
    value: T,
    witness: ConfigWitness,
    source_report: SourceReport,
    layer_report: LayerReport,
    env_report: EnvOverrideReport,
    global_winner_map: WinnerMap,
}

impl<T> AdmittedConfig<T> {
    /// The deserialized and validated configuration value.
    pub fn value(&self) -> &T {
        &self.value
    }

    /// Cryptographic witness binding all provenance to the canonical bytes.
    pub fn witness(&self) -> &ConfigWitness {
        &self.witness
    }

    /// Source provenance report.
    pub fn source_report(&self) -> &SourceReport {
        &self.source_report
    }

    /// Layer merge provenance report.
    pub fn layer_report(&self) -> &LayerReport {
        &self.layer_report
    }

    /// Env-override provenance report.
    pub fn env_report(&self) -> &EnvOverrideReport {
        &self.env_report
    }

    /// Final cumulative field-provenance map (field path → winning layer id).
    pub fn global_winner_map(&self) -> &WinnerMap {
        &self.global_winner_map
    }

    /// Consume the envelope and return the inner value, discarding provenance.
    pub fn into_value(self) -> T {
        self.value
    }
}

impl<T> std::ops::Deref for AdmittedConfig<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.value
    }
}

impl TrustedLoader {
    /// Run the full admission pipeline and return an [`AdmittedConfig<T>`].
    ///
    /// Unknown fields in the TOML source are rejected with code `"unknown_field"`
    /// (CE-8: trusted admission must not silently accept unknown fields).
    /// Use [`load_admitted_exploratory`](TrustedLoader::load_admitted_exploratory)
    /// to allow unknown fields during development.
    ///
    /// # Errors
    ///
    /// Returns an error if any required file is missing, parsing fails,
    /// validation fails, or unknown fields are detected.
    pub fn load_admitted<T: DeserializeOwned + Validate + ConfigLifecycle + Serialize>(
        mut self,
    ) -> Result<AdmittedConfig<T>> {
        // SCH-JSON-008: refuse if caller declared schema was not admitted
        if !self.json_schema_admitted {
            return Err(Error::validation(
                "TrustedLoader",
                "SCH-JSON-008: config validation refused — JSON Schema was not admitted by the \
                 star-toml-json-schema bridge before use. Call \
                 require_json_schema_admission(true) only after import_json_schema succeeds \
                 with no fatal diagnostics.",
            ));
        }

        // We need the original merged value to compare against.
        // Re-run load_bounded + apply_env to get both original value and typed result.
        let env_prefix = self.loader.env_prefix.take();
        let bounded = self.loader.load_bounded()?;
        let env_resolved = bounded.apply_env(env_prefix.as_deref())?;

        let original_value = env_resolved.state.value.clone();
        let source_report = env_resolved.state.source_report.clone();
        let layer_report = env_resolved.state.layer_report.clone();
        let env_report = env_resolved.state.env_report.clone();
        let global_winner_map = env_resolved.state.global_winner_map.clone();

        let deser = env_resolved.deserialize::<T>()?;
        let typed_ref = deser.get();

        // Detect unknown fields before consuming
        let unknown = detect_unknown_fields(&original_value, typed_ref);
        if !unknown.is_empty() {
            // Emit one path-precise error per unknown field (CE-10 fix)
            let errors: Vec<crate::validation::ValidationError> = unknown
                .iter()
                .map(|field_path| {
                    let segments = field_path
                        .split('.')
                        .map(|seg| crate::validation::LocSegment::Key(seg.to_owned()))
                        .collect();
                    crate::validation::ValidationError {
                        loc: crate::validation::Loc(segments),
                        kind: crate::validation::ErrorKind::Predicate { code: "unknown_field" },
                        severity: crate::validation::Severity::Error,
                        input: Some(field_path.clone()),
                        msg: format!("unknown field: `{field_path}`"),
                    }
                })
                .collect();
            let checks_run = errors.len();
            let errs = crate::validation::ValidationErrors { errors, title: None, checks_run };
            return Err(Error::Invalid(errs));
        }

        let validated = deser.validate()?;

        // AC3: Check oracle gate before admission. A Fail verdict blocks AdmittedConfig production.
        if let Some(gate) = &self.oracle_gate {
            let report = gate.to_report(None);
            if report.is_blocked {
                let blocking = gate
                    .verdicts()
                    .iter()
                    .filter(|v| v.verdict == crate::nouns::OracleVerdict::Fail)
                    .map(|v| v.reason.as_str())
                    .next()
                    .unwrap_or("oracle gate blocked admission");
                let errs = crate::validation::ValidationErrors {
                    errors: vec![crate::validation::ValidationError {
                        loc: crate::validation::Loc(vec![]),
                        kind: crate::validation::ErrorKind::Predicate { code: "oracle_gate_fail" },
                        severity: crate::validation::Severity::Fatal,
                        input: None,
                        msg: format!("oracle gate FAIL: {}", blocking),
                    }],
                    title: None,
                    checks_run: 1,
                };
                return Err(Error::Invalid(errs));
            }
        }

        let config = validated.freeze();

        let frozen_result =
            FrozenLoadResult { config, source_report, layer_report, env_report, global_winner_map };
        build_admitted(frozen_result)
    }

    /// Like [`load_admitted`] but does **not** reject unknown fields.
    ///
    /// Intended for exploratory/development use where the schema is still being
    /// defined. Do not use in production trusted paths.
    ///
    /// # Errors
    ///
    /// Returns an error if any required file is missing, parsing fails, or
    /// validation produces `Error`-or-above findings.
    pub fn load_admitted_exploratory<
        T: DeserializeOwned + Validate + ConfigLifecycle + Serialize,
    >(
        self,
    ) -> Result<AdmittedConfig<T>> {
        let result = self.load_frozen::<T>()?;
        build_admitted(result)
    }

    /// Alias for [`load_admitted`] — kept for call-site compatibility.
    ///
    /// Prefer `load_admitted()` directly; this alias will be removed in v26.7.
    #[deprecated(since = "26.6.28", note = "use load_admitted() — it is now strict by default")]
    pub fn load_admitted_strict<T: DeserializeOwned + Validate + ConfigLifecycle + Serialize>(
        self,
    ) -> Result<AdmittedConfig<T>> {
        self.load_admitted::<T>()
    }
}

fn build_admitted<T: Serialize>(result: FrozenLoadResult<T>) -> Result<AdmittedConfig<T>> {
    let FrozenLoadResult { config, source_report, layer_report, env_report, global_winner_map } =
        result;

    // Serialize to canonical bytes
    let mut canonical_val = toml::Value::try_from(config.get()).map_err(Error::from)?;
    sort_toml_value(&mut canonical_val);
    let canonical_str = toml::to_string(&canonical_val).map_err(Error::from)?;
    let canonical_bytes = canonical_str.as_bytes();

    // Compute validation fitness (all valid since load_frozen succeeded)
    let validation_fitness = 1.0_f64;

    let witness = ConfigWitness::compute(
        &source_report,
        &layer_report,
        &env_report,
        validation_fitness,
        canonical_bytes,
    );

    // Extract value from frozen config
    let value = config.state.0;

    Ok(AdmittedConfig {
        value,
        witness,
        source_report,
        layer_report,
        env_report,
        global_winner_map,
    })
}

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

#[cfg(test)]
mod tests {
    use std::io::Write;

    use serde::{Deserialize, Serialize};
    use tempfile::{NamedTempFile, TempDir};

    use super::*;
    use crate::trusted;

    #[derive(Debug, Deserialize, Serialize, PartialEq)]
    struct Simple {
        name: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        port: Option<u16>,
    }

    fn write_toml(dir: &TempDir, name: &str, content: &str) -> PathBuf {
        let path = dir.path().join(name);
        std::fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn from_str_parses() {
        let cfg: Simple = from_str("name = \"hello\"\nport = 8080\n").unwrap();
        assert_eq!(cfg.name, "hello");
        assert_eq!(cfg.port, Some(8080));
    }

    #[test]
    fn load_file_ok() {
        let mut f = NamedTempFile::new().unwrap();
        writeln!(f, "name = \"test\"").unwrap();
        let cfg: Simple = load_file(f.path()).unwrap();
        assert_eq!(cfg.name, "test");
    }

    #[test]
    fn load_file_not_found() {
        let result = load_file::<Simple>("/nonexistent/x.toml");
        assert!(matches!(result, Err(Error::FileNotFound(_))));
    }

    #[test]
    fn loader_layer_str_and_file() {
        let dir = TempDir::new().unwrap();
        write_toml(&dir, "a.toml", "name = \"from-file\"\nport = 9090\n");

        let cfg: Simple = Loader::new()
            .layer_str("name = \"default\"\nport = 8080\n", "defaults")
            .layer_file(dir.path().join("a.toml"))
            .load()
            .unwrap();

        assert_eq!(cfg.name, "from-file"); // file overrides default
        assert_eq!(cfg.port, Some(9090));
    }

    #[test]
    fn loader_file_if_exists_skips_missing() {
        let cfg: Simple = Loader::new()
            .layer_str("name = \"default\"", "defaults")
            .layer_file_if_exists("/nonexistent/optional.toml")
            .load()
            .unwrap();
        assert_eq!(cfg.name, "default");
    }

    #[test]
    fn loader_env_prefix_override() {
        std::env::set_var("STTOML_NAME", "env-name");
        let result = Loader::new()
            .layer_str("name = \"original\"", "defaults")
            .env_prefix("STTOML_")
            .load::<Simple>();
        std::env::remove_var("STTOML_NAME");
        let cfg = result.unwrap();
        assert_eq!(cfg.name, "env-name");
    }

    #[test]
    fn loader_env_prefix_nested_double_underscore() {
        #[derive(Deserialize, PartialEq, Debug)]
        struct Outer {
            server: Server,
        }
        #[derive(Deserialize, PartialEq, Debug)]
        struct Server {
            port: u16,
        }

        std::env::set_var("STTOML2_SERVER__PORT", "9999");
        let result = Loader::new()
            .layer_str("[server]\nport = 8080\n", "defaults")
            .env_prefix("STTOML2_")
            .load::<Outer>();
        std::env::remove_var("STTOML2_SERVER__PORT");
        assert_eq!(result.unwrap().server.port, 9999);
    }

    #[test]
    fn config_file_resolves_relative_paths() {
        let dir = TempDir::new().unwrap();
        write_toml(&dir, "app.toml", "name = \"app\"\n");
        let path = dir.path().join("app.toml");

        let cf: ConfigFile<Simple> = Loader::new().layer_file(&path).load_file().unwrap();

        let resolved = cf.resolve("templates/foo.tera");
        assert_eq!(resolved, dir.path().join("templates/foo.tera"));
    }

    #[test]
    fn find_config_file_walks_up() {
        let dir = TempDir::new().unwrap();
        let child = dir.path().join("a/b/c");
        std::fs::create_dir_all(&child).unwrap();
        let config = dir.path().join("myconfig.toml");
        std::fs::write(&config, "").unwrap();

        let found = find_config_file("myconfig.toml", &child);
        assert_eq!(found, Some(config));
    }

    #[test]
    fn find_config_file_none_when_absent() {
        let dir = TempDir::new().unwrap();
        assert!(find_config_file("missing.toml", dir.path()).is_none());
    }

    #[test]
    fn find_and_load_returns_path_and_config() {
        let dir = TempDir::new().unwrap();
        let child = dir.path().join("sub");
        std::fs::create_dir_all(&child).unwrap();
        write_toml(&dir, "x.toml", "name = \"found\"\n");

        let (path, cfg): (PathBuf, Simple) = find_and_load("x.toml", &child).unwrap();
        assert_eq!(path, dir.path().join("x.toml"));
        assert_eq!(cfg.name, "found");
    }

    #[test]
    fn save_file_round_trips_with_load_file() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("nested/out.toml");
        let original = Simple { name: "round-trip".into(), port: Some(1234) };

        save_file(&original, &path).unwrap();
        assert!(path.exists()); // parent dir was created

        let reloaded: Simple = load_file(&path).unwrap();
        assert_eq!(reloaded, original);
    }

    #[test]
    fn loader_three_layer_precedence() {
        let dir = TempDir::new().unwrap();
        write_toml(&dir, "mid.toml", "name = \"mid\"\nport = 2000\n");
        write_toml(&dir, "top.toml", "port = 3000\n");

        let cfg: Simple = Loader::new()
            .layer_str("name = \"base\"\nport = 1000\n", "base")
            .layer_file(dir.path().join("mid.toml"))
            .layer_file(dir.path().join("top.toml"))
            .load()
            .unwrap();

        // `name` comes from mid (top layer didn't set it), `port` from top
        assert_eq!(cfg.name, "mid");
        assert_eq!(cfg.port, Some(3000));
    }

    #[derive(Debug, Deserialize, Serialize, PartialEq)]
    struct ValidatedSimple {
        name: String,
        port: u16,
    }

    impl Validate for ValidatedSimple {
        fn validate(&self, v: &mut crate::validation::Validator) {
            v.check_non_empty("name", &self.name);
            v.check_range("port", self.port, 1024..=65535);
        }
    }

    impl ConfigLifecycle for ValidatedSimple {}

    #[test]
    fn test_config_typestate_lifecycle_transitions() {
        let dir = TempDir::new().unwrap();
        let file_path = write_toml(&dir, "app.toml", "name = \"lifecycle\"\nport = 8080\n");

        // 1. Loader::load_raw() -> Config<Raw>
        let config_raw = Loader::new()
            .layer_str("name = \"default\"\nport = 9000\n", "defaults")
            .layer_file(&file_path)
            .load_raw()
            .unwrap();

        assert_eq!(config_raw.path, file_path);

        // Ensure env prefix is NOT applied yet
        std::env::set_var("ST_PORT", "9999");

        // 2. Config<Raw>::merge() -> Config<Merged>
        let config_merged = config_raw.merge(Some("ST_")).unwrap();
        std::env::remove_var("ST_PORT");

        // Check that the merged TOML value is updated with the env override
        assert_eq!(config_merged.state.0["port"].as_integer(), Some(9999));
        assert_eq!(config_merged.path, file_path);

        // 3. Config<Merged>::deserialize() -> Config<Deserialized<ValidatedSimple>>
        let config_deser = config_merged.deserialize::<ValidatedSimple>().unwrap();
        assert_eq!(config_deser.state.0.name, "lifecycle");
        assert_eq!(config_deser.state.0.port, 9999);
        assert_eq!(config_deser.path, file_path);

        // 4. Config<Deserialized<T>>::validate() -> Config<Validated<T>>
        let config_val = config_deser.validate().unwrap();
        assert_eq!(config_val.state.0.port, 9999);
        assert_eq!(config_val.path, file_path);

        // 5. Config<Validated<T>>::freeze() -> Config<Frozen<T>>
        let config_frozen = config_val.freeze();
        assert_eq!(config_frozen.state.0.port, 9999);
        assert_eq!(config_frozen.path, file_path);
    }

    #[test]
    fn test_config_typestate_lifecycle_failure() {
        let dir = TempDir::new().unwrap();
        let file_path = write_toml(&dir, "app.toml", "name = \"\"\nport = 80\n"); // empty name, port out of range

        let config_raw = Loader::new().layer_file(&file_path).load_raw().unwrap();
        let config_merged = config_raw.merge(None).unwrap();
        let config_deser = config_merged.deserialize::<ValidatedSimple>().unwrap();

        let val_res = config_deser.validate();
        assert!(val_res.is_err());
        if let Err(Error::Invalid(errs)) = val_res {
            assert_eq!(errs.len(), 2);
            assert_eq!(errs.fitness(), 0.0); // 0 out of 2 checks passed
        } else {
            panic!("Expected Error::Invalid");
        }
    }

    #[test]
    fn test_trusted_loader_success() {
        let dir = TempDir::new().unwrap();
        let file_path = write_toml(&dir, "app.toml", "name = \"trusted\"\nport = 8080\n");

        std::env::set_var("TR_PORT", "1234");
        let trusted_config: TrustedConfig<ValidatedSimple> = trusted()
            .layer_str("name = \"default\"\nport = 9000\n", "defaults")
            .layer_file(&file_path)
            .env_prefix("TR_")
            .load()
            .unwrap();
        std::env::remove_var("TR_PORT");

        assert_eq!(trusted_config.value.name, "trusted");
        assert_eq!(trusted_config.value.port, 1234);
        assert_eq!(trusted_config.source.path, file_path);

        // ValidationReport check
        assert_eq!(trusted_config.validation.fitness, 1.0);
        assert_eq!(trusted_config.validation.checks_run, 2);
        assert_eq!(trusted_config.validation.checks_passed, 2);
        assert!(trusted_config.validation.errors.is_empty());

        // ConfigDigest check
        assert!(trusted_config.digest.0 > 0);
    }

    #[test]
    fn test_trusted_loader_validation_failure() {
        let dir = TempDir::new().unwrap();
        let file_path = write_toml(&dir, "app.toml", "name = \"\"\nport = 8080\n"); // name empty

        let res = trusted().layer_file(&file_path).load::<ValidatedSimple>();

        assert!(res.is_err());
        if let Err(Error::Invalid(errs)) = res {
            assert_eq!(errs.len(), 1);
            // 1 check passed (port), 1 check failed (name) -> fitness = 0.5
            assert_eq!(errs.fitness(), 0.5);
            assert_eq!(errs.errors()[0].code(), "empty");
        } else {
            panic!("Expected Error::Invalid");
        }
    }

    #[test]
    fn test_trusted_loader_digest_stability() {
        let dir = TempDir::new().unwrap();
        let file_path = write_toml(&dir, "app.toml", "name = \"stable\"\nport = 8080\n");

        let tc1 = trusted().layer_file(&file_path).load::<ValidatedSimple>().unwrap();

        let tc2 = trusted().layer_file(&file_path).load::<ValidatedSimple>().unwrap();

        assert_eq!(tc1.digest, tc2.digest);
    }

    #[derive(Debug, Deserialize, Serialize, PartialEq)]
    struct NestedTest {
        z: String,
        a: String,
        m: SubTest,
    }

    #[derive(Debug, Deserialize, Serialize, PartialEq)]
    struct SubTest {
        y: i32,
        b: i32,
    }

    impl Validate for NestedTest {
        fn validate(&self, _v: &mut crate::validation::Validator) {}
    }

    impl Validate for SubTest {
        fn validate(&self, _v: &mut crate::validation::Validator) {}
    }

    impl ConfigLifecycle for NestedTest {}
    impl ConfigLifecycle for SubTest {}

    #[test]
    fn test_save_pretty_and_save_file() {
        let dir = TempDir::new().unwrap();
        let pretty_path = dir.path().join("pretty.toml");
        let plain_path = dir.path().join("plain.toml");

        let original =
            NestedTest { z: "last".into(), a: "first".into(), m: SubTest { y: 10, b: 20 } };

        save_pretty(&original, &pretty_path).unwrap();
        save_file(&original, &plain_path).unwrap();

        assert!(pretty_path.exists());
        assert!(plain_path.exists());

        let pretty_content = std::fs::read_to_string(&pretty_path).unwrap();
        let plain_content = std::fs::read_to_string(&plain_path).unwrap();

        let reloaded_pretty: NestedTest = load_file(&pretty_path).unwrap();
        let reloaded_plain: NestedTest = load_file(&plain_path).unwrap();

        assert_eq!(reloaded_pretty, original);
        assert_eq!(reloaded_plain, original);

        assert!(pretty_content.len() >= plain_content.len());
    }

    #[test]
    fn test_save_canonical_sorting() {
        let dir = TempDir::new().unwrap();
        let canonical_path = dir.path().join("canonical.toml");

        let original =
            NestedTest { z: "last".into(), a: "first".into(), m: SubTest { y: 10, b: 20 } };

        let config_raw = Config::<Raw>::new("");
        let config_merged = config_raw.merge(None).unwrap();
        let config_val = Config::<Validated<NestedTest>>::new(original).unwrap();
        let config_frozen = config_val.freeze();

        config_frozen.save_canonical(&canonical_path).unwrap();
        assert!(canonical_path.exists());

        let canonical_content = std::fs::read_to_string(&canonical_path).unwrap();

        let pos_a = canonical_content.find("a =").expect("Key a not found");
        let pos_z = canonical_content.find("z =").expect("Key z not found");
        assert!(pos_a < pos_z, "Key 'a' must come before 'z' in canonical serialization");

        let pos_b = canonical_content.find("b =").expect("Key b not found");
        let pos_y = canonical_content.find("y =").expect("Key y not found");
        assert!(pos_b < pos_y, "Key 'b' must come before 'y' in canonical serialization");
    }

    #[derive(Debug, Deserialize, Serialize, PartialEq)]
    struct NormTest {
        name: String,
        port: u16,
    }

    impl Validate for NormTest {
        fn validate(&self, _v: &mut crate::validation::Validator) {}
    }

    impl ConfigLifecycle for NormTest {
        fn normalize(&mut self) {
            self.name = self.name.trim().to_string();
        }
        fn validate_lifecycle(&self, v: &mut crate::validation::Validator) {
            v.check_range("port", self.port, 1000..=9999);
        }
    }

    #[test]
    fn test_config_lifecycle_normalization_and_validation() {
        let raw = Config::<Raw>::new("name = '  spaces  '\nport = 2000");
        let merged = raw.merge(None).unwrap();
        let deserialized = merged.deserialize::<NormTest>().unwrap();
        assert_eq!(deserialized.get().name, "spaces");

        let val_res = deserialized.validate();
        assert!(val_res.is_ok());

        let raw_fail = Config::<Raw>::new("name = 'test'\nport = 80");
        let deserialized_fail = raw_fail.merge(None).unwrap().deserialize::<NormTest>().unwrap();
        let val_fail_res = deserialized_fail.validate();
        assert!(val_fail_res.is_err());
        if let Err(Error::Invalid(errs)) = val_fail_res {
            assert_eq!(errs.len(), 1);
            assert_eq!(errs.errors()[0].code(), "out_of_range");
            assert_eq!(errs.errors()[0].loc.to_string(), "port");
        } else {
            panic!("Expected Error::Invalid");
        }
    }
}