osp-cli 1.5.1

CLI and REPL for querying and managing OSP infrastructure data
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
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{Display, Formatter};
use std::sync::OnceLock;

use crate::config::ConfigError;
pub(crate) use crate::normalize::{normalize_identifier, normalize_optional_identifier};

/// Result details for an in-place TOML edit operation.
#[derive(Debug, Clone, PartialEq)]
pub struct TomlEditResult {
    /// Previous value removed or replaced by the edit, if one existed.
    pub previous: Option<ConfigValue>,
}

/// Origin of a resolved configuration value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ConfigSource {
    /// Built-in defaults compiled into the CLI.
    BuiltinDefaults,
    /// Presentation defaults derived from the active UI preset.
    PresentationDefaults,
    /// Values loaded from user configuration files.
    ConfigFile,
    /// Values loaded from the secrets layer, including secrets files and
    /// secret-specific environment overrides.
    Secrets,
    /// Values supplied through `OSP__...` environment variables.
    Environment,
    /// Values supplied on the current command line.
    Cli,
    /// Values recorded for the current interactive session.
    Session,
    /// Values derived internally during resolution.
    Derived,
}

impl Display for ConfigSource {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let value = match self {
            ConfigSource::BuiltinDefaults => "defaults",
            ConfigSource::PresentationDefaults => "presentation",
            ConfigSource::ConfigFile => "file",
            ConfigSource::Secrets => "secrets",
            ConfigSource::Environment => "env",
            ConfigSource::Cli => "cli",
            ConfigSource::Session => "session",
            ConfigSource::Derived => "derived",
        };
        write!(f, "{value}")
    }
}

/// Typed value stored in config layers and resolved output.
#[derive(Debug, Clone, PartialEq)]
pub enum ConfigValue {
    /// UTF-8 string value.
    String(String),
    /// Boolean value.
    Bool(bool),
    /// Signed 64-bit integer value.
    Integer(i64),
    /// 64-bit floating-point value.
    Float(f64),
    /// Ordered list of nested config values.
    List(Vec<ConfigValue>),
    /// Value wrapped for redacted display and debug output.
    Secret(SecretValue),
}

impl ConfigValue {
    /// Returns `true` when the value is wrapped as a secret.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::ConfigValue;
    ///
    /// assert!(!ConfigValue::String("alice".to_string()).is_secret());
    /// assert!(ConfigValue::String("alice".to_string()).into_secret().is_secret());
    /// ```
    pub fn is_secret(&self) -> bool {
        matches!(self, ConfigValue::Secret(_))
    }

    /// Returns the underlying value, unwrapping one secret layer if present.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::ConfigValue;
    ///
    /// let secret = ConfigValue::String("alice".to_string()).into_secret();
    /// assert_eq!(secret.reveal(), &ConfigValue::String("alice".to_string()));
    /// ```
    pub fn reveal(&self) -> &ConfigValue {
        match self {
            ConfigValue::Secret(secret) => secret.expose(),
            other => other,
        }
    }

    /// Wraps the value as a secret unless it is already secret.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::ConfigValue;
    ///
    /// let wrapped = ConfigValue::String("token".to_string()).into_secret();
    /// assert!(wrapped.is_secret());
    /// ```
    pub fn into_secret(self) -> ConfigValue {
        match self {
            ConfigValue::Secret(_) => self,
            other => ConfigValue::Secret(SecretValue::new(other)),
        }
    }

    pub(crate) fn from_toml(path: &str, value: &toml::Value) -> Result<Self, ConfigError> {
        match value {
            toml::Value::String(v) => Ok(Self::String(v.clone())),
            toml::Value::Integer(v) => Ok(Self::Integer(*v)),
            toml::Value::Float(v) => Ok(Self::Float(*v)),
            toml::Value::Boolean(v) => Ok(Self::Bool(*v)),
            toml::Value::Datetime(v) => Ok(Self::String(v.to_string())),
            toml::Value::Array(values) => {
                let mut out = Vec::with_capacity(values.len());
                for item in values {
                    out.push(Self::from_toml(path, item)?);
                }
                Ok(Self::List(out))
            }
            toml::Value::Table(_) => Err(ConfigError::UnsupportedTomlValue {
                path: path.to_string(),
                kind: "table".to_string(),
            }),
        }
    }

    pub(crate) fn as_interpolation_string(
        &self,
        key: &str,
        placeholder: &str,
    ) -> Result<String, ConfigError> {
        match self.reveal() {
            ConfigValue::String(value) => Ok(value.clone()),
            ConfigValue::Bool(value) => Ok(value.to_string()),
            ConfigValue::Integer(value) => Ok(value.to_string()),
            ConfigValue::Float(value) => Ok(value.to_string()),
            ConfigValue::List(_) => Err(ConfigError::NonScalarPlaceholder {
                key: key.to_string(),
                placeholder: placeholder.to_string(),
            }),
            ConfigValue::Secret(_) => Err(ConfigError::NonScalarPlaceholder {
                key: key.to_string(),
                placeholder: placeholder.to_string(),
            }),
        }
    }
}

/// Secret config value that redacts its display and debug output.
#[derive(Clone, PartialEq)]
pub struct SecretValue(Box<ConfigValue>);

impl SecretValue {
    /// Wraps a config value in a secret container.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::{ConfigValue, SecretValue};
    ///
    /// let secret = SecretValue::new(ConfigValue::String("hidden".to_string()));
    /// assert_eq!(secret.expose(), &ConfigValue::String("hidden".to_string()));
    /// ```
    pub fn new(value: ConfigValue) -> Self {
        Self(Box::new(value))
    }

    /// Returns the underlying unredacted value.
    pub fn expose(&self) -> &ConfigValue {
        &self.0
    }

    /// Consumes the wrapper and returns the inner value.
    pub fn into_inner(self) -> ConfigValue {
        *self.0
    }
}

impl std::fmt::Debug for SecretValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "[REDACTED]")
    }
}

impl Display for SecretValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "[REDACTED]")
    }
}

/// Schema-level type used for parsing and validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SchemaValueType {
    /// Scalar string value.
    String,
    /// Scalar boolean value.
    Bool,
    /// Scalar signed integer value.
    Integer,
    /// Scalar floating-point value.
    Float,
    /// List of string values.
    StringList,
}

impl Display for SchemaValueType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let value = match self {
            SchemaValueType::String => "string",
            SchemaValueType::Bool => "bool",
            SchemaValueType::Integer => "integer",
            SchemaValueType::Float => "float",
            SchemaValueType::StringList => "list",
        };
        write!(f, "{value}")
    }
}

/// Bootstrap stage in which a key must be resolved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BootstrapPhase {
    /// The key is needed before path-dependent config can be loaded.
    Path,
    /// The key is needed before the active profile can be finalized.
    Profile,
}

/// Scope restriction for bootstrap-only keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BootstrapScopeRule {
    /// The key is valid only in the global scope.
    GlobalOnly,
    /// The key is valid globally or in a terminal-only scope.
    GlobalOrTerminal,
}

/// Additional validation rule for bootstrap values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BootstrapValueRule {
    /// The value must be a string containing at least one non-whitespace character.
    NonEmptyString,
}

/// Bootstrap metadata derived from a schema entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BootstrapKeySpec {
    /// Canonical dotted config key.
    pub key: &'static str,
    /// Bootstrap phase in which the key is consulted.
    pub phase: BootstrapPhase,
    /// Whether the key also appears in the runtime-resolved config.
    pub runtime_visible: bool,
    /// Scope restriction enforced for the key.
    pub scope_rule: BootstrapScopeRule,
}

impl BootstrapKeySpec {
    fn allows_scope(&self, scope: &Scope) -> bool {
        match self.scope_rule {
            BootstrapScopeRule::GlobalOnly => scope.profile.is_none() && scope.terminal.is_none(),
            BootstrapScopeRule::GlobalOrTerminal => scope.profile.is_none(),
        }
    }
}

/// Schema definition for a single config key.
#[derive(Debug, Clone)]
#[must_use]
pub struct SchemaEntry {
    canonical_key: Option<&'static str>,
    doc: Option<&'static str>,
    value_type: SchemaValueType,
    required: bool,
    writable: bool,
    allowed_values: Option<Vec<String>>,
    runtime_visible: bool,
    bootstrap_phase: Option<BootstrapPhase>,
    bootstrap_scope_rule: Option<BootstrapScopeRule>,
    bootstrap_value_rule: Option<BootstrapValueRule>,
}

impl SchemaEntry {
    /// Starts a schema entry for string values.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::{SchemaEntry, SchemaValueType};
    ///
    /// let entry = SchemaEntry::string().required();
    /// assert_eq!(entry.value_type(), SchemaValueType::String);
    /// assert!(entry.runtime_visible());
    /// ```
    pub fn string() -> Self {
        Self {
            canonical_key: None,
            doc: None,
            value_type: SchemaValueType::String,
            required: false,
            writable: true,
            allowed_values: None,
            runtime_visible: true,
            bootstrap_phase: None,
            bootstrap_scope_rule: None,
            bootstrap_value_rule: None,
        }
    }

    /// Starts a schema entry for boolean values.
    pub fn boolean() -> Self {
        Self {
            canonical_key: None,
            doc: None,
            value_type: SchemaValueType::Bool,
            required: false,
            writable: true,
            allowed_values: None,
            runtime_visible: true,
            bootstrap_phase: None,
            bootstrap_scope_rule: None,
            bootstrap_value_rule: None,
        }
    }

    /// Starts a schema entry for integer values.
    pub fn integer() -> Self {
        Self {
            canonical_key: None,
            doc: None,
            value_type: SchemaValueType::Integer,
            required: false,
            writable: true,
            allowed_values: None,
            runtime_visible: true,
            bootstrap_phase: None,
            bootstrap_scope_rule: None,
            bootstrap_value_rule: None,
        }
    }

    /// Starts a schema entry for floating-point values.
    pub fn float() -> Self {
        Self {
            canonical_key: None,
            doc: None,
            value_type: SchemaValueType::Float,
            required: false,
            writable: true,
            allowed_values: None,
            runtime_visible: true,
            bootstrap_phase: None,
            bootstrap_scope_rule: None,
            bootstrap_value_rule: None,
        }
    }

    /// Starts a schema entry for lists of strings.
    pub fn string_list() -> Self {
        Self {
            canonical_key: None,
            doc: None,
            value_type: SchemaValueType::StringList,
            required: false,
            writable: true,
            allowed_values: None,
            runtime_visible: true,
            bootstrap_phase: None,
            bootstrap_scope_rule: None,
            bootstrap_value_rule: None,
        }
    }

    /// Marks the key as required in the resolved runtime view.
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// Marks the key as read-only for user-provided config sources.
    pub fn read_only(mut self) -> Self {
        self.writable = false;
        self
    }

    /// Attaches a human-readable description to the key.
    pub fn with_doc(mut self, doc: &'static str) -> Self {
        self.doc = Some(doc);
        self
    }

    /// Marks the key as bootstrap-only with the given phase and scope rule.
    pub fn bootstrap_only(mut self, phase: BootstrapPhase, scope_rule: BootstrapScopeRule) -> Self {
        self.runtime_visible = false;
        self.bootstrap_phase = Some(phase);
        self.bootstrap_scope_rule = Some(scope_rule);
        self
    }

    /// Adds a bootstrap-only value validation rule.
    pub fn with_bootstrap_value_rule(mut self, rule: BootstrapValueRule) -> Self {
        self.bootstrap_value_rule = Some(rule);
        self
    }

    /// Restricts accepted values using a case-insensitive allow-list.
    pub fn with_allowed_values<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.allowed_values = Some(
            values
                .into_iter()
                .map(|value| value.as_ref().to_ascii_lowercase())
                .collect(),
        );
        self
    }

    /// Returns the declared schema type for the key.
    pub fn value_type(&self) -> SchemaValueType {
        self.value_type
    }

    /// Returns the normalized allow-list, if the key is enumerated.
    pub fn allowed_values(&self) -> Option<&[String]> {
        self.allowed_values.as_deref()
    }

    /// Returns the human-readable description for the key, if one exists.
    pub fn doc(&self) -> Option<&'static str> {
        self.doc
    }

    /// Returns whether the key is visible in resolved runtime config.
    pub fn runtime_visible(&self) -> bool {
        self.runtime_visible
    }

    /// Returns whether the key can be written by user-controlled sources.
    pub fn writable(&self) -> bool {
        self.writable
    }

    fn with_canonical_key(mut self, key: &'static str) -> Self {
        self.canonical_key = Some(key);
        self
    }

    fn bootstrap_spec(&self) -> Option<BootstrapKeySpec> {
        Some(BootstrapKeySpec {
            key: self.canonical_key?,
            phase: self.bootstrap_phase?,
            runtime_visible: self.runtime_visible,
            scope_rule: self.bootstrap_scope_rule?,
        })
    }

    fn validate_bootstrap_value(&self, key: &str, value: &ConfigValue) -> Result<(), ConfigError> {
        match self.bootstrap_value_rule {
            Some(BootstrapValueRule::NonEmptyString) => match value.reveal() {
                ConfigValue::String(current) if !current.trim().is_empty() => Ok(()),
                ConfigValue::String(current) => Err(ConfigError::InvalidBootstrapValue {
                    key: key.to_string(),
                    reason: format!("expected a non-empty string, got {current:?}"),
                }),
                other => Err(ConfigError::InvalidBootstrapValue {
                    key: key.to_string(),
                    reason: format!("expected string, got {other:?}"),
                }),
            },
            None => Ok(()),
        }
    }
}

/// Config schema used for validation, parsing, and runtime filtering.
#[derive(Debug, Clone)]
pub struct ConfigSchema {
    entries: BTreeMap<String, SchemaEntry>,
    allow_extensions_namespace: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DynamicSchemaKeyKind {
    PluginCommandState,
    PluginCommandProvider,
}

impl Default for ConfigSchema {
    fn default() -> Self {
        builtin_config_schema().clone()
    }
}

impl ConfigSchema {
    fn builtin() -> Self {
        let mut schema = Self {
            entries: BTreeMap::new(),
            allow_extensions_namespace: true,
        };
        insert_identity_schema_keys(&mut schema);
        insert_ui_schema_keys(&mut schema);
        insert_repl_schema_keys(&mut schema);
        insert_color_schema_keys(&mut schema);
        insert_misc_schema_keys(&mut schema);

        schema
    }
}

fn insert_builtin_schema_key(
    schema: &mut ConfigSchema,
    key: &'static str,
    entry: SchemaEntry,
    doc: &'static str,
) {
    schema.insert(key, entry.with_doc(doc));
}

fn insert_identity_schema_keys(schema: &mut ConfigSchema) {
    insert_builtin_schema_key(
        schema,
        "profile.default",
        SchemaEntry::string()
            .bootstrap_only(
                BootstrapPhase::Profile,
                BootstrapScopeRule::GlobalOrTerminal,
            )
            .with_bootstrap_value_rule(BootstrapValueRule::NonEmptyString),
        "Default profile selected when no override is provided",
    );
    insert_builtin_schema_key(
        schema,
        "profile.active",
        SchemaEntry::string().required().read_only(),
        "Active profile derived during resolution",
    );
    insert_builtin_schema_key(
        schema,
        "theme.name",
        SchemaEntry::string(),
        "Name of the active color theme",
    );
    insert_builtin_schema_key(
        schema,
        "theme.path",
        SchemaEntry::string_list(),
        "Extra theme search paths",
    );
    insert_builtin_schema_key(
        schema,
        "user.name",
        SchemaEntry::string(),
        "Short user name used in prompts and interpolation",
    );
    insert_builtin_schema_key(
        schema,
        "user.display_name",
        SchemaEntry::string(),
        "Preferred display name for the current user",
    );
    insert_builtin_schema_key(
        schema,
        "user.full_name",
        SchemaEntry::string(),
        "Full name for the current user",
    );
    insert_builtin_schema_key(
        schema,
        "domain",
        SchemaEntry::string(),
        "Default domain name used in prompts and interpolation",
    );
}

fn insert_ui_schema_keys(schema: &mut ConfigSchema) {
    insert_builtin_schema_key(
        schema,
        "ui.format",
        SchemaEntry::string()
            .with_allowed_values(["auto", "guide", "json", "table", "md", "mreg", "value"]),
        "Default output format",
    );
    insert_builtin_schema_key(
        schema,
        "ui.mode",
        SchemaEntry::string().with_allowed_values(["auto", "plain", "rich"]),
        "Preferred render mode",
    );
    insert_builtin_schema_key(
        schema,
        "ui.presentation",
        SchemaEntry::string().with_allowed_values([
            "expressive",
            "compact",
            "austere",
            "gammel-og-bitter",
        ]),
        "UI presentation preset",
    );
    insert_builtin_schema_key(
        schema,
        "ui.color.mode",
        SchemaEntry::string().with_allowed_values(["auto", "always", "never"]),
        "Color rendering policy",
    );
    insert_builtin_schema_key(
        schema,
        "ui.unicode.mode",
        SchemaEntry::string().with_allowed_values(["auto", "always", "never"]),
        "Unicode rendering policy",
    );
    insert_builtin_schema_key(
        schema,
        "ui.width",
        SchemaEntry::integer(),
        "Default render width hint",
    );
    insert_builtin_schema_key(
        schema,
        "ui.margin",
        SchemaEntry::integer(),
        "Left margin used when rendering output",
    );
    insert_builtin_schema_key(
        schema,
        "ui.indent",
        SchemaEntry::integer(),
        "Indent width for nested output",
    );
    insert_builtin_schema_key(
        schema,
        "ui.help.level",
        SchemaEntry::string().with_allowed_values(["inherit", "none", "tiny", "normal", "verbose"]),
        "Help detail level or inherit",
    );
    insert_builtin_schema_key(
        schema,
        "ui.guide.default_format",
        SchemaEntry::string().with_allowed_values(["guide", "inherit", "none"]),
        "Guide rendering format used by help-like output",
    );
    insert_builtin_schema_key(
        schema,
        "ui.messages.layout",
        SchemaEntry::string().with_allowed_values([
            "full", "compact", "austere", "plain", "none", "grouped", "minimal",
        ]),
        "Message layout style",
    );
    insert_builtin_schema_key(
        schema,
        "ui.chrome.frame",
        SchemaEntry::string().with_allowed_values([
            "none",
            "top",
            "bottom",
            "top-bottom",
            "square",
            "round",
        ]),
        "Section chrome frame style",
    );
    insert_builtin_schema_key(
        schema,
        "ui.chrome.rule_policy",
        SchemaEntry::string().with_allowed_values([
            "per-section",
            "independent",
            "separate",
            "shared",
            "stacked",
            "list",
        ]),
        "How sibling section rules are shared",
    );
    insert_builtin_schema_key(
        schema,
        "ui.table.overflow",
        SchemaEntry::string().with_allowed_values([
            "clip", "hidden", "crop", "ellipsis", "truncate", "wrap", "none", "visible",
        ]),
        "Table overflow behavior",
    );
    insert_builtin_schema_key(
        schema,
        "ui.table.border",
        SchemaEntry::string().with_allowed_values(["none", "square", "round"]),
        "Table border style",
    );
    insert_builtin_schema_key(
        schema,
        "ui.help.table_chrome",
        SchemaEntry::string().with_allowed_values(["inherit", "none", "square", "round"]),
        "Help table chrome style or inherit",
    );
    insert_builtin_schema_key(
        schema,
        "ui.help.entry_indent",
        SchemaEntry::string(),
        "Help entry indent override or inherit",
    );
    insert_builtin_schema_key(
        schema,
        "ui.help.entry_gap",
        SchemaEntry::string(),
        "Help entry gap override or inherit",
    );
    insert_builtin_schema_key(
        schema,
        "ui.help.section_spacing",
        SchemaEntry::string(),
        "Help section spacing override or inherit",
    );
    insert_builtin_schema_key(
        schema,
        "ui.short_list_max",
        SchemaEntry::integer(),
        "Maximum items rendered as a short list",
    );
    insert_builtin_schema_key(
        schema,
        "ui.medium_list_max",
        SchemaEntry::integer(),
        "Maximum items rendered as a medium list",
    );
    insert_builtin_schema_key(
        schema,
        "ui.grid_padding",
        SchemaEntry::integer(),
        "Padding between rendered grid columns",
    );
    insert_builtin_schema_key(
        schema,
        "ui.grid_columns",
        SchemaEntry::integer(),
        "Fixed grid column count when set",
    );
    insert_builtin_schema_key(
        schema,
        "ui.column_weight",
        SchemaEntry::integer(),
        "Relative weight used for adaptive columns",
    );
    insert_builtin_schema_key(
        schema,
        "ui.mreg.stack_min_col_width",
        SchemaEntry::integer(),
        "Minimum column width before MREG stacks columns",
    );
    insert_builtin_schema_key(
        schema,
        "ui.mreg.stack_overflow_ratio",
        SchemaEntry::integer(),
        "Overflow ratio threshold for stacked MREG output",
    );
    insert_builtin_schema_key(
        schema,
        "ui.message.verbosity",
        SchemaEntry::string().with_allowed_values(["error", "warning", "success", "info", "trace"]),
        "Default message verbosity level",
    );
    insert_builtin_schema_key(
        schema,
        "ui.prompt",
        SchemaEntry::string(),
        "Prompt template used by the UI",
    );
    insert_builtin_schema_key(
        schema,
        "ui.prompt.secrets",
        SchemaEntry::boolean(),
        "Whether prompts may reveal secret values",
    );
    insert_builtin_schema_key(
        schema,
        "extensions.plugins.timeout_ms",
        SchemaEntry::integer(),
        "Plugin process timeout in milliseconds",
    );
    insert_builtin_schema_key(
        schema,
        "extensions.plugins.discovery.path",
        SchemaEntry::boolean(),
        "Whether plugin discovery should scan PATH",
    );
}

fn insert_repl_schema_keys(schema: &mut ConfigSchema) {
    insert_builtin_schema_key(
        schema,
        "repl.prompt",
        SchemaEntry::string(),
        "Prompt template used by the REPL",
    );
    insert_builtin_schema_key(
        schema,
        "repl.prompt_right",
        SchemaEntry::string(),
        "Right-hand prompt template used by the REPL",
    );
    insert_builtin_schema_key(
        schema,
        "repl.input_mode",
        SchemaEntry::string().with_allowed_values(["auto", "interactive", "basic"]),
        "REPL input mode",
    );
    insert_builtin_schema_key(
        schema,
        "repl.simple_prompt",
        SchemaEntry::boolean(),
        "Whether the REPL should use the simple prompt",
    );
    insert_builtin_schema_key(
        schema,
        "repl.shell_indicator",
        SchemaEntry::string(),
        "Template for the current shell indicator",
    );
    insert_builtin_schema_key(
        schema,
        "repl.intro",
        SchemaEntry::string().with_allowed_values(["none", "minimal", "compact", "full"]),
        "REPL intro detail level",
    );
    insert_builtin_schema_key(
        schema,
        "repl.intro_template.minimal",
        SchemaEntry::string(),
        "Template for the minimal REPL intro",
    );
    insert_builtin_schema_key(
        schema,
        "repl.intro_template.compact",
        SchemaEntry::string(),
        "Template for the compact REPL intro",
    );
    insert_builtin_schema_key(
        schema,
        "repl.intro_template.full",
        SchemaEntry::string(),
        "Template for the full REPL intro",
    );
    insert_builtin_schema_key(
        schema,
        "repl.history.path",
        SchemaEntry::string(),
        "Path to the persistent REPL history file",
    );
    insert_builtin_schema_key(
        schema,
        "repl.history.max_entries",
        SchemaEntry::integer(),
        "Maximum number of persisted REPL history entries",
    );
    insert_builtin_schema_key(
        schema,
        "repl.history.enabled",
        SchemaEntry::boolean(),
        "Whether persistent REPL history is enabled",
    );
    insert_builtin_schema_key(
        schema,
        "repl.history.dedupe",
        SchemaEntry::boolean(),
        "Whether duplicate history entries are collapsed",
    );
    insert_builtin_schema_key(
        schema,
        "repl.history.profile_scoped",
        SchemaEntry::boolean(),
        "Whether history files are scoped by profile",
    );
    insert_builtin_schema_key(
        schema,
        "repl.history.menu_rows",
        SchemaEntry::integer(),
        "Maximum rows shown in the history menu",
    );
    insert_builtin_schema_key(
        schema,
        "repl.history.exclude",
        SchemaEntry::string_list(),
        "Commands excluded from persisted history",
    );
    insert_builtin_schema_key(
        schema,
        "session.cache.max_results",
        SchemaEntry::integer(),
        "Maximum cached session results",
    );
}

fn insert_color_schema_keys(schema: &mut ConfigSchema) {
    insert_builtin_schema_key(
        schema,
        "color.prompt.text",
        SchemaEntry::string(),
        "Prompt text color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.prompt.command",
        SchemaEntry::string(),
        "Prompt command color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.prompt.completion.text",
        SchemaEntry::string(),
        "Completion text color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.prompt.completion.background",
        SchemaEntry::string(),
        "Completion background color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.prompt.completion.highlight",
        SchemaEntry::string(),
        "Completion highlight color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.text",
        SchemaEntry::string(),
        "Primary text color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.text.muted",
        SchemaEntry::string(),
        "Muted text color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.key",
        SchemaEntry::string(),
        "Key label color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.border",
        SchemaEntry::string(),
        "Border color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.table.header",
        SchemaEntry::string(),
        "Table header color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.mreg.key",
        SchemaEntry::string(),
        "MREG key color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.value",
        SchemaEntry::string(),
        "Value color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.value.number",
        SchemaEntry::string(),
        "Numeric value color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.value.bool_true",
        SchemaEntry::string(),
        "True boolean color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.value.bool_false",
        SchemaEntry::string(),
        "False boolean color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.value.null",
        SchemaEntry::string(),
        "Null value color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.value.ipv4",
        SchemaEntry::string(),
        "IPv4 value color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.value.ipv6",
        SchemaEntry::string(),
        "IPv6 value color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.panel.border",
        SchemaEntry::string(),
        "Panel border color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.panel.title",
        SchemaEntry::string(),
        "Panel title color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.code",
        SchemaEntry::string(),
        "Code block color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.json.key",
        SchemaEntry::string(),
        "JSON key color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.message.error",
        SchemaEntry::string(),
        "Error message color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.message.warning",
        SchemaEntry::string(),
        "Warning message color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.message.success",
        SchemaEntry::string(),
        "Success message color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.message.info",
        SchemaEntry::string(),
        "Info message color override",
    );
    insert_builtin_schema_key(
        schema,
        "color.message.trace",
        SchemaEntry::string(),
        "Trace message color override",
    );
}

fn insert_misc_schema_keys(schema: &mut ConfigSchema) {
    insert_builtin_schema_key(
        schema,
        "auth.visible.builtins",
        SchemaEntry::string(),
        "Visible builtin auth command allow-list",
    );
    insert_builtin_schema_key(
        schema,
        "auth.visible.plugins",
        SchemaEntry::string(),
        "Visible plugin auth command allow-list",
    );
    insert_builtin_schema_key(
        schema,
        "debug.level",
        SchemaEntry::integer(),
        "Developer debug verbosity",
    );
    insert_builtin_schema_key(
        schema,
        "log.file.enabled",
        SchemaEntry::boolean(),
        "Whether file logging is enabled",
    );
    insert_builtin_schema_key(
        schema,
        "log.file.path",
        SchemaEntry::string(),
        "Path to the runtime log file",
    );
    insert_builtin_schema_key(
        schema,
        "log.file.level",
        SchemaEntry::string().with_allowed_values(["error", "warn", "info", "debug", "trace"]),
        "Minimum log level written to the log file",
    );
    insert_builtin_schema_key(
        schema,
        "base.dir",
        SchemaEntry::string(),
        "Base directory available for interpolation and tooling",
    );
}

impl ConfigSchema {
    /// Registers or replaces a schema entry for a canonical key.
    pub fn insert(&mut self, key: &'static str, entry: SchemaEntry) {
        self.entries
            .insert(key.to_string(), entry.with_canonical_key(key));
    }

    /// Enables or disables the `extensions.*` namespace shortcut.
    pub fn set_allow_extensions_namespace(&mut self, value: bool) {
        self.allow_extensions_namespace = value;
    }

    /// Returns whether the key is recognized by the schema.
    pub fn is_known_key(&self, key: &str) -> bool {
        self.entries.contains_key(key)
            || self.is_extension_key(key)
            || self.is_alias_key(key)
            || dynamic_schema_key_kind(key).is_some()
    }

    /// Returns whether the key can appear in resolved runtime output.
    pub fn is_runtime_visible_key(&self, key: &str) -> bool {
        self.entries
            .get(key)
            .is_some_and(SchemaEntry::runtime_visible)
            || self.is_extension_key(key)
            || dynamic_schema_key_kind(key).is_some()
    }

    /// Rejects read-only keys for user-supplied config input.
    pub fn validate_writable_key(&self, key: &str) -> Result<(), ConfigError> {
        let normalized = key.trim().to_ascii_lowercase();
        if let Some(entry) = self.entries.get(&normalized)
            && !entry.writable()
        {
            return Err(ConfigError::ReadOnlyConfigKey {
                key: normalized,
                reason: "derived at runtime".to_string(),
            });
        }
        Ok(())
    }

    /// Returns bootstrap metadata for the key, if it has bootstrap semantics.
    pub fn bootstrap_key_spec(&self, key: &str) -> Option<BootstrapKeySpec> {
        let normalized = key.trim().to_ascii_lowercase();
        self.entries
            .get(&normalized)
            .and_then(SchemaEntry::bootstrap_spec)
    }

    /// Iterates over canonical schema entries.
    pub fn entries(&self) -> impl Iterator<Item = (&str, &SchemaEntry)> {
        self.entries
            .iter()
            .map(|(key, entry)| (key.as_str(), entry))
    }

    /// Returns the schema-owned description for a key, if one exists.
    pub fn doc_for_key(&self, key: &str) -> Option<&'static str> {
        let normalized = key.trim().to_ascii_lowercase();
        self.entries.get(&normalized).and_then(SchemaEntry::doc)
    }

    /// Returns the expected runtime type for a key.
    pub fn expected_type(&self, key: &str) -> Option<SchemaValueType> {
        self.entries
            .get(key)
            .map(|entry| entry.value_type)
            .or_else(|| dynamic_schema_key_kind(key).map(|_| SchemaValueType::String))
    }

    /// Parses a raw string into the schema's typed config representation.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::{ConfigSchema, ConfigValue};
    ///
    /// let schema = ConfigSchema::default();
    /// assert_eq!(
    ///     schema.parse_input_value("repl.history.enabled", "true").unwrap(),
    ///     ConfigValue::Bool(true)
    /// );
    /// assert_eq!(
    ///     schema.parse_input_value("theme.name", "dracula").unwrap(),
    ///     ConfigValue::String("dracula".to_string())
    /// );
    /// ```
    pub fn parse_input_value(&self, key: &str, raw: &str) -> Result<ConfigValue, ConfigError> {
        if !self.is_known_key(key) {
            return Err(ConfigError::UnknownConfigKeys {
                keys: vec![key.to_string()],
            });
        }
        self.validate_writable_key(key)?;

        let value = match self.expected_type(key) {
            Some(SchemaValueType::String) | None => ConfigValue::String(raw.to_string()),
            Some(SchemaValueType::Bool) => {
                ConfigValue::Bool(
                    parse_bool(raw).ok_or_else(|| ConfigError::InvalidValueType {
                        key: key.to_string(),
                        expected: SchemaValueType::Bool,
                        actual: "string".to_string(),
                    })?,
                )
            }
            Some(SchemaValueType::Integer) => {
                let parsed =
                    raw.trim()
                        .parse::<i64>()
                        .map_err(|_| ConfigError::InvalidValueType {
                            key: key.to_string(),
                            expected: SchemaValueType::Integer,
                            actual: "string".to_string(),
                        })?;
                ConfigValue::Integer(parsed)
            }
            Some(SchemaValueType::Float) => {
                let parsed =
                    raw.trim()
                        .parse::<f64>()
                        .map_err(|_| ConfigError::InvalidValueType {
                            key: key.to_string(),
                            expected: SchemaValueType::Float,
                            actual: "string".to_string(),
                        })?;
                ConfigValue::Float(parsed)
            }
            Some(SchemaValueType::StringList) => {
                let items = parse_string_list(raw);
                ConfigValue::List(items.into_iter().map(ConfigValue::String).collect())
            }
        };

        if let Some(entry) = self.entries.get(key) {
            validate_allowed_values(
                key,
                &value,
                entry
                    .allowed_values()
                    .map(|values| values.iter().map(String::as_str).collect::<Vec<_>>())
                    .as_deref(),
            )?;
        } else if let Some(DynamicSchemaKeyKind::PluginCommandState) = dynamic_schema_key_kind(key)
        {
            validate_allowed_values(key, &value, Some(&["enabled", "disabled"]))?;
        }

        Ok(value)
    }

    pub(crate) fn validate_and_adapt(
        &self,
        values: &mut BTreeMap<String, ResolvedValue>,
    ) -> Result<(), ConfigError> {
        let mut unknown = Vec::new();
        for key in values.keys() {
            if self.is_runtime_visible_key(key) {
                continue;
            }
            unknown.push(key.clone());
        }
        if !unknown.is_empty() {
            unknown.sort();
            return Err(ConfigError::UnknownConfigKeys { keys: unknown });
        }

        for (key, entry) in &self.entries {
            if entry.runtime_visible && entry.required && !values.contains_key(key) {
                return Err(ConfigError::MissingRequiredKey { key: key.clone() });
            }
        }

        for (key, resolved) in values.iter_mut() {
            if let Some(kind) = dynamic_schema_key_kind(key) {
                resolved.value = adapt_dynamic_value_for_schema(key, &resolved.value, kind)?;
                continue;
            }
            let Some(schema_entry) = self.entries.get(key) else {
                continue;
            };
            if !schema_entry.runtime_visible {
                continue;
            }
            resolved.value = adapt_value_for_schema(key, &resolved.value, schema_entry)?;
        }

        Ok(())
    }

    fn is_extension_key(&self, key: &str) -> bool {
        self.allow_extensions_namespace && key.starts_with("extensions.")
    }

    fn is_alias_key(&self, key: &str) -> bool {
        key.starts_with("alias.")
    }

    /// Validates that a key is allowed in the provided scope.
    pub fn validate_key_scope(&self, key: &str, scope: &Scope) -> Result<(), ConfigError> {
        let normalized_scope = normalize_scope(scope.clone());
        if let Some(spec) = self.bootstrap_key_spec(key)
            && !spec.allows_scope(&normalized_scope)
        {
            return Err(ConfigError::InvalidBootstrapScope {
                key: spec.key.to_string(),
                profile: normalized_scope.profile,
                terminal: normalized_scope.terminal,
            });
        }

        Ok(())
    }

    /// Validates bootstrap-only value rules for a key.
    pub fn validate_bootstrap_value(
        &self,
        key: &str,
        value: &ConfigValue,
    ) -> Result<(), ConfigError> {
        let normalized = key.trim().to_ascii_lowercase();
        let Some(entry) = self.entries.get(&normalized) else {
            return Ok(());
        };
        entry.validate_bootstrap_value(&normalized, value)
    }
}

fn builtin_config_schema() -> &'static ConfigSchema {
    static BUILTIN_SCHEMA: OnceLock<ConfigSchema> = OnceLock::new();
    BUILTIN_SCHEMA.get_or_init(ConfigSchema::builtin)
}

impl Display for ConfigValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigValue::String(v) => write!(f, "{v}"),
            ConfigValue::Bool(v) => write!(f, "{v}"),
            ConfigValue::Integer(v) => write!(f, "{v}"),
            ConfigValue::Float(v) => write!(f, "{v}"),
            ConfigValue::List(v) => {
                let joined = v
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<String>>()
                    .join(",");
                write!(f, "[{joined}]")
            }
            ConfigValue::Secret(secret) => write!(f, "{secret}"),
        }
    }
}

impl From<&str> for ConfigValue {
    fn from(value: &str) -> Self {
        ConfigValue::String(value.to_string())
    }
}

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

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

impl From<i64> for ConfigValue {
    fn from(value: i64) -> Self {
        ConfigValue::Integer(value)
    }
}

impl From<f64> for ConfigValue {
    fn from(value: f64) -> Self {
        ConfigValue::Float(value)
    }
}

impl From<Vec<String>> for ConfigValue {
    fn from(values: Vec<String>) -> Self {
        ConfigValue::List(values.into_iter().map(ConfigValue::String).collect())
    }
}

/// Scope selector used when storing or resolving config entries.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Scope {
    /// Profile selector, normalized to the canonical profile identifier.
    pub profile: Option<String>,
    /// Terminal selector, normalized to the canonical terminal identifier.
    pub terminal: Option<String>,
}

impl Scope {
    /// Creates an unscoped selector.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::Scope;
    ///
    /// assert_eq!(Scope::global(), Scope::default());
    /// ```
    pub fn global() -> Self {
        Self::default()
    }

    /// Creates a selector scoped to one profile.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::Scope;
    ///
    /// let scope = Scope::profile("TSD");
    /// assert_eq!(scope.profile.as_deref(), Some("tsd"));
    /// assert_eq!(scope.terminal, None);
    /// ```
    pub fn profile(profile: &str) -> Self {
        Self {
            profile: Some(normalize_identifier(profile)),
            terminal: None,
        }
    }

    /// Creates a selector scoped to one terminal kind.
    pub fn terminal(terminal: &str) -> Self {
        Self {
            profile: None,
            terminal: Some(normalize_identifier(terminal)),
        }
    }

    /// Creates a selector scoped to both profile and terminal.
    pub fn profile_terminal(profile: &str, terminal: &str) -> Self {
        Self {
            profile: Some(normalize_identifier(profile)),
            terminal: Some(normalize_identifier(terminal)),
        }
    }
}

/// Single entry stored inside a config layer.
#[derive(Debug, Clone, PartialEq)]
pub struct LayerEntry {
    /// Canonical config key.
    pub key: String,
    /// Stored value for the key in this layer.
    pub value: ConfigValue,
    /// Scope attached to the entry.
    pub scope: Scope,
    /// External origin label such as an environment variable name.
    pub origin: Option<String>,
}

/// Ordered collection of config entries from one source layer.
#[derive(Debug, Clone, Default)]
pub struct ConfigLayer {
    pub(crate) entries: Vec<LayerEntry>,
}

impl ConfigLayer {
    /// Returns the entries in insertion order.
    pub fn entries(&self) -> &[LayerEntry] {
        &self.entries
    }

    /// Appends every entry from another layer in insertion order.
    ///
    /// Later entries from `other` win over earlier entries in this layer when
    /// the resolver evaluates duplicate keys from the same source layer.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::ConfigLayer;
    ///
    /// let mut base = ConfigLayer::default();
    /// base.set("theme.name", "dracula");
    ///
    /// let mut site = ConfigLayer::default();
    /// site.set("extensions.site.enabled", true);
    /// site.set("theme.name", "nord");
    ///
    /// base.extend_from_layer(&site);
    ///
    /// assert_eq!(base.entries().len(), 3);
    /// assert_eq!(base.entries()[2].key, "theme.name");
    /// assert_eq!(base.entries()[2].value.to_string(), "nord");
    /// ```
    pub fn extend_from_layer(&mut self, other: &ConfigLayer) {
        self.entries.extend(other.entries().iter().cloned());
    }

    /// Inserts a global entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::{ConfigLayer, Scope};
    ///
    /// let mut layer = ConfigLayer::default();
    /// layer.set("theme.name", "dracula");
    ///
    /// let entry = &layer.entries()[0];
    /// assert_eq!(entry.key, "theme.name");
    /// assert_eq!(entry.scope, Scope::global());
    /// ```
    pub fn set<K, V>(&mut self, key: K, value: V)
    where
        K: Into<String>,
        V: Into<ConfigValue>,
    {
        self.insert(key, value, Scope::global());
    }

    /// Inserts an entry scoped to a profile.
    pub fn set_for_profile<K, V>(&mut self, profile: &str, key: K, value: V)
    where
        K: Into<String>,
        V: Into<ConfigValue>,
    {
        self.insert(key, value, Scope::profile(profile));
    }

    /// Inserts an entry scoped to a terminal.
    pub fn set_for_terminal<K, V>(&mut self, terminal: &str, key: K, value: V)
    where
        K: Into<String>,
        V: Into<ConfigValue>,
    {
        self.insert(key, value, Scope::terminal(terminal));
    }

    /// Inserts an entry scoped to both profile and terminal.
    pub fn set_for_profile_terminal<K, V>(
        &mut self,
        profile: &str,
        terminal: &str,
        key: K,
        value: V,
    ) where
        K: Into<String>,
        V: Into<ConfigValue>,
    {
        self.insert(key, value, Scope::profile_terminal(profile, terminal));
    }

    /// Inserts an entry with an explicit scope.
    pub fn insert<K, V>(&mut self, key: K, value: V, scope: Scope)
    where
        K: Into<String>,
        V: Into<ConfigValue>,
    {
        self.entries.push(LayerEntry {
            key: key.into(),
            value: value.into(),
            scope: normalize_scope(scope),
            origin: None,
        });
    }

    /// Inserts an entry and records its external origin.
    pub fn insert_with_origin<K, V, O>(&mut self, key: K, value: V, scope: Scope, origin: Option<O>)
    where
        K: Into<String>,
        V: Into<ConfigValue>,
        O: Into<String>,
    {
        self.entries.push(LayerEntry {
            key: key.into(),
            value: value.into(),
            scope: normalize_scope(scope),
            origin: origin.map(Into::into),
        });
    }

    /// Marks every entry in the layer as secret.
    pub fn mark_all_secret(&mut self) {
        for entry in &mut self.entries {
            if !entry.value.is_secret() {
                entry.value = entry.value.clone().into_secret();
            }
        }
    }

    /// Removes the last matching entry for a key and scope.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::{ConfigLayer, ConfigValue, Scope};
    ///
    /// let mut layer = ConfigLayer::default();
    /// layer.set("theme.name", "catppuccin");
    /// layer.set("theme.name", "dracula");
    ///
    /// let removed = layer.remove_scoped("theme.name", &Scope::global());
    /// assert_eq!(removed, Some(ConfigValue::String("dracula".to_string())));
    /// ```
    pub fn remove_scoped(&mut self, key: &str, scope: &Scope) -> Option<ConfigValue> {
        let normalized_scope = normalize_scope(scope.clone());
        let index = self
            .entries
            .iter()
            .rposition(|entry| entry.key == key && entry.scope == normalized_scope)?;
        Some(self.entries.remove(index).value)
    }

    /// Parses a config layer from the project's TOML layout.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::ConfigLayer;
    ///
    /// let layer = ConfigLayer::from_toml_str(r#"
    /// [default]
    /// theme.name = "dracula"
    ///
    /// [profile.tsd]
    /// ui.format = "json"
    /// "#).unwrap();
    ///
    /// assert_eq!(layer.entries().len(), 2);
    /// ```
    pub fn from_toml_str(raw: &str) -> Result<Self, ConfigError> {
        let parsed = raw
            .parse::<toml::Value>()
            .map_err(|err| ConfigError::TomlParse(err.to_string()))?;

        let root = parsed.as_table().ok_or(ConfigError::TomlRootMustBeTable)?;
        let mut layer = ConfigLayer::default();

        for (section, value) in root {
            match section.as_str() {
                "default" => {
                    let table = value
                        .as_table()
                        .ok_or_else(|| ConfigError::InvalidSection {
                            section: "default".to_string(),
                            expected: "table".to_string(),
                        })?;
                    flatten_table(&mut layer, table, "", &Scope::global())?;
                }
                "profile" => {
                    let profiles = value
                        .as_table()
                        .ok_or_else(|| ConfigError::InvalidSection {
                            section: "profile".to_string(),
                            expected: "table".to_string(),
                        })?;
                    for (profile, profile_table_value) in profiles {
                        let profile_table = profile_table_value.as_table().ok_or_else(|| {
                            ConfigError::InvalidSection {
                                section: format!("profile.{profile}"),
                                expected: "table".to_string(),
                            }
                        })?;
                        flatten_table(&mut layer, profile_table, "", &Scope::profile(profile))?;
                    }
                }
                "terminal" => {
                    let terminals =
                        value
                            .as_table()
                            .ok_or_else(|| ConfigError::InvalidSection {
                                section: "terminal".to_string(),
                                expected: "table".to_string(),
                            })?;

                    for (terminal, terminal_table_value) in terminals {
                        let terminal_table = terminal_table_value.as_table().ok_or_else(|| {
                            ConfigError::InvalidSection {
                                section: format!("terminal.{terminal}"),
                                expected: "table".to_string(),
                            }
                        })?;

                        for (key, terminal_value) in terminal_table {
                            if key == "profile" {
                                continue;
                            }

                            flatten_key_value(
                                &mut layer,
                                key,
                                terminal_value,
                                &Scope::terminal(terminal),
                            )?;
                        }

                        if let Some(profile_section) = terminal_table.get("profile") {
                            let profile_tables = profile_section.as_table().ok_or_else(|| {
                                ConfigError::InvalidSection {
                                    section: format!("terminal.{terminal}.profile"),
                                    expected: "table".to_string(),
                                }
                            })?;

                            for (profile_key, profile_value) in profile_tables {
                                if let Some(profile_table) = profile_value.as_table() {
                                    flatten_table(
                                        &mut layer,
                                        profile_table,
                                        "",
                                        &Scope::profile_terminal(profile_key, terminal),
                                    )?;
                                } else {
                                    flatten_key_value(
                                        &mut layer,
                                        &format!("profile.{profile_key}"),
                                        profile_value,
                                        &Scope::terminal(terminal),
                                    )?;
                                }
                            }
                        }
                    }
                }
                unknown => {
                    return Err(ConfigError::UnknownTopLevelSection(unknown.to_string()));
                }
            }
        }

        Ok(layer)
    }

    /// Builds a config layer from `OSP__...` environment variables.
    pub fn from_env_iter<I, K, V>(vars: I) -> Result<Self, ConfigError>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let mut layer = ConfigLayer::default();

        for (name, value) in vars {
            let key = name.as_ref();
            if !key.starts_with("OSP__") {
                continue;
            }

            let spec = parse_env_key(key)?;
            builtin_config_schema().validate_writable_key(&spec.key)?;
            validate_key_scope(&spec.key, &spec.scope)?;
            let converted = ConfigValue::String(value.as_ref().to_string());
            validate_bootstrap_value(&spec.key, &converted)?;
            layer.insert_with_origin(spec.key, converted, spec.scope, Some(key.to_string()));
        }

        Ok(layer)
    }

    pub(crate) fn validate_entries(&self) -> Result<(), ConfigError> {
        for entry in &self.entries {
            builtin_config_schema().validate_writable_key(&entry.key)?;
            validate_key_scope(&entry.key, &entry.scope)?;
            validate_bootstrap_value(&entry.key, &entry.value)?;
        }

        Ok(())
    }
}

pub(crate) struct EnvKeySpec {
    pub(crate) key: String,
    pub(crate) scope: Scope,
}

/// Options that affect profile and terminal selection during resolution.
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct ResolveOptions {
    /// Explicit profile to use instead of the configured default profile.
    pub profile_override: Option<String>,
    /// Terminal selector used to include terminal-scoped entries.
    pub terminal: Option<String>,
}

impl ResolveOptions {
    /// Creates empty resolution options with no explicit profile or terminal.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::ResolveOptions;
    ///
    /// let options = ResolveOptions::new();
    /// assert_eq!(options.profile_override, None);
    /// assert_eq!(options.terminal, None);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Replaces the optional normalized profile override.
    pub fn with_profile_override(mut self, profile_override: Option<String>) -> Self {
        self.profile_override = normalize_optional_identifier(profile_override);
        self
    }

    /// Forces resolution to use the provided profile.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::ResolveOptions;
    ///
    /// let options = ResolveOptions::new().with_profile("TSD");
    /// assert_eq!(options.profile_override.as_deref(), Some("tsd"));
    /// ```
    pub fn with_profile(mut self, profile: &str) -> Self {
        self.profile_override = Some(normalize_identifier(profile));
        self
    }

    /// Resolves values for the provided terminal selector.
    pub fn with_terminal(mut self, terminal: &str) -> Self {
        self.terminal = Some(normalize_identifier(terminal));
        self
    }

    /// Replaces the optional normalized terminal selector.
    pub fn with_terminal_override(mut self, terminal: Option<String>) -> Self {
        self.terminal = normalize_optional_identifier(terminal);
        self
    }
}

/// Fully resolved value together with selection metadata.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedValue {
    /// Value before schema adaptation or interpolation.
    pub raw_value: ConfigValue,
    /// Final runtime value after adaptation and interpolation.
    pub value: ConfigValue,
    /// Source layer that contributed the selected value.
    pub source: ConfigSource,
    /// Scope of the selected entry.
    pub scope: Scope,
    /// External origin label for the selected entry, if tracked.
    pub origin: Option<String>,
}

/// Candidate entry considered while explaining a key.
#[derive(Debug, Clone, PartialEq)]
pub struct ExplainCandidate {
    /// Zero-based index of the entry within its layer.
    pub entry_index: usize,
    /// Candidate value before final selection.
    pub value: ConfigValue,
    /// Scope attached to the candidate entry.
    pub scope: Scope,
    /// External origin label for the candidate entry, if tracked.
    pub origin: Option<String>,
    /// Selection rank used by resolution, if one was assigned.
    pub rank: Option<u8>,
    /// Whether this candidate won selection within its layer.
    pub selected_in_layer: bool,
}

/// Per-layer explanation for a resolved or bootstrap key.
#[derive(Debug, Clone, PartialEq)]
pub struct ExplainLayer {
    /// Source represented by this explanation layer.
    pub source: ConfigSource,
    /// Index of the selected candidate within `candidates`, if any.
    pub selected_entry_index: Option<usize>,
    /// Candidate entries contributed by the layer.
    pub candidates: Vec<ExplainCandidate>,
}

/// Single placeholder expansion step captured by `config explain`.
#[derive(Debug, Clone, PartialEq)]
pub struct ExplainInterpolationStep {
    /// Placeholder name referenced by the template.
    pub placeholder: String,
    /// Placeholder value before schema adaptation or interpolation.
    pub raw_value: ConfigValue,
    /// Placeholder value after schema adaptation and interpolation.
    pub value: ConfigValue,
    /// Source layer that provided the placeholder value.
    pub source: ConfigSource,
    /// Scope of the entry that supplied the placeholder.
    pub scope: Scope,
    /// External origin label for the placeholder entry, if tracked.
    pub origin: Option<String>,
}

/// Interpolation trace for a resolved string value.
#[derive(Debug, Clone, PartialEq)]
pub struct ExplainInterpolation {
    /// Original string template before placeholder substitution.
    pub template: String,
    /// Placeholder expansion steps applied to the template.
    pub steps: Vec<ExplainInterpolationStep>,
}

/// Source used to determine the active profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActiveProfileSource {
    /// The active profile came from an explicit override.
    Override,
    /// The active profile came from `profile.default`.
    DefaultProfile,
}

impl ActiveProfileSource {
    /// Returns the stable string label used in explain output.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Override => "override",
            Self::DefaultProfile => "profile.default",
        }
    }
}

/// Human-readable explanation of runtime resolution for a single key.
#[derive(Debug, Clone, PartialEq)]
pub struct ConfigExplain {
    /// Canonical key being explained.
    pub key: String,
    /// Profile used during resolution.
    pub active_profile: String,
    /// Source used to determine `active_profile`.
    pub active_profile_source: ActiveProfileSource,
    /// Terminal selector used during resolution, if any.
    pub terminal: Option<String>,
    /// Profiles discovered across the evaluated layers.
    pub known_profiles: BTreeSet<String>,
    /// Per-layer candidate and selection details.
    pub layers: Vec<ExplainLayer>,
    /// Final resolved entry, if the key resolved successfully.
    pub final_entry: Option<ResolvedValue>,
    /// Interpolation trace for string results, if interpolation occurred.
    pub interpolation: Option<ExplainInterpolation>,
}

/// Human-readable explanation of bootstrap resolution for a single key.
#[derive(Debug, Clone, PartialEq)]
pub struct BootstrapConfigExplain {
    /// Canonical key being explained.
    pub key: String,
    /// Profile used during bootstrap resolution.
    pub active_profile: String,
    /// Source used to determine `active_profile`.
    pub active_profile_source: ActiveProfileSource,
    /// Terminal selector used during bootstrap resolution, if any.
    pub terminal: Option<String>,
    /// Profiles discovered across the evaluated layers.
    pub known_profiles: BTreeSet<String>,
    /// Per-layer candidate and selection details.
    pub layers: Vec<ExplainLayer>,
    /// Final bootstrap-resolved entry, if one was selected.
    pub final_entry: Option<ResolvedValue>,
}

/// Final resolved configuration view used at runtime.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedConfig {
    pub(crate) active_profile: String,
    pub(crate) terminal: Option<String>,
    pub(crate) known_profiles: BTreeSet<String>,
    pub(crate) values: BTreeMap<String, ResolvedValue>,
    pub(crate) aliases: BTreeMap<String, ResolvedValue>,
}

impl ResolvedConfig {
    /// Returns the profile selected for resolution.
    pub fn active_profile(&self) -> &str {
        &self.active_profile
    }

    /// Returns the terminal selector used during resolution, if any.
    pub fn terminal(&self) -> Option<&str> {
        self.terminal.as_deref()
    }

    /// Returns the set of profiles discovered across config layers.
    pub fn known_profiles(&self) -> &BTreeSet<String> {
        &self.known_profiles
    }

    /// Returns all resolved runtime-visible values.
    pub fn values(&self) -> &BTreeMap<String, ResolvedValue> {
        &self.values
    }

    /// Returns resolved alias entries excluded from normal runtime values.
    pub fn aliases(&self) -> &BTreeMap<String, ResolvedValue> {
        &self.aliases
    }

    /// Returns the resolved value for a key.
    pub fn get(&self, key: &str) -> Option<&ConfigValue> {
        self.values.get(key).map(|entry| &entry.value)
    }

    /// Returns the resolved string value for a key.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::{ConfigLayer, ConfigResolver, ResolveOptions};
    ///
    /// let mut defaults = ConfigLayer::default();
    /// defaults.set("profile.default", "default");
    /// defaults.set("theme.name", "dracula");
    ///
    /// let mut resolver = ConfigResolver::default();
    /// resolver.set_defaults(defaults);
    /// let resolved = resolver.resolve(ResolveOptions::default()).unwrap();
    ///
    /// assert_eq!(resolved.get_string("theme.name"), Some("dracula"));
    /// ```
    pub fn get_string(&self, key: &str) -> Option<&str> {
        match self.get(key).map(ConfigValue::reveal) {
            Some(ConfigValue::String(value)) => Some(value),
            _ => None,
        }
    }

    /// Returns the resolved boolean value for a key.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::{ConfigLayer, ConfigResolver, ResolveOptions};
    ///
    /// let mut defaults = ConfigLayer::default();
    /// defaults.set("profile.default", "default");
    /// defaults.set("repl.history.enabled", true);
    ///
    /// let mut resolver = ConfigResolver::default();
    /// resolver.set_defaults(defaults);
    /// let resolved = resolver.resolve(ResolveOptions::default()).unwrap();
    ///
    /// assert_eq!(resolved.get_bool("repl.history.enabled"), Some(true));
    /// ```
    pub fn get_bool(&self, key: &str) -> Option<bool> {
        match self.get(key).map(ConfigValue::reveal) {
            Some(ConfigValue::Bool(value)) => Some(*value),
            _ => None,
        }
    }

    /// Returns the resolved string list for a key.
    ///
    /// If the resolved value is a scalar string instead of a list, it is
    /// promoted to a single-element vector.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::{ConfigLayer, ConfigResolver, ResolveOptions};
    ///
    /// let mut defaults = ConfigLayer::default();
    /// defaults.set("profile.default", "default");
    /// defaults.set("theme.path", vec!["/tmp/themes".to_string()]);
    ///
    /// let mut resolver = ConfigResolver::default();
    /// resolver.set_defaults(defaults);
    /// let resolved = resolver.resolve(ResolveOptions::default()).unwrap();
    ///
    /// assert_eq!(
    ///     resolved.get_string_list("theme.path"),
    ///     Some(vec!["/tmp/themes".to_string()])
    /// );
    ///
    /// let mut defaults = ConfigLayer::default();
    /// defaults.set("profile.default", "default");
    /// defaults.set("theme.path", "/tmp/themes");
    ///
    /// let mut resolver = ConfigResolver::default();
    /// resolver.set_defaults(defaults);
    /// let resolved = resolver.resolve(ResolveOptions::default()).unwrap();
    ///
    /// assert_eq!(
    ///     resolved.get_string_list("theme.path"),
    ///     Some(vec!["/tmp/themes".to_string()])
    /// );
    /// ```
    pub fn get_string_list(&self, key: &str) -> Option<Vec<String>> {
        match self.get(key).map(ConfigValue::reveal) {
            Some(ConfigValue::List(values)) => Some(
                values
                    .iter()
                    .filter_map(|value| match value {
                        ConfigValue::String(text) => Some(text.clone()),
                        ConfigValue::Secret(secret) => match secret.expose() {
                            ConfigValue::String(text) => Some(text.clone()),
                            _ => None,
                        },
                        _ => None,
                    })
                    .collect(),
            ),
            Some(ConfigValue::String(value)) => Some(vec![value.clone()]),
            Some(ConfigValue::Secret(secret)) => match secret.expose() {
                ConfigValue::String(value) => Some(vec![value.clone()]),
                _ => None,
            },
            _ => None,
        }
    }

    /// Returns the full resolved entry for a runtime-visible key.
    pub fn get_value_entry(&self, key: &str) -> Option<&ResolvedValue> {
        self.values.get(key)
    }

    /// Returns the resolved alias entry for a key.
    pub fn get_alias_entry(&self, key: &str) -> Option<&ResolvedValue> {
        let normalized = if key.trim().to_ascii_lowercase().starts_with("alias.") {
            key.trim().to_ascii_lowercase()
        } else {
            format!("alias.{}", key.trim().to_ascii_lowercase())
        };
        self.aliases.get(&normalized)
    }
}

fn flatten_table(
    layer: &mut ConfigLayer,
    table: &toml::value::Table,
    prefix: &str,
    scope: &Scope,
) -> Result<(), ConfigError> {
    for (key, value) in table {
        let full_key = if prefix.is_empty() {
            key.to_string()
        } else {
            format!("{prefix}.{key}")
        };

        flatten_key_value(layer, &full_key, value, scope)?;
    }

    Ok(())
}

fn flatten_key_value(
    layer: &mut ConfigLayer,
    key: &str,
    value: &toml::Value,
    scope: &Scope,
) -> Result<(), ConfigError> {
    match value {
        toml::Value::Table(table) => flatten_table(layer, table, key, scope),
        _ => {
            let converted = ConfigValue::from_toml(key, value)?;
            builtin_config_schema().validate_writable_key(key)?;
            validate_key_scope(key, scope)?;
            validate_bootstrap_value(key, &converted)?;
            layer.insert(key.to_string(), converted, scope.clone());
            Ok(())
        }
    }
}

/// Looks up bootstrap-time metadata for a canonical config key.
pub fn bootstrap_key_spec(key: &str) -> Option<BootstrapKeySpec> {
    builtin_config_schema().bootstrap_key_spec(key)
}

/// Reports whether `key` is consumed during bootstrap but not exposed as a
/// normal runtime-resolved config key.
pub fn is_bootstrap_only_key(key: &str) -> bool {
    bootstrap_key_spec(key).is_some_and(|spec| !spec.runtime_visible)
}

/// Reports whether `key` belongs to the `alias.*` namespace.
///
/// # Examples
///
/// ```
/// use osp_cli::config::is_alias_key;
///
/// assert!(is_alias_key("alias.prod"));
/// assert!(is_alias_key(" Alias.User "));
/// assert!(!is_alias_key("ui.format"));
/// ```
pub fn is_alias_key(key: &str) -> bool {
    key.trim().to_ascii_lowercase().starts_with("alias.")
}

/// Validates that a key can be written in the provided scope.
pub fn validate_key_scope(key: &str, scope: &Scope) -> Result<(), ConfigError> {
    builtin_config_schema().validate_key_scope(key, scope)
}

/// Validates bootstrap-only value constraints for a key.
pub fn validate_bootstrap_value(key: &str, value: &ConfigValue) -> Result<(), ConfigError> {
    builtin_config_schema().validate_bootstrap_value(key, value)
}

fn adapt_value_for_schema(
    key: &str,
    value: &ConfigValue,
    schema: &SchemaEntry,
) -> Result<ConfigValue, ConfigError> {
    let (is_secret, value) = match value {
        ConfigValue::Secret(secret) => (true, secret.expose()),
        other => (false, other),
    };

    let adapted = match schema.value_type {
        SchemaValueType::String => match value {
            ConfigValue::String(value) => ConfigValue::String(value.clone()),
            other => {
                return Err(ConfigError::InvalidValueType {
                    key: key.to_string(),
                    expected: SchemaValueType::String,
                    actual: value_type_name(other).to_string(),
                });
            }
        },
        SchemaValueType::Bool => match value {
            ConfigValue::Bool(value) => ConfigValue::Bool(*value),
            ConfigValue::String(value) => {
                ConfigValue::Bool(parse_bool(value).ok_or_else(|| {
                    ConfigError::InvalidValueType {
                        key: key.to_string(),
                        expected: SchemaValueType::Bool,
                        actual: "string".to_string(),
                    }
                })?)
            }
            other => {
                return Err(ConfigError::InvalidValueType {
                    key: key.to_string(),
                    expected: SchemaValueType::Bool,
                    actual: value_type_name(other).to_string(),
                });
            }
        },
        SchemaValueType::Integer => match value {
            ConfigValue::Integer(value) => ConfigValue::Integer(*value),
            ConfigValue::String(value) => {
                let parsed =
                    value
                        .trim()
                        .parse::<i64>()
                        .map_err(|_| ConfigError::InvalidValueType {
                            key: key.to_string(),
                            expected: SchemaValueType::Integer,
                            actual: "string".to_string(),
                        })?;
                ConfigValue::Integer(parsed)
            }
            other => {
                return Err(ConfigError::InvalidValueType {
                    key: key.to_string(),
                    expected: SchemaValueType::Integer,
                    actual: value_type_name(other).to_string(),
                });
            }
        },
        SchemaValueType::Float => match value {
            ConfigValue::Float(value) => ConfigValue::Float(*value),
            ConfigValue::Integer(value) => ConfigValue::Float(*value as f64),
            ConfigValue::String(value) => {
                let parsed =
                    value
                        .trim()
                        .parse::<f64>()
                        .map_err(|_| ConfigError::InvalidValueType {
                            key: key.to_string(),
                            expected: SchemaValueType::Float,
                            actual: "string".to_string(),
                        })?;
                ConfigValue::Float(parsed)
            }
            other => {
                return Err(ConfigError::InvalidValueType {
                    key: key.to_string(),
                    expected: SchemaValueType::Float,
                    actual: value_type_name(other).to_string(),
                });
            }
        },
        SchemaValueType::StringList => match value {
            ConfigValue::List(values) => {
                let mut out = Vec::with_capacity(values.len());
                for value in values {
                    match value {
                        ConfigValue::String(value) => out.push(ConfigValue::String(value.clone())),
                        ConfigValue::Secret(secret) => match secret.expose() {
                            ConfigValue::String(value) => {
                                out.push(ConfigValue::String(value.clone()))
                            }
                            other => {
                                return Err(ConfigError::InvalidValueType {
                                    key: key.to_string(),
                                    expected: SchemaValueType::StringList,
                                    actual: value_type_name(other).to_string(),
                                });
                            }
                        },
                        other => {
                            return Err(ConfigError::InvalidValueType {
                                key: key.to_string(),
                                expected: SchemaValueType::StringList,
                                actual: value_type_name(other).to_string(),
                            });
                        }
                    }
                }
                ConfigValue::List(out)
            }
            ConfigValue::String(value) => {
                let items = parse_string_list(value);
                ConfigValue::List(items.into_iter().map(ConfigValue::String).collect())
            }
            ConfigValue::Secret(secret) => match secret.expose() {
                ConfigValue::String(value) => {
                    let items = parse_string_list(value);
                    ConfigValue::List(items.into_iter().map(ConfigValue::String).collect())
                }
                other => {
                    return Err(ConfigError::InvalidValueType {
                        key: key.to_string(),
                        expected: SchemaValueType::StringList,
                        actual: value_type_name(other).to_string(),
                    });
                }
            },
            other => {
                return Err(ConfigError::InvalidValueType {
                    key: key.to_string(),
                    expected: SchemaValueType::StringList,
                    actual: value_type_name(other).to_string(),
                });
            }
        },
    };

    let adapted = if is_secret {
        adapted.into_secret()
    } else {
        adapted
    };

    if let Some(allowed_values) = &schema.allowed_values
        && let ConfigValue::String(value) = adapted.reveal()
    {
        let normalized = value.to_ascii_lowercase();
        if !allowed_values.contains(&normalized) {
            return Err(ConfigError::InvalidEnumValue {
                key: key.to_string(),
                value: value.clone(),
                allowed: allowed_values.clone(),
            });
        }
    }

    Ok(adapted)
}

fn adapt_dynamic_value_for_schema(
    key: &str,
    value: &ConfigValue,
    kind: DynamicSchemaKeyKind,
) -> Result<ConfigValue, ConfigError> {
    let adapted = match kind {
        DynamicSchemaKeyKind::PluginCommandState | DynamicSchemaKeyKind::PluginCommandProvider => {
            adapt_value_for_schema(key, value, &SchemaEntry::string())?
        }
    };

    if matches!(kind, DynamicSchemaKeyKind::PluginCommandState) {
        validate_allowed_values(key, &adapted, Some(&["enabled", "disabled"]))?;
    }

    Ok(adapted)
}

fn validate_allowed_values(
    key: &str,
    value: &ConfigValue,
    allowed: Option<&[&str]>,
) -> Result<(), ConfigError> {
    let Some(allowed) = allowed else {
        return Ok(());
    };
    if let ConfigValue::String(current) = value {
        let normalized = current.to_ascii_lowercase();
        if !allowed.iter().any(|candidate| *candidate == normalized) {
            return Err(ConfigError::InvalidEnumValue {
                key: key.to_string(),
                value: current.clone(),
                allowed: allowed.iter().map(|value| (*value).to_string()).collect(),
            });
        }
    }
    Ok(())
}

fn dynamic_schema_key_kind(key: &str) -> Option<DynamicSchemaKeyKind> {
    let normalized = key.trim().to_ascii_lowercase();
    let remainder = normalized.strip_prefix("plugins.")?;
    let (command, field) = remainder.rsplit_once('.')?;
    if command.trim().is_empty() {
        return None;
    }
    match field {
        "state" => Some(DynamicSchemaKeyKind::PluginCommandState),
        "provider" => Some(DynamicSchemaKeyKind::PluginCommandProvider),
        _ => None,
    }
}

fn parse_bool(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "true" => Some(true),
        "false" => Some(false),
        _ => None,
    }
}

fn parse_string_list(value: &str) -> Vec<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Vec::new();
    }

    let inner = trimmed
        .strip_prefix('[')
        .and_then(|value| value.strip_suffix(']'))
        .unwrap_or(trimmed);

    inner
        .split(',')
        .map(|value| value.trim())
        .filter(|value| !value.is_empty())
        .map(|value| {
            value
                .strip_prefix('"')
                .and_then(|value| value.strip_suffix('"'))
                .or_else(|| {
                    value
                        .strip_prefix('\'')
                        .and_then(|value| value.strip_suffix('\''))
                })
                .unwrap_or(value)
                .to_string()
        })
        .collect()
}

fn value_type_name(value: &ConfigValue) -> &'static str {
    match value.reveal() {
        ConfigValue::String(_) => "string",
        ConfigValue::Bool(_) => "bool",
        ConfigValue::Integer(_) => "integer",
        ConfigValue::Float(_) => "float",
        ConfigValue::List(_) => "list",
        ConfigValue::Secret(_) => "string",
    }
}

pub(crate) fn parse_env_key(key: &str) -> Result<EnvKeySpec, ConfigError> {
    let Some(raw) = key.strip_prefix("OSP__") else {
        return Err(ConfigError::InvalidEnvOverride {
            key: key.to_string(),
            reason: "missing OSP__ prefix".to_string(),
        });
    };

    let parts = raw
        .split("__")
        .filter(|part| !part.is_empty())
        .collect::<Vec<&str>>();

    if parts.is_empty() {
        return Err(ConfigError::InvalidEnvOverride {
            key: key.to_string(),
            reason: "missing key path".to_string(),
        });
    }

    let mut cursor = 0usize;
    let mut terminal: Option<String> = None;
    let mut profile: Option<String> = None;

    while cursor < parts.len() {
        let part = parts[cursor];
        if part.eq_ignore_ascii_case("TERM") {
            if terminal.is_some() {
                return Err(ConfigError::InvalidEnvOverride {
                    key: key.to_string(),
                    reason: "TERM scope specified more than once".to_string(),
                });
            }
            let term = parts
                .get(cursor + 1)
                .ok_or_else(|| ConfigError::InvalidEnvOverride {
                    key: key.to_string(),
                    reason: "TERM requires a terminal name".to_string(),
                })?;
            terminal = Some(normalize_identifier(term));
            cursor += 2;
            continue;
        }

        if part.eq_ignore_ascii_case("PROFILE") {
            // `profile.default` is a bootstrap key, not a profile scope. Keep
            // the exception isolated here so the scope parser stays readable.
            if remaining_parts_are_bootstrap_profile_default(&parts[cursor..]) {
                break;
            }
            if profile.is_some() {
                return Err(ConfigError::InvalidEnvOverride {
                    key: key.to_string(),
                    reason: "PROFILE scope specified more than once".to_string(),
                });
            }
            let profile_name =
                parts
                    .get(cursor + 1)
                    .ok_or_else(|| ConfigError::InvalidEnvOverride {
                        key: key.to_string(),
                        reason: "PROFILE requires a profile name".to_string(),
                    })?;
            profile = Some(normalize_identifier(profile_name));
            cursor += 2;
            continue;
        }

        break;
    }

    let key_parts = &parts[cursor..];
    if key_parts.is_empty() {
        return Err(ConfigError::InvalidEnvOverride {
            key: key.to_string(),
            reason: "missing final config key".to_string(),
        });
    }

    let dotted_key = key_parts
        .iter()
        .map(|part| part.to_ascii_lowercase())
        .collect::<Vec<String>>()
        .join(".");

    Ok(EnvKeySpec {
        key: dotted_key,
        scope: Scope { profile, terminal },
    })
}

fn remaining_parts_are_bootstrap_profile_default(parts: &[&str]) -> bool {
    matches!(parts, [profile, default]
        if profile.eq_ignore_ascii_case("PROFILE")
            && default.eq_ignore_ascii_case("DEFAULT"))
}

pub(crate) fn normalize_scope(scope: Scope) -> Scope {
    Scope {
        profile: normalize_optional_identifier(scope.profile),
        terminal: normalize_optional_identifier(scope.terminal),
    }
}

#[cfg(test)]
mod tests;