cgx-core 0.0.9

Core library for cgx, the Rust equivalent of uvx or npx for running Rust crates quickly and easily
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
use crate::{Result, cli::CliArgs};
use etcetera::{AppStrategy, AppStrategyArgs, choose_app_strategy};
use serde::{Deserialize, Serialize};
use snafu::ResultExt;
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    time::Duration,
};
use strum::{Display, EnumIter, EnumString, IntoStaticStr, VariantNames};

const DEFAULT_RESOLVE_CACHE_TIMEOUT: Duration = Duration::from_secs(60 * 60);
const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_HTTP_RETRIES: usize = 2;
const DEFAULT_HTTP_BACKOFF_BASE: Duration = Duration::from_millis(500);
const DEFAULT_HTTP_BACKOFF_MAX: Duration = Duration::from_secs(5);

/// The user's preference for using pre-built binaries.
#[derive(
    Default, Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, EnumString, Display, VariantNames,
)]
#[strum(serialize_all = "kebab-case")]
#[serde(rename_all = "kebab-case")]
pub enum UsePrebuiltBinaries {
    /// Use pre-built binaries when possible (subject to the configured allowed binary providers),
    /// fall back to building from source when no suitable binary is found.
    #[default]
    Auto,
    /// Only ever use pre-built binaries.  If a particular crate invocation cannot be satisfied
    /// with a pre-built binary then fail the invocation rather than building from source
    Always,
    /// Never look for or use pre-built binaries, always build from source.
    Never,
}

/// Represents the sources to check for pre-built binaries before building from source.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    EnumString,
    Display,
    IntoStaticStr,
    EnumIter,
    VariantNames,
)]
#[strum(serialize_all = "kebab-case")]
#[serde(rename_all = "kebab-case")]
pub enum BinaryProvider {
    /// Use the crate's declared `[package.metadata.binstall]` metadata (if present) to find
    /// pre-built binaries
    Binstall,
    /// Check GitHub releases on the crate's repository
    GithubReleases,
    /// Check GitLab releases on the crate's repository
    GitlabReleases,
    /// Use the community-driven quickinstall repository
    Quickinstall,
}

/// Configuration for how (and whether) to look for pre-built binaries when running a crate.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct PrebuiltBinariesConfig {
    /// Whether and how to use pre-built binaries.
    pub use_prebuilt_binaries: UsePrebuiltBinaries,

    /// List of sources to check for pre-built binaries before building from source.
    ///
    /// If this list is empty and [`Self::use_prebuilt_binaries`] is not set to `Never`, config
    /// loading will fail with an error. To disable prebuilt binaries, set
    /// [`Self::use_prebuilt_binaries`] to `Never` rather than using an empty provider list.
    pub binary_providers: Vec<BinaryProvider>,

    /// If enabled, when downloading a binary check for a checksum file and if found verify that
    /// the download matches the checksum.
    ///
    /// This adds minimal overhead and is recommended for security, therefore is on by default.
    pub verify_checksums: bool,

    /// If enabled, when dowloading a binary check for a signature file and if found verify that
    /// the download matches the signature.
    ///
    /// This is not quite as simple as [`Self::verify_checksums`] since it requires having the
    /// minisign tooling  available to perform verification.  However it adds stronger security
    /// against malicious binaries.
    pub verify_signatures: bool,
}

impl Default for PrebuiltBinariesConfig {
    fn default() -> Self {
        Self {
            use_prebuilt_binaries: UsePrebuiltBinaries::Auto,
            binary_providers: vec![
                BinaryProvider::Binstall,
                BinaryProvider::GithubReleases,
                BinaryProvider::GitlabReleases,
                BinaryProvider::Quickinstall,
            ],
            verify_checksums: true,
            verify_signatures: true,
        }
    }
}

/// HTTP client settings for registry queries, binary downloads, API calls, and git operations.
///
/// For git operations, proxy, user agent, and connect timeout are applied via gix config
/// overrides (backed by the curl HTTP backend). Retry and backoff settings are applied by
/// cgx's own retry wrapper around git fetches. The timeout setting is intentionally used for
/// both connection timeout and stalled-transfer timeout detection for git-over-HTTP.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct HttpConfig {
    /// Request timeout for HTTP operations.
    ///
    /// For git operations over HTTP/S this value is also used as both:
    /// - connection timeout
    /// - stalled-transfer timeout threshold
    #[serde(with = "humantime_serde")]
    pub timeout: Duration,

    /// Maximum number of retries for transient HTTP failures (429, 5xx, connection errors).
    pub retries: usize,

    /// Base delay for exponential backoff between retries.
    #[serde(with = "humantime_serde")]
    pub backoff_base: Duration,

    /// Maximum delay between retries (caps exponential growth).
    #[serde(with = "humantime_serde")]
    pub backoff_max: Duration,

    /// HTTP or SOCKS5 proxy URL for all HTTP requests.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy: Option<String>,
}

impl Default for HttpConfig {
    fn default() -> Self {
        Self {
            timeout: DEFAULT_HTTP_TIMEOUT,
            retries: DEFAULT_HTTP_RETRIES,
            backoff_base: DEFAULT_HTTP_BACKOFF_BASE,
            backoff_max: DEFAULT_HTTP_BACKOFF_MAX,
            proxy: None,
        }
    }
}

/// Raw HTTP config from config file, with optional fields for detecting whether values were set.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct HttpConfigFile {
    #[serde(default, with = "humantime_serde::option")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout: Option<Duration>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub retries: Option<usize>,

    #[serde(default, with = "humantime_serde::option")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backoff_base: Option<Duration>,

    #[serde(default, with = "humantime_serde::option")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backoff_max: Option<Duration>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy: Option<String>,
}

/// Configuration for a specific tool, matching Cargo.toml dependency format.
///
/// This can be a simple version string like `"1.0"` or a more complex specification
/// with version, features, registry, git repo, etc.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields, untagged)]
pub enum ToolConfig {
    /// Simple version specification (e.g., "1.0", "*")
    Version(String),
    /// Detailed configuration with version, features, registry, etc.
    Detailed {
        #[serde(skip_serializing_if = "Option::is_none")]
        version: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        features: Option<Vec<String>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        registry: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        git: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        branch: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        tag: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        rev: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        path: Option<PathBuf>,
    },
}

/// Intermediate structure for deserializing config files from TOML.
///
/// This matches the structure of cgx.toml files and is used during the deserialization
/// process. Fields are then mapped to the final [`Config`] struct.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ConfigFile {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(deserialize_with = "deserialize_optional_expanded_path")]
    pub bin_dir: Option<PathBuf>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(deserialize_with = "deserialize_optional_expanded_path")]
    pub build_dir: Option<PathBuf>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(deserialize_with = "deserialize_optional_expanded_path")]
    pub cache_dir: Option<PathBuf>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub locked: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub log_level: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub offline: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "humantime_serde")]
    pub resolve_cache_timeout: Option<Duration>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub toolchain: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_registry: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub prebuilt_binaries: Option<PrebuiltBinariesConfig>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http: Option<HttpConfigFile>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<HashMap<String, ToolConfig>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub aliases: Option<HashMap<String, String>>,
}

impl ConfigFile {
    /// Returns the base configuration with sensible defaults.
    ///
    /// This is distinct from [`Default`] which returns all `None` values. The `Default` impl
    /// is used by serde to represent fields missing from a config file, so it must be all `None`.
    ///
    /// This method provides the actual default values that serve as the lowest-precedence layer
    /// in the config hierarchy, before any config files are applied.
    pub fn base_config() -> Self {
        Self {
            bin_dir: None,
            build_dir: None,
            cache_dir: None,
            locked: Some(true),
            log_level: None,
            offline: Some(false),
            resolve_cache_timeout: Some(DEFAULT_RESOLVE_CACHE_TIMEOUT),
            toolchain: None,
            default_registry: None,
            prebuilt_binaries: Some(PrebuiltBinariesConfig::default()),
            http: None,
            tools: None,
            aliases: None,
        }
    }
}

/// Custom deserializer for optional [`PathBuf`] that expands ~ to home directory.
fn deserialize_optional_expanded_path<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<PathBuf>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let opt_string: Option<String> = Option::deserialize(deserializer)?;
    match opt_string {
        None => Ok(None),
        Some(s) => {
            let expanded = shellexpand::tilde(&s);
            Ok(Some(PathBuf::from(expanded.as_ref())))
        }
    }
}

/// Configuration settings for cgx.
///
/// Configuration is loaded from multiple sources in order of precedence (later sources override
/// earlier ones):
/// 1. Hard-coded defaults
/// 2. System-wide config file (`/etc/cgx.toml` on Linux/macOS)
/// 3. User config file (`$XDG_CONFIG_HOME/cgx/cgx.toml` or platform equivalent)
/// 4. Directory hierarchy from filesystem root to current directory (each `cgx.toml` found)
/// 5. Command-line arguments (highest priority)
#[derive(Debug, Clone)]
pub struct Config {
    /// Directory where config files are stored
    #[allow(dead_code)]
    pub config_dir: PathBuf,

    /// The cache directory where various levels of cache are located
    pub cache_dir: PathBuf,

    /// Directory where compiled binaries that can be re-used are stored
    pub bin_dir: PathBuf,

    /// Directory for ephemeral build artifacts.
    ///
    /// Temporary directories for source extraction and compilation are created here.
    /// Only the final compiled binary is retained; all other build artifacts are cleaned up.
    pub build_dir: PathBuf,

    /// How long to keep resolved crate information in the cache before re-resolving
    pub resolve_cache_timeout: Duration,

    pub offline: bool,

    pub locked: bool,

    pub refresh: bool,

    /// Rust toolchain to use for building (e.g., "nightly", "1.70.0", "stable")
    pub toolchain: Option<String>,

    /// Logging verbosity level (e.g., "info", "debug", "trace")
    pub log_level: Option<String>,

    /// Default registry to use instead of crates.io when no registry is explicitly specified
    pub default_registry: Option<String>,

    /// How or whether to look for pre-built binaries published for the crates being run.
    pub prebuilt_binaries: PrebuiltBinariesConfig,

    /// HTTP client configuration for registry queries, binary downloads, and API calls.
    pub http: HttpConfig,

    /// Pinned tool versions and configurations.
    ///
    /// Tools listed here will use the specified version/source instead of being resolved
    /// dynamically. This allows pinning critical tools to specific versions.
    pub tools: HashMap<String, ToolConfig>,

    /// Tool name aliases.
    ///
    /// Maps convenient names to actual crate names. For example, `rg` -> `ripgrep`.
    /// Note that aliases shadow actual crate names, so aliased crates become inaccessible.
    pub aliases: HashMap<String, String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            config_dir: PathBuf::default(),
            cache_dir: PathBuf::default(),
            bin_dir: PathBuf::default(),
            build_dir: PathBuf::default(),
            resolve_cache_timeout: Duration::from_secs(3600),
            offline: false,
            locked: true,
            refresh: false,
            toolchain: None,
            log_level: None,
            default_registry: None,
            prebuilt_binaries: PrebuiltBinariesConfig::default(),
            http: HttpConfig::default(),
            tools: HashMap::default(),
            aliases: HashMap::default(),
        }
    }
}

impl Config {
    /// Load the configuration, honoring config files and command line arguments.
    ///
    /// Configuration is loaded from multiple sources with the following precedence
    /// (later sources override earlier ones):
    /// 1. Hard-coded defaults
    /// 2. System-wide config file
    /// 3. User config file
    /// 4. Directory hierarchy config files (from root to current directory)
    /// 5. Command-line arguments (highest priority)
    pub fn load(args: &CliArgs) -> Result<Self> {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

        Self::load_from_dir(&cwd, args)
    }

    /// Load config from the CLI args and a specified directory which may or may not contain config
    /// files.
    pub fn load_from_dir(cwd: &Path, args: &CliArgs) -> Result<Self> {
        use figment::{
            Figment,
            providers::{Format, Serialized, Toml},
        };

        let strategy = Self::get_user_dirs()?;

        // Start with base config defaults, then merge config files
        let mut figment = Figment::new().merge(Serialized::defaults(ConfigFile::base_config()));

        for config_file in Self::discover_config_files(cwd, args)? {
            figment = figment.merge(Toml::file(config_file));
        }

        // Extract merged config file values (no CLI overrides applied yet via Figment)
        let config_file: ConfigFile = figment.extract().context(crate::error::ConfigExtractSnafu)?;

        // Override the config file values using any CLI args that were specified

        // locked: --unlocked > --locked/--frozen > config > default(true)
        let locked = if args.unlocked {
            false
        } else if args.locked || args.frozen {
            true
        } else {
            config_file.locked.unwrap_or(true)
        };

        // offline: --offline/--frozen > config > default(false)
        let offline = if args.offline || args.frozen {
            true
        } else {
            config_file.offline.unwrap_or(false)
        };

        // toolchain: CLI > config
        let toolchain = args.toolchain.clone().or(config_file.toolchain);

        // Determine config_dir based on override precedence
        let config_dir = if let Some(user_config_dir) = &args.user_config_dir {
            user_config_dir.clone()
        } else if let Some(app_dir) = &args.app_dir {
            app_dir.join("config")
        } else {
            strategy.config_dir()
        };

        // Determine cache_dir: CLI (app-dir) > config file > strategy
        let cache_dir = if let Some(app_dir) = &args.app_dir {
            app_dir.join("cache")
        } else {
            config_file.cache_dir.unwrap_or_else(|| strategy.cache_dir())
        };

        // Determine bin_dir: CLI (app-dir) > config file > strategy
        let bin_dir = if let Some(app_dir) = &args.app_dir {
            app_dir.join("bins")
        } else {
            config_file
                .bin_dir
                .unwrap_or_else(|| strategy.in_data_dir("bins"))
        };

        // Determine build_dir: CLI (app-dir) > config file > strategy
        let build_dir = if let Some(app_dir) = &args.app_dir {
            app_dir.join("build")
        } else {
            config_file
                .build_dir
                .unwrap_or_else(|| strategy.in_data_dir("build"))
        };

        let mut prebuilt_binaries = config_file.prebuilt_binaries.unwrap_or_default();

        // Apply CLI overrides for prebuilt binaries
        if let Some(mode) = args.prebuilt_binary {
            prebuilt_binaries.use_prebuilt_binaries = mode;
        }
        if let Some(ref providers) = args.prebuilt_binary_sources {
            prebuilt_binaries.binary_providers = providers.clone();
        }
        if args.prebuilt_binary_no_verify_checksums {
            prebuilt_binaries.verify_checksums = false;
        }
        if args.prebuilt_binary_no_verify_signatures {
            prebuilt_binaries.verify_signatures = false;
        }

        // Validate prebuilt binaries configuration
        if prebuilt_binaries.binary_providers.is_empty()
            && prebuilt_binaries.use_prebuilt_binaries != UsePrebuiltBinaries::Never
        {
            return crate::error::NoProvidersConfiguredSnafu.fail();
        }

        // Build HTTP config with precedence: CLI > config file > Cargo env vars > defaults
        let http_config_file = config_file.http.unwrap_or_default();
        let http = Self::build_http_config(&http_config_file, args)?;

        Ok(Self {
            config_dir,
            cache_dir,
            bin_dir,
            build_dir,
            resolve_cache_timeout: config_file
                .resolve_cache_timeout
                .unwrap_or(DEFAULT_RESOLVE_CACHE_TIMEOUT),
            offline,
            locked,
            refresh: args.refresh,
            toolchain,
            log_level: config_file.log_level,
            default_registry: config_file.default_registry,
            prebuilt_binaries,
            http,
            tools: config_file.tools.unwrap_or_default(),
            aliases: config_file.aliases.unwrap_or_default(),
        })
    }

    /// Discover all config file locations in order of precedence.
    ///
    /// Returns paths from lowest to highest precedence. Later config files override earlier ones.
    ///
    /// The search order is:
    /// 1. System config: `/etc/cgx.toml` on Unix, Windows equivalent (or override location)
    /// 2. User config: `$XDG_CONFIG_HOME/cgx/cgx.toml` or platform equivalent (or override
    ///    location)
    /// 3. Directory hierarchy: All `cgx.toml` files from filesystem root to current directory
    fn discover_config_files(cwd: &Path, args: &CliArgs) -> Result<Vec<PathBuf>> {
        let mut config_files = Vec::new();

        // If the user explicitly specified a config file, read ONLY that file
        if let Some(config_path) = &args.config_file {
            return Ok(vec![config_path.clone()]);
        }

        // System config (can be overridden)
        if let Some(system_config_dir) = &args.system_config_dir {
            let system_config = system_config_dir.join("cgx.toml");
            if system_config.exists() {
                config_files.push(system_config);
            }
        } else {
            #[cfg(unix)]
            {
                let system_config = PathBuf::from("/etc/cgx.toml");
                if system_config.exists() {
                    config_files.push(system_config);
                }
            }

            #[cfg(windows)]
            {
                if let Some(program_data) = std::env::var_os("ProgramData") {
                    let system_config = PathBuf::from(program_data).join("cgx").join("cgx.toml");
                    if system_config.exists() {
                        config_files.push(system_config);
                    }
                }
            }
        }

        // User config (can be overridden via user-config-dir or app-dir)
        let user_config = if let Some(user_config_dir) = &args.user_config_dir {
            // Most specific: explicit user config directory
            user_config_dir.join("cgx.toml")
        } else if let Some(app_dir) = &args.app_dir {
            // App dir provides a base for config
            app_dir.join("config").join("cgx.toml")
        } else {
            // Default: use platform-specific config directory
            let strategy = Self::get_user_dirs()?;
            strategy.config_dir().join("cgx.toml")
        };

        if user_config.exists() {
            config_files.push(user_config);
        }

        let mut ancestors: Vec<PathBuf> = cwd.ancestors().map(|p| p.to_path_buf()).collect();
        ancestors.reverse();

        for ancestor in ancestors {
            let config_file = ancestor.join("cgx.toml");
            if config_file.exists() {
                config_files.push(config_file);
            }
        }

        Ok(config_files)
    }

    fn get_user_dirs() -> Result<impl AppStrategy> {
        choose_app_strategy(AppStrategyArgs {
            top_level_domain: "org".to_string(),
            author: "anelson".to_string(),
            app_name: "cgx".to_string(),
        })
        .context(crate::error::EtceteraSnafu)
    }

    /// Build [`HttpConfig`] with proper precedence:
    /// 1. CLI args (highest priority)
    /// 2. Config file values
    /// 3. Cargo environment variable fallbacks
    /// 4. Defaults (lowest priority)
    fn build_http_config(config_file: &HttpConfigFile, args: &CliArgs) -> Result<HttpConfig> {
        // Determine if CLI args were provided (they override everything)
        let cli_timeout = args.http_timeout.as_ref();
        let cli_retries = args.http_retries;
        let cli_proxy = args.http_proxy.as_ref();

        // timeout: CLI > config > CARGO_HTTP_TIMEOUT > default
        let timeout = if let Some(timeout_str) = cli_timeout {
            humantime::parse_duration(timeout_str).context(crate::error::InvalidHttpTimeoutSnafu {
                value: timeout_str.clone(),
            })?
        } else if let Some(config_timeout) = config_file.timeout {
            config_timeout
        } else if let Ok(cargo_timeout) = std::env::var("CARGO_HTTP_TIMEOUT") {
            if let Ok(secs) = cargo_timeout.parse::<u64>() {
                Duration::from_secs(secs)
            } else {
                tracing::warn!(
                    "Invalid CARGO_HTTP_TIMEOUT value '{}', falling back to default {:?}.",
                    cargo_timeout,
                    DEFAULT_HTTP_TIMEOUT
                );
                DEFAULT_HTTP_TIMEOUT
            }
        } else {
            DEFAULT_HTTP_TIMEOUT
        };

        // retries: CLI > config > CARGO_NET_RETRY > default
        let retries = if let Some(cli_retries) = cli_retries {
            cli_retries
        } else if let Some(config_retries) = config_file.retries {
            config_retries
        } else if let Ok(cargo_retry) = std::env::var("CARGO_NET_RETRY") {
            if let Ok(retries) = cargo_retry.parse::<usize>() {
                retries
            } else {
                tracing::warn!(
                    "Invalid CARGO_NET_RETRY value '{}', falling back to default {}.",
                    cargo_retry,
                    DEFAULT_HTTP_RETRIES
                );
                DEFAULT_HTTP_RETRIES
            }
        } else {
            DEFAULT_HTTP_RETRIES
        };

        // proxy: CLI > config > CARGO_HTTP_PROXY > None (let reqwest handle system proxies)
        let proxy = if let Some(p) = cli_proxy {
            Some(p.clone())
        } else if config_file.proxy.is_some() {
            config_file.proxy.clone()
        } else if let Ok(cargo_proxy) = std::env::var("CARGO_HTTP_PROXY") {
            Some(cargo_proxy)
        } else {
            None
        };

        // backoff settings: config > defaults (no CLI or Cargo env fallback)
        let backoff_base = config_file.backoff_base.unwrap_or(DEFAULT_HTTP_BACKOFF_BASE);
        let backoff_max = config_file.backoff_max.unwrap_or(DEFAULT_HTTP_BACKOFF_MAX);

        Ok(HttpConfig {
            timeout,
            retries,
            backoff_base,
            backoff_max,
            proxy,
        })
    }
}

/// Create a fake, isolated config environment for testing, with all of the path config
/// settings pointing to a [`tempfile::TempDir`] directory.
#[cfg(test)]
pub(crate) fn create_test_env() -> (tempfile::TempDir, Config) {
    let temp_dir = tempfile::tempdir().unwrap();
    let config = Config {
        config_dir: temp_dir.path().join("config"),
        cache_dir: temp_dir.path().join("cache"),
        bin_dir: temp_dir.path().join("bins"),
        build_dir: temp_dir.path().join("build"),
        resolve_cache_timeout: Duration::from_secs(3600),
        locked: true,
        ..Default::default()
    };

    (temp_dir, config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    /// Apply test-local config directory overrides so config loading cannot read
    /// host-level `/etc/cgx.toml` or user-level cgx config on the machine running tests.
    ///
    /// This keeps tests deterministic on developer systems that actively use cgx.
    fn with_isolated_global_config(mut args: CliArgs, root: &Path) -> CliArgs {
        args.system_config_dir = Some(root.join("system"));
        args.user_config_dir = Some(root.join("user"));
        args
    }

    #[test]
    fn test_deserialize_basic_config() {
        let toml_content = r#"
            bin_dir = "/usr/local/bin"
            cache_dir = "/tmp/cache"
            offline = true
            locked = false
        "#;

        let config: ConfigFile = toml::from_str(toml_content).unwrap();
        assert_eq!(config.bin_dir, Some(PathBuf::from("/usr/local/bin")));
        assert_eq!(config.cache_dir, Some(PathBuf::from("/tmp/cache")));
        assert_eq!(config.offline, Some(true));
        assert_eq!(config.locked, Some(false));
    }

    #[test]
    fn test_deserialize_duration() {
        let toml_content = r#"
            resolve_cache_timeout = "2h"
        "#;

        let config: ConfigFile = toml::from_str(toml_content).unwrap();
        assert_eq!(
            config.resolve_cache_timeout,
            Some(Duration::from_secs(2 * 60 * 60))
        );
    }

    #[test]
    fn test_deserialize_tilde_expansion() {
        let toml_content = r#"
            bin_dir = "~/.local/bin"
        "#;

        let config: ConfigFile = toml::from_str(toml_content).unwrap();
        let home = std::env::var("HOME")
            .or_else(|_| std::env::var("USERPROFILE"))
            .unwrap();
        let expected = PathBuf::from(home).join(".local/bin");
        assert_eq!(config.bin_dir, Some(expected));
    }

    #[test]
    fn test_deserialize_binary_providers() {
        let toml_content = r#"
            [prebuilt_binaries]
            binary_providers = ["github-releases", "quickinstall"]
        "#;

        let config: ConfigFile = toml::from_str(toml_content).unwrap();
        assert_eq!(
            config.prebuilt_binaries.unwrap().binary_providers,
            vec![BinaryProvider::GithubReleases, BinaryProvider::Quickinstall,]
        );
    }

    #[test]
    fn test_deserialize_tools_simple() {
        let toml_content = r#"
            [tools]
            ripgrep = "14.0"
        "#;

        let config: ConfigFile = toml::from_str(toml_content).unwrap();
        let tools = config.tools.unwrap();
        assert_eq!(
            tools.get("ripgrep"),
            Some(&ToolConfig::Version("14.0".to_string()))
        );
    }

    #[test]
    fn test_deserialize_tools_detailed() {
        let toml_content = r#"
            [tools]
            taplo-cli = { version = "1.11.0", features = ["schema"] }
        "#;

        let config: ConfigFile = toml::from_str(toml_content).unwrap();
        let tools = config.tools.unwrap();

        match tools.get("taplo-cli") {
            Some(ToolConfig::Detailed {
                version, features, ..
            }) => {
                assert_eq!(*version, Some("1.11.0".to_string()));
                assert_eq!(*features, Some(vec!["schema".to_string()]));
            }
            _ => panic!("Expected Detailed tool config"),
        }
    }

    #[test]
    fn test_deserialize_aliases() {
        let toml_content = r#"
            [aliases]
            rg = "ripgrep"
            taplo = "taplo-cli"
        "#;

        let config: ConfigFile = toml::from_str(toml_content).unwrap();
        let aliases = config.aliases.unwrap();
        assert_eq!(aliases.get("rg"), Some(&"ripgrep".to_string()));
        assert_eq!(aliases.get("taplo"), Some(&"taplo-cli".to_string()));
    }

    #[test]
    fn test_config_defaults() {
        let args = CliArgs::parse_from_test_args(["test-crate"]);
        let config = Config::load(&args).unwrap();

        assert!(!config.offline);
        assert!(config.locked); // Default is true per issue #55
        assert_eq!(config.toolchain, None);
        assert_eq!(config.resolve_cache_timeout, Duration::from_secs(60 * 60));
    }

    #[test]
    fn test_cli_overrides() {
        let args = CliArgs::parse_from_test_args(["+nightly", "--offline", "--locked", "test-crate"]);
        let config = Config::load(&args).unwrap();

        assert!(config.offline);
        assert!(config.locked);
        assert_eq!(config.toolchain, Some("nightly".to_string()));
    }

    #[test]
    fn test_frozen_implies_locked_and_offline() {
        let args = CliArgs::parse_from_test_args(["--frozen", "test-crate"]);
        let config = Config::load(&args).unwrap();

        assert!(config.offline);
        assert!(config.locked);
    }

    #[test]
    fn test_full_config_example() {
        let toml_content = r#"
            bin_dir = "~/.local/bin"
            build_dir = "~/.local/build"
            cache_dir = "~/.cache/cgx"
            locked = true
            log_level = "info"
            offline = false
            resolve_cache_timeout = "1h"
            toolchain = "stable"
            default_registry = "my-registry"

            [prebuilt_binaries]
            binary_providers = ["github-releases", "gitlab-releases", "quickinstall"]

            [tools]
            ripgrep = "*"
            taplo-cli = { version = "1.11.0", features = ["schema"] }

            [aliases]
            rg = "ripgrep"
            taplo = "taplo-cli"
        "#;

        let config: ConfigFile = toml::from_str(toml_content).unwrap();

        assert_eq!(config.log_level, Some("info".to_string()));
        assert_eq!(config.toolchain, Some("stable".to_string()));
        assert_eq!(config.default_registry, Some("my-registry".to_string()));
        assert_eq!(config.locked, Some(true));
        assert_eq!(config.offline, Some(false));
        assert_eq!(config.resolve_cache_timeout, Some(Duration::from_secs(60 * 60)));

        let prebuilt_binaries = config.prebuilt_binaries.unwrap();

        assert_eq!(prebuilt_binaries.binary_providers.len(), 3);

        // Other prebuild binary settings should be defaults
        assert_eq!(prebuilt_binaries.use_prebuilt_binaries, UsePrebuiltBinaries::Auto);
        assert!(prebuilt_binaries.verify_checksums);
        assert!(prebuilt_binaries.verify_signatures);

        let tools = config.tools.unwrap();
        assert_eq!(tools.len(), 2);

        let aliases = config.aliases.unwrap();
        assert_eq!(aliases.len(), 2);
    }

    mod prebuilt_validation_tests {
        use super::*;
        use assert_matches::assert_matches;
        use std::io::Write;

        fn create_temp_config(toml_content: &str) -> tempfile::TempDir {
            let temp_dir = tempfile::tempdir().unwrap();
            let config_path = temp_dir.path().join("cgx.toml");
            let mut file = std::fs::File::create(&config_path).unwrap();
            file.write_all(toml_content.as_bytes()).unwrap();
            temp_dir
        }

        #[test]
        fn test_empty_providers_with_auto_fails() {
            let toml_content = r#"
                [prebuilt_binaries]
                use_prebuilt_binaries = "auto"
                binary_providers = []
            "#;

            let temp_dir = create_temp_config(toml_content);
            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let result = Config::load_from_dir(temp_dir.path(), &args);
            assert_matches!(result, Err(crate::error::Error::NoProvidersConfigured));
        }

        #[test]
        fn test_empty_providers_with_always_fails() {
            let toml_content = r#"
                [prebuilt_binaries]
                use_prebuilt_binaries = "always"
                binary_providers = []
            "#;

            let temp_dir = create_temp_config(toml_content);
            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let result = Config::load_from_dir(temp_dir.path(), &args);
            assert_matches!(result, Err(crate::error::Error::NoProvidersConfigured));
        }

        #[test]
        fn test_empty_providers_with_never_ok() {
            let toml_content = r#"
                [prebuilt_binaries]
                use_prebuilt_binaries = "never"
                binary_providers = []
            "#;

            let temp_dir = create_temp_config(toml_content);
            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let result = Config::load_from_dir(temp_dir.path(), &args);
            assert!(result.is_ok(), "Empty providers with 'never' mode should succeed");
        }
    }

    /// Test the config loading logic that traverses up a directory hierarchy looking for config
    /// files.
    ///
    /// `testdata/configs` contains test config files constructed specificially to facilitate these
    /// tests
    mod hierarchy_tests {
        use super::*;
        use assert_matches::assert_matches;

        /// Test loading config from a 3-level hierarchy (root → work → project1).
        ///
        /// Verifies that config files are merged in order of precedence, with closer files
        /// overriding values from parent directories. The `resolve_cache_timeout` should be 3m
        /// (from project1), tools should include entries from all 3 levels (5 total), and aliases
        /// should show the `dummytool` override from project1.
        #[test]
        fn test_config_hierarchy_project1() {
            let test_case = crate::testdata::ConfigTestCase::hierarchy_project1();

            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let config = Config::load_from_dir(test_case.path(), &args).unwrap();

            assert_eq!(config.resolve_cache_timeout, Duration::from_secs(3 * 60));

            assert!(config.tools.contains_key("ripgrep"));
            assert!(config.tools.contains_key("root_tool"));
            assert!(config.tools.contains_key("taplo-cli"));
            assert!(config.tools.contains_key("work_tool"));
            assert!(config.tools.contains_key("project1_tool"));
            assert_eq!(config.tools.len(), 5);

            assert_eq!(config.aliases.get("dummytool"), Some(&"project1".to_string()));
            assert_eq!(config.aliases.get("rg"), Some(&"ripgrep".to_string()));
            assert_eq!(config.aliases.get("taplo"), Some(&"taplo-cli".to_string()));
            assert_eq!(config.aliases.len(), 3);
        }

        /// Test loading config from a parallel 3-level hierarchy (root → work → project2).
        ///
        /// Similar to project1, but verifies that sibling project directories maintain
        /// independent configurations. The `resolve_cache_timeout` should be 5m (from project2),
        /// tools should include `project2_tool` instead of `project1_tool` (5 total), and the
        /// `dummytool` alias should override to "project2".
        #[test]
        fn test_config_hierarchy_project2() {
            let test_case = crate::testdata::ConfigTestCase::hierarchy_project2();

            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let config = Config::load_from_dir(test_case.path(), &args).unwrap();

            assert_eq!(config.resolve_cache_timeout, Duration::from_secs(5 * 60));

            assert!(config.tools.contains_key("ripgrep"));
            assert!(config.tools.contains_key("root_tool"));
            assert!(config.tools.contains_key("taplo-cli"));
            assert!(config.tools.contains_key("work_tool"));
            assert!(config.tools.contains_key("project2_tool"));
            assert_eq!(config.tools.len(), 5);

            assert_eq!(config.aliases.get("dummytool"), Some(&"project2".to_string()));
            assert_eq!(config.aliases.get("rg"), Some(&"ripgrep".to_string()));
            assert_eq!(config.aliases.get("taplo"), Some(&"taplo-cli".to_string()));
            assert_eq!(config.aliases.len(), 3);
        }

        /// Test loading config from a 2-level hierarchy (root → work).
        ///
        /// Verifies config merging at an intermediate level in the hierarchy. The
        /// `resolve_cache_timeout` should be 2m (from work), tools should include entries from
        /// both root and work (4 total), and the `dummytool` alias should override to "work".
        #[test]
        fn test_config_hierarchy_work() {
            let test_case = crate::testdata::ConfigTestCase::hierarchy_work();

            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let config = Config::load_from_dir(test_case.path(), &args).unwrap();

            assert_eq!(config.resolve_cache_timeout, Duration::from_secs(2 * 60));

            assert!(config.tools.contains_key("ripgrep"));
            assert!(config.tools.contains_key("root_tool"));
            assert!(config.tools.contains_key("taplo-cli"));
            assert!(config.tools.contains_key("work_tool"));
            assert_eq!(config.tools.len(), 4);

            assert_eq!(config.aliases.get("dummytool"), Some(&"work".to_string()));
            assert_eq!(config.aliases.get("rg"), Some(&"ripgrep".to_string()));
            assert_eq!(config.aliases.get("taplo"), Some(&"taplo-cli".to_string()));
            assert_eq!(config.aliases.len(), 3);
        }

        /// Test loading config from the root level only.
        ///
        /// Establishes the baseline configuration from the root config file. The
        /// `resolve_cache_timeout` should be 1m (from root), and only root-level tools and aliases
        /// should be present (3 tools, 3 aliases including dummytool="root").
        #[test]
        fn test_config_hierarchy_root() {
            let test_case = crate::testdata::ConfigTestCase::hierarchy_root();

            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let config = Config::load_from_dir(test_case.path(), &args).unwrap();

            assert_eq!(config.resolve_cache_timeout, Duration::from_secs(60));

            assert!(config.tools.contains_key("ripgrep"));
            assert!(config.tools.contains_key("root_tool"));
            assert!(config.tools.contains_key("taplo-cli"));
            assert_eq!(config.tools.len(), 3);

            assert_eq!(config.aliases.get("dummytool"), Some(&"root".to_string()));
            assert_eq!(config.aliases.get("rg"), Some(&"ripgrep".to_string()));
            assert_eq!(config.aliases.get("taplo"), Some(&"taplo-cli".to_string()));
            assert_eq!(config.aliases.len(), 3);
        }

        /// Test that specifying `--config-file` bypasses hierarchy traversal.
        ///
        /// When an explicit config file is provided via CLI, ONLY that file is read without
        /// walking up the directory tree. This test uses a non-standard filename to verify
        /// it's the explicit path (not discovery) that loads the config. Should have only 1 tool
        /// and 1 alias from the specified file, with timeout=6m.
        #[test]
        fn test_explicit_config_file() {
            let test_case = crate::testdata::ConfigTestCase::explicit_non_standard_name();

            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.config_file = Some(test_case.path().to_path_buf());

            let config = Config::load(&args).unwrap();

            assert_eq!(config.resolve_cache_timeout, Duration::from_secs(6 * 60));

            assert!(config.tools.contains_key("project1_tool"));
            assert_eq!(config.tools.len(), 1);

            assert_eq!(
                config.aliases.get("dummytool"),
                Some(&"not_called_cgx_project1".to_string())
            );
            assert_eq!(config.aliases.len(), 1);
        }

        /// Test that detailed tool configurations are preserved during hierarchy merging.
        ///
        /// Verifies that tools specified with detailed configs (version, features, etc.) maintain
        /// their structure when merged across the hierarchy. The taplo-cli tool from root should
        /// retain its version="1.11.0" and features=["schema"] specification.
        #[test]
        fn test_tools_detailed_config_preserved() {
            let test_case = crate::testdata::ConfigTestCase::hierarchy_root();

            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let config = Config::load_from_dir(test_case.path(), &args).unwrap();

            let taplo_tool = config.tools.get("taplo-cli").unwrap();
            assert_matches!(
                taplo_tool,
                ToolConfig::Detailed {
                    version: Some(v),
                    features: Some(f),
                    ..
                } if v == "1.11.0" && f == &vec!["schema".to_string()]
            );
        }

        /// Test that CLI arguments have the highest precedence over config files.
        ///
        /// Command-line flags should override any values set in config files, regardless of
        /// where those config files appear in the hierarchy. This verifies that --offline,
        /// --locked, and +toolchain flags take precedence over the merged config.
        #[test]
        fn test_cli_args_override_config_files() {
            let test_case = crate::testdata::ConfigTestCase::hierarchy_project1();

            let args = CliArgs::parse_from_test_args(["+stable", "--offline", "--locked", "test-crate"]);
            let config = Config::load_from_dir(test_case.path(), &args).unwrap();

            assert!(config.offline);
            assert!(config.locked);
            assert_eq!(config.toolchain, Some("stable".to_string()));
        }

        /// Test that --config-file reads only the specified file.
        ///
        /// When --config-file is specified, only that single config file should be loaded,
        /// bypassing all config discovery (system, user, and hierarchy configs).
        #[test]
        fn test_config_file_reads_only_specified_file() {
            // The hierarchy has configs with resolve_cache_timeout set to various values:
            // root=1m, work=2m, project1=3m
            let hierarchy_dir = crate::testdata::ConfigTestCase::hierarchy_project1();

            // The explicit config has a different timeout (6m)
            let explicit_config = crate::testdata::ConfigTestCase::explicit_non_standard_name();

            // Load config from project1 directory but with --config-file pointing to explicit config
            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.config_file = Some(explicit_config.path().to_path_buf());

            let config = Config::load_from_dir(hierarchy_dir.path(), &args).unwrap();

            // Should have the explicit config's timeout (6m), not any from the hierarchy (1m/2m/3m)
            assert_eq!(config.resolve_cache_timeout, Duration::from_secs(6 * 60));

            // Should have only the tool from explicit config, not from hierarchy
            assert!(config.tools.contains_key("project1_tool"));
            assert_eq!(config.tools.len(), 1);

            // Should have only the alias from explicit config
            assert_eq!(
                config.aliases.get("dummytool"),
                Some(&"not_called_cgx_project1".to_string())
            );
            assert_eq!(config.aliases.len(), 1);
        }
    }

    mod config_file_discovery_tests {
        use super::*;

        /// Test that [`discover_config_files`] returns only the explicit file when --config-file is
        /// set.
        ///
        /// This directly tests the discovery logic to ensure hierarchy configs are not included.
        #[test]
        fn test_discover_only_explicit_file() {
            use std::fs;

            // RAII guard to ensure user config cleanup happens even if test panics
            struct UserConfigGuard {
                path: PathBuf,
                should_delete: bool,
            }

            impl Drop for UserConfigGuard {
                fn drop(&mut self) {
                    if self.should_delete {
                        fs::remove_file(&self.path).ok();
                    }
                }
            }

            let temp_dir = tempfile::tempdir().unwrap();
            let cwd = temp_dir.path();

            // Create a hierarchy of config files
            let root_config = cwd.join("cgx.toml");
            fs::write(&root_config, "resolve_cache_timeout = \"1m\"").unwrap();

            let sub_dir = cwd.join("subdir");
            fs::create_dir(&sub_dir).unwrap();
            let sub_config = sub_dir.join("cgx.toml");
            fs::write(&sub_config, "resolve_cache_timeout = \"2m\"").unwrap();

            // Create an explicit config elsewhere
            let explicit_config = temp_dir.path().join("explicit.toml");
            fs::write(&explicit_config, "resolve_cache_timeout = \"3m\"").unwrap();

            // Create a user config to trigger the bug (if it doesn't already exist)
            let strategy = Config::get_user_dirs().unwrap();
            let user_config_dir = strategy.config_dir();
            fs::create_dir_all(&user_config_dir).ok();
            let user_config_path = user_config_dir.join("cgx.toml");
            let user_config_existed = user_config_path.exists();

            // Guard ensures cleanup even if test panics
            let _guard = if !user_config_existed {
                fs::write(&user_config_path, "resolve_cache_timeout = \"99m\"").unwrap();
                UserConfigGuard {
                    path: user_config_path,
                    should_delete: true,
                }
            } else {
                UserConfigGuard {
                    path: user_config_path,
                    should_delete: false,
                }
            };

            // Test with --config-file
            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.config_file = Some(explicit_config.clone());

            let discovered = Config::discover_config_files(&sub_dir, &args).unwrap();

            // Should contain ONLY the explicit config file (no system, user, or hierarchy configs)
            // This will FAIL if the bug exists, showing [user_config, explicit_config]
            assert_eq!(
                discovered.len(),
                1,
                "Expected only 1 config file, got {}: {:?}",
                discovered.len(),
                discovered
            );
            assert_eq!(discovered[0], explicit_config);
        }

        /// Test that hierarchy configs are discovered when --config-file is not set.
        #[test]
        fn test_discover_hierarchy_without_explicit() {
            use std::fs;

            let temp_dir = tempfile::tempdir().unwrap();
            let cwd = temp_dir.path();

            // Create a hierarchy of config files
            let root_config = cwd.join("cgx.toml");
            fs::write(&root_config, "resolve_cache_timeout = \"1m\"").unwrap();

            let sub_dir = cwd.join("subdir");
            fs::create_dir(&sub_dir).unwrap();
            let sub_config = sub_dir.join("cgx.toml");
            fs::write(&sub_config, "resolve_cache_timeout = \"2m\"").unwrap();

            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let discovered = Config::discover_config_files(&sub_dir, &args).unwrap();

            // Should contain both hierarchy configs (and possibly system/user if they exist)
            // We check that at least our two configs are present
            assert!(
                discovered.contains(&root_config),
                "Root config should be discovered"
            );
            assert!(
                discovered.contains(&sub_config),
                "Sub config should be discovered"
            );
        }
    }

    mod override_tests {
        use super::*;
        use std::fs;

        mod system_config_dir_tests {
            use super::*;

            #[test]
            fn test_system_config_dir_cli_arg() {
                let temp_dir = tempfile::tempdir().unwrap();
                let system_config_dir = temp_dir.path().join("system");
                fs::create_dir_all(&system_config_dir).unwrap();
                let system_config = system_config_dir.join("cgx.toml");
                fs::write(&system_config, "resolve_cache_timeout = \"5m\"").unwrap();

                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                // Also set user_config_dir to ensure isolation (no real user config is loaded)
                let user_config_dir = temp_dir.path().join("user");
                fs::create_dir_all(&user_config_dir).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.system_config_dir = Some(system_config_dir);
                args.user_config_dir = Some(user_config_dir);

                let config = Config::load_from_dir(&cwd, &args).unwrap();
                assert_eq!(config.resolve_cache_timeout, Duration::from_secs(5 * 60));
            }

            #[test]
            fn test_system_config_dir_vs_user_config() {
                let temp_dir = tempfile::tempdir().unwrap();

                // Create system config with 10m timeout
                let system_config_dir = temp_dir.path().join("system");
                fs::create_dir_all(&system_config_dir).unwrap();
                fs::write(
                    system_config_dir.join("cgx.toml"),
                    "resolve_cache_timeout = \"10m\"",
                )
                .unwrap();

                // Create user config with 20m timeout
                let user_config_dir = temp_dir.path().join("user");
                fs::create_dir_all(&user_config_dir).unwrap();
                fs::write(
                    user_config_dir.join("cgx.toml"),
                    "resolve_cache_timeout = \"20m\"",
                )
                .unwrap();

                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.system_config_dir = Some(system_config_dir);
                args.user_config_dir = Some(user_config_dir);

                let config = Config::load_from_dir(&cwd, &args).unwrap();
                // User config should override system config
                assert_eq!(config.resolve_cache_timeout, Duration::from_secs(20 * 60));
            }
        }

        mod app_dir_tests {
            use super::*;

            #[test]
            fn test_app_dir_config_location() {
                let temp_dir = tempfile::tempdir().unwrap();
                let app_dir = temp_dir.path().join("app");
                let config_dir = app_dir.join("config");
                fs::create_dir_all(&config_dir).unwrap();
                fs::write(config_dir.join("cgx.toml"), "resolve_cache_timeout = \"7m\"").unwrap();

                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.app_dir = Some(app_dir.clone());

                let config = Config::load_from_dir(&cwd, &args).unwrap();
                assert_eq!(config.resolve_cache_timeout, Duration::from_secs(7 * 60));
                assert_eq!(config.config_dir, config_dir);
            }

            #[test]
            fn test_app_dir_cache_location() {
                let temp_dir = tempfile::tempdir().unwrap();
                let app_dir = temp_dir.path().join("app");
                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.app_dir = Some(app_dir.clone());

                let config = Config::load_from_dir(&cwd, &args).unwrap();
                assert_eq!(config.cache_dir, app_dir.join("cache"));
            }

            #[test]
            fn test_app_dir_bins_location() {
                let temp_dir = tempfile::tempdir().unwrap();
                let app_dir = temp_dir.path().join("app");
                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.app_dir = Some(app_dir.clone());

                let config = Config::load_from_dir(&cwd, &args).unwrap();
                assert_eq!(config.bin_dir, app_dir.join("bins"));
            }

            #[test]
            fn test_app_dir_build_location() {
                let temp_dir = tempfile::tempdir().unwrap();
                let app_dir = temp_dir.path().join("app");
                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.app_dir = Some(app_dir.clone());

                let config = Config::load_from_dir(&cwd, &args).unwrap();
                assert_eq!(config.build_dir, app_dir.join("build"));
            }

            #[test]
            fn test_app_dir_complete_isolation() {
                let temp_dir = tempfile::tempdir().unwrap();
                let app_dir = temp_dir.path().join("app");
                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.app_dir = Some(app_dir.clone());

                let config = Config::load_from_dir(&cwd, &args).unwrap();

                // All directories should be under app_dir
                assert!(config.config_dir.starts_with(&app_dir));
                assert!(config.cache_dir.starts_with(&app_dir));
                assert!(config.bin_dir.starts_with(&app_dir));
                assert!(config.build_dir.starts_with(&app_dir));
            }
        }

        mod user_config_dir_tests {
            use super::*;

            #[test]
            fn test_user_config_dir_cli_arg() {
                let temp_dir = tempfile::tempdir().unwrap();
                let user_config_dir = temp_dir.path().join("user");
                fs::create_dir_all(&user_config_dir).unwrap();
                fs::write(user_config_dir.join("cgx.toml"), "resolve_cache_timeout = \"8m\"").unwrap();

                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.user_config_dir = Some(user_config_dir.clone());

                let config = Config::load_from_dir(&cwd, &args).unwrap();
                assert_eq!(config.resolve_cache_timeout, Duration::from_secs(8 * 60));
                assert_eq!(config.config_dir, user_config_dir);
            }

            #[test]
            fn test_user_config_dir_overrides_app_dir() {
                let temp_dir = tempfile::tempdir().unwrap();

                // Create app_dir with config
                let app_dir = temp_dir.path().join("app");
                let app_config_dir = app_dir.join("config");
                fs::create_dir_all(&app_config_dir).unwrap();
                fs::write(app_config_dir.join("cgx.toml"), "resolve_cache_timeout = \"9m\"").unwrap();

                // Create user_config_dir with different config
                let user_config_dir = temp_dir.path().join("user");
                fs::create_dir_all(&user_config_dir).unwrap();
                fs::write(
                    user_config_dir.join("cgx.toml"),
                    "resolve_cache_timeout = \"11m\"",
                )
                .unwrap();

                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.app_dir = Some(app_dir.clone());
                args.user_config_dir = Some(user_config_dir.clone());

                let config = Config::load_from_dir(&cwd, &args).unwrap();

                // user_config_dir should override app_dir for config location
                assert_eq!(config.resolve_cache_timeout, Duration::from_secs(11 * 60));
                assert_eq!(config.config_dir, user_config_dir);

                // But cache/bins/build should still come from app_dir
                assert_eq!(config.cache_dir, app_dir.join("cache"));
                assert_eq!(config.bin_dir, app_dir.join("bins"));
                assert_eq!(config.build_dir, app_dir.join("build"));
            }
        }

        mod combined_tests {
            use super::*;

            #[test]
            fn test_all_three_overrides() {
                let temp_dir = tempfile::tempdir().unwrap();

                // System config
                let system_config_dir = temp_dir.path().join("system");
                fs::create_dir_all(&system_config_dir).unwrap();
                fs::write(
                    system_config_dir.join("cgx.toml"),
                    "[tools]\nsystem_tool = \"1\"\n[aliases]\ndummytool = \"system\"",
                )
                .unwrap();

                // App dir with config
                let app_dir = temp_dir.path().join("app");
                let app_config_dir = app_dir.join("config");
                fs::create_dir_all(&app_config_dir).unwrap();
                fs::write(app_config_dir.join("cgx.toml"), "[tools]\napp_tool = \"1\"").unwrap();

                // User config dir
                let user_config_dir = temp_dir.path().join("user");
                fs::create_dir_all(&user_config_dir).unwrap();
                fs::write(
                    user_config_dir.join("cgx.toml"),
                    "resolve_cache_timeout = \"12m\"\n[tools]\nuser_tool = \"1\"\n[aliases]\ndummytool = \
                     \"user\"",
                )
                .unwrap();

                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.system_config_dir = Some(system_config_dir);
                args.app_dir = Some(app_dir.clone());
                args.user_config_dir = Some(user_config_dir.clone());

                let config = Config::load_from_dir(&cwd, &args).unwrap();

                // Should have merged tools from all configs
                assert!(config.tools.contains_key("system_tool"));
                assert!(config.tools.contains_key("user_tool"));
                assert_eq!(config.tools.len(), 2);

                // User config should override alias
                assert_eq!(config.aliases.get("dummytool"), Some(&"user".to_string()));

                // Config dir from user_config_dir
                assert_eq!(config.config_dir, user_config_dir);

                // Other dirs from app_dir
                assert_eq!(config.cache_dir, app_dir.join("cache"));
                assert_eq!(config.bin_dir, app_dir.join("bins"));
                assert_eq!(config.build_dir, app_dir.join("build"));
            }

            #[test]
            fn test_hierarchy_still_works_with_overrides() {
                let temp_dir = tempfile::tempdir().unwrap();

                // App dir
                let app_dir = temp_dir.path().join("app");

                // Create hierarchy with configs
                let root = temp_dir.path().join("work");
                fs::create_dir_all(&root).unwrap();
                fs::write(root.join("cgx.toml"), "[tools]\nroot_tool = \"1\"").unwrap();

                let sub = root.join("sub");
                fs::create_dir_all(&sub).unwrap();
                fs::write(sub.join("cgx.toml"), "[tools]\nsub_tool = \"1\"").unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.app_dir = Some(app_dir);

                let config = Config::load_from_dir(&sub, &args).unwrap();

                // Should have tools from both hierarchy configs
                assert!(config.tools.contains_key("root_tool"));
                assert!(config.tools.contains_key("sub_tool"));
                assert_eq!(config.tools.len(), 2);
            }

            #[test]
            fn test_app_dir_takes_precedence_over_config_file() {
                let temp_dir = tempfile::tempdir().unwrap();

                // App dir
                let app_dir = temp_dir.path().join("app");
                let app_config_dir = app_dir.join("config");
                fs::create_dir_all(&app_config_dir).unwrap();

                // Config file with explicit settings that should be overridden
                let config_file = temp_dir.path().join("explicit.toml");
                let test_config = ConfigFile {
                    cache_dir: Some(temp_dir.path().join("my-cache")),
                    bin_dir: Some(temp_dir.path().join("my-bins")),
                    build_dir: Some(temp_dir.path().join("my-build")),
                    ..Default::default()
                };
                fs::write(&config_file, toml::to_string(&test_config).unwrap()).unwrap();

                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                args.app_dir = Some(app_dir.clone());
                args.config_file = Some(config_file);

                let config = Config::load_from_dir(&cwd, &args).unwrap();

                // CLI --app-dir should win over config file settings
                assert_eq!(config.cache_dir, app_dir.join("cache"));
                assert_eq!(config.bin_dir, app_dir.join("bins"));
                assert_eq!(config.build_dir, app_dir.join("build"));
            }

            #[test]
            fn test_config_file_paths_used_when_no_app_dir() {
                let temp_dir = tempfile::tempdir().unwrap();

                // Config file with explicit path settings
                let config_file = temp_dir.path().join("explicit.toml");
                let test_config = ConfigFile {
                    cache_dir: Some(temp_dir.path().join("my-cache")),
                    bin_dir: Some(temp_dir.path().join("my-bins")),
                    build_dir: Some(temp_dir.path().join("my-build")),
                    ..Default::default()
                };
                fs::write(&config_file, toml::to_string(&test_config).unwrap()).unwrap();

                let cwd = temp_dir.path().join("work");
                fs::create_dir_all(&cwd).unwrap();

                let mut args = CliArgs::parse_from_test_args(["test-crate"]);
                // No --app-dir specified
                args.config_file = Some(config_file);

                let config = Config::load_from_dir(&cwd, &args).unwrap();

                // Config file paths should be used when --app-dir is not specified
                assert_eq!(config.cache_dir, temp_dir.path().join("my-cache"));
                assert_eq!(config.bin_dir, temp_dir.path().join("my-bins"));
                assert_eq!(config.build_dir, temp_dir.path().join("my-build"));
            }
        }
    }

    mod http_config_deserialization_tests {
        use super::*;

        #[test]
        fn test_deserialize_http_config_full() {
            let toml_content = r#"
                [http]
                timeout = "2m"
                retries = 5
                backoff_base = "1s"
                backoff_max = "30s"
                proxy = "http://proxy.example.com:3128"
            "#;

            let config: ConfigFile = toml::from_str(toml_content).unwrap();
            let http = config.http.unwrap();
            assert_eq!(http.timeout, Some(Duration::from_secs(120)));
            assert_eq!(http.retries, Some(5));
            assert_eq!(http.backoff_base, Some(Duration::from_secs(1)));
            assert_eq!(http.backoff_max, Some(Duration::from_secs(30)));
            assert_eq!(http.proxy, Some("http://proxy.example.com:3128".to_string()));
        }

        #[test]
        fn test_deserialize_http_config_partial() {
            let toml_content = r#"
                [http]
                timeout = "45s"
                retries = 3
            "#;

            let config: ConfigFile = toml::from_str(toml_content).unwrap();
            let http = config.http.unwrap();
            assert_eq!(http.timeout, Some(Duration::from_secs(45)));
            assert_eq!(http.retries, Some(3));
            assert_eq!(http.backoff_base, None);
            assert_eq!(http.backoff_max, None);
            assert_eq!(http.proxy, None);
        }

        #[test]
        fn test_deserialize_http_config_empty_section() {
            let toml_content = r#"
                [http]
            "#;

            let config: ConfigFile = toml::from_str(toml_content).unwrap();
            let http = config.http.unwrap();
            assert_eq!(http.timeout, None);
            assert_eq!(http.retries, None);
            assert_eq!(http.backoff_base, None);
            assert_eq!(http.backoff_max, None);
            assert_eq!(http.proxy, None);
        }

        #[test]
        fn test_deserialize_http_config_unknown_field_rejected() {
            let toml_content = r#"
                [http]
                timeoutt = "30s"
            "#;

            let result: std::result::Result<ConfigFile, _> = toml::from_str(toml_content);
            assert!(result.is_err(), "Expected error for unknown field 'timeoutt'");
        }

        #[test]
        fn test_http_config_default_values() {
            let defaults = HttpConfig::default();
            assert_eq!(defaults.timeout, DEFAULT_HTTP_TIMEOUT);
            assert_eq!(defaults.retries, DEFAULT_HTTP_RETRIES);
            assert_eq!(defaults.backoff_base, DEFAULT_HTTP_BACKOFF_BASE);
            assert_eq!(defaults.backoff_max, DEFAULT_HTTP_BACKOFF_MAX);
            assert_eq!(defaults.proxy, None);
        }
    }

    mod build_http_config_tests {
        use super::*;
        use assert_matches::assert_matches;
        use std::io::Write;

        fn create_temp_config(toml_content: &str) -> tempfile::TempDir {
            let temp_dir = tempfile::tempdir().unwrap();
            let config_path = temp_dir.path().join("cgx.toml");
            let mut file = std::fs::File::create(&config_path).unwrap();
            file.write_all(toml_content.as_bytes()).unwrap();
            temp_dir
        }

        #[test]
        fn test_http_config_all_defaults() {
            let temp_dir = tempfile::tempdir().unwrap();
            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.timeout, Duration::from_secs(30));
            assert_eq!(config.http.retries, 2);
            assert_eq!(config.http.backoff_base, Duration::from_millis(500));
            assert_eq!(config.http.backoff_max, Duration::from_secs(5));
            assert_eq!(config.http.proxy, None);
        }

        #[test]
        fn test_http_config_from_config_file() {
            let toml_content = r#"
                [http]
                timeout = "2m"
                retries = 5
                proxy = "http://proxy:3128"
            "#;
            let temp_dir = create_temp_config(toml_content);
            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.timeout, Duration::from_secs(120));
            assert_eq!(config.http.retries, 5);
            assert_eq!(config.http.proxy, Some("http://proxy:3128".to_string()));
        }

        #[test]
        fn test_http_config_cli_overrides_config_file() {
            let toml_content = r#"
                [http]
                timeout = "2m"
                retries = 5
                proxy = "http://proxy:3128"
            "#;
            let temp_dir = create_temp_config(toml_content);
            let mut args = CliArgs::parse_from_test_args([
                "--http-timeout",
                "10s",
                "--http-retries",
                "0",
                "--http-proxy",
                "socks5://other:1080",
                "test-crate",
            ]);
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.timeout, Duration::from_secs(10));
            assert_eq!(config.http.retries, 0);
            assert_eq!(config.http.proxy, Some("socks5://other:1080".to_string()));
        }

        #[test]
        fn test_http_config_cli_overrides_partial() {
            let toml_content = r#"
                [http]
                timeout = "2m"
                retries = 5
                proxy = "http://proxy:3128"
            "#;
            let temp_dir = create_temp_config(toml_content);
            let mut args = CliArgs::parse_from_test_args(["--http-timeout", "10s", "test-crate"]);
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.timeout, Duration::from_secs(10));
            assert_eq!(config.http.retries, 5);
            assert_eq!(config.http.proxy, Some("http://proxy:3128".to_string()));
        }

        #[test]
        fn test_http_config_invalid_timeout_duration() {
            let temp_dir = tempfile::tempdir().unwrap();
            let mut args = CliArgs::parse_from_test_args(["--http-timeout", "not-a-duration", "test-crate"]);
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let result = Config::load_from_dir(temp_dir.path(), &args);
            assert_matches!(result, Err(crate::error::Error::InvalidHttpTimeout { .. }));
        }

        #[test]
        fn test_http_config_zero_retries() {
            let temp_dir = tempfile::tempdir().unwrap();
            let mut args = CliArgs::parse_from_test_args(["--http-retries", "0", "test-crate"]);
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.retries, 0);
        }

        #[test]
        fn test_http_config_backoff_from_config_file() {
            let toml_content = r#"
                [http]
                backoff_base = "2s"
                backoff_max = "60s"
            "#;
            let temp_dir = create_temp_config(toml_content);
            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.backoff_base, Duration::from_secs(2));
            assert_eq!(config.http.backoff_max, Duration::from_secs(60));
        }

        #[test]
        fn test_http_config_backoff_defaults_when_not_in_file() {
            let toml_content = r#"
                [http]
                timeout = "45s"
            "#;
            let temp_dir = create_temp_config(toml_content);
            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.backoff_base, Duration::from_millis(500));
            assert_eq!(config.http.backoff_max, Duration::from_secs(5));
        }

        #[test]
        /// Verifies hierarchy merge behavior where a child config overrides timeout
        /// while inheriting retries from its parent `[http]` section.
        fn test_http_config_hierarchy_merging_preserves_parent_fields() {
            let temp_dir = tempfile::tempdir().unwrap();

            let parent = temp_dir.path().join("parent");
            std::fs::create_dir_all(&parent).unwrap();
            std::fs::write(
                parent.join("cgx.toml"),
                r#"
                [http]
                timeout = "1m"
                retries = 3
                "#,
            )
            .unwrap();

            let child = parent.join("child");
            std::fs::create_dir_all(&child).unwrap();
            std::fs::write(
                child.join("cgx.toml"),
                r#"
                [http]
                timeout = "45s"
                "#,
            )
            .unwrap();

            let args =
                with_isolated_global_config(CliArgs::parse_from_test_args(["test-crate"]), temp_dir.path());

            let config = Config::load_from_dir(&child, &args).unwrap();
            // Timeout comes from the child, overriding the parent, but since retries wasn't
            // specified in the child, it should be inherited from the parent config
            assert_eq!(config.http.timeout, Duration::from_secs(45));
            assert_eq!(config.http.retries, 3);
        }

        #[test]
        /// Verifies hierarchy merge behavior where a child config explicitly
        /// overrides parent timeout and retries fields in `[http]`.
        fn test_http_config_hierarchy_merging_child_overrides_parent_fields() {
            let temp_dir = tempfile::tempdir().unwrap();

            let parent = temp_dir.path().join("parent");
            std::fs::create_dir_all(&parent).unwrap();
            std::fs::write(
                parent.join("cgx.toml"),
                r#"
                [http]
                timeout = "1m"
                retries = 3
                "#,
            )
            .unwrap();

            let child = parent.join("child");
            std::fs::create_dir_all(&child).unwrap();
            std::fs::write(
                child.join("cgx.toml"),
                r#"
                [http]
                timeout = "45s"
                retries = 5
                "#,
            )
            .unwrap();

            let args =
                with_isolated_global_config(CliArgs::parse_from_test_args(["test-crate"]), temp_dir.path());

            let config = Config::load_from_dir(&child, &args).unwrap();
            assert_eq!(config.http.timeout, Duration::from_secs(45));
            assert_eq!(config.http.retries, 5);
        }
    }

    mod build_http_config_env_tests {
        use super::*;
        use sealed_test::prelude::*;
        use std::io::Write;

        fn create_temp_config(toml_content: &str) -> tempfile::TempDir {
            let temp_dir = tempfile::tempdir().unwrap();
            let config_path = temp_dir.path().join("cgx.toml");
            let mut file = std::fs::File::create(&config_path).unwrap();
            file.write_all(toml_content.as_bytes()).unwrap();
            temp_dir
        }

        #[sealed_test(env = [("CARGO_HTTP_TIMEOUT", "45")])]
        /// Verifies `CARGO_HTTP_TIMEOUT` is used when neither CLI nor config file sets timeout.
        fn test_env_timeout_used_when_no_cli_or_config() {
            let temp_dir = tempfile::tempdir().unwrap();
            let args =
                with_isolated_global_config(CliArgs::parse_from_test_args(["test-crate"]), temp_dir.path());

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.timeout, Duration::from_secs(45));
        }

        #[sealed_test(env = [("CARGO_NET_RETRY", "7")])]
        /// Verifies `CARGO_NET_RETRY` is used when neither CLI nor config file sets retries.
        fn test_env_retries_used_when_no_cli_or_config() {
            let temp_dir = tempfile::tempdir().unwrap();
            let args =
                with_isolated_global_config(CliArgs::parse_from_test_args(["test-crate"]), temp_dir.path());

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.retries, 7);
        }

        #[sealed_test(env = [("CARGO_HTTP_PROXY", "socks5://env-proxy:1080")])]
        /// Verifies `CARGO_HTTP_PROXY` is used when neither CLI nor config file sets proxy.
        fn test_env_proxy_used_when_no_cli_or_config() {
            let temp_dir = tempfile::tempdir().unwrap();
            let args =
                with_isolated_global_config(CliArgs::parse_from_test_args(["test-crate"]), temp_dir.path());

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.proxy, Some("socks5://env-proxy:1080".to_string()));
        }

        #[sealed_test(env = [
            ("CARGO_HTTP_TIMEOUT", "45"),
            ("CARGO_NET_RETRY", "7"),
            ("CARGO_HTTP_PROXY", "http://env-proxy:3128")
        ])]
        /// Verifies CLI HTTP flags take precedence over Cargo HTTP environment variables.
        fn test_cli_overrides_env() {
            let temp_dir = tempfile::tempdir().unwrap();
            let args = with_isolated_global_config(
                CliArgs::parse_from_test_args([
                    "--http-timeout",
                    "10s",
                    "--http-retries",
                    "1",
                    "--http-proxy",
                    "socks5://cli-proxy:1080",
                    "test-crate",
                ]),
                temp_dir.path(),
            );

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.timeout, Duration::from_secs(10));
            assert_eq!(config.http.retries, 1);
            assert_eq!(config.http.proxy, Some("socks5://cli-proxy:1080".to_string()));
        }

        #[sealed_test(env = [
            ("CARGO_HTTP_TIMEOUT", "45"),
            ("CARGO_NET_RETRY", "7"),
            ("CARGO_HTTP_PROXY", "http://env-proxy:3128")
        ])]
        /// Verifies config file `[http]` values take precedence over Cargo HTTP env variables.
        fn test_config_file_overrides_env() {
            let toml_content = r#"
                [http]
                timeout = "2m"
                retries = 5
                proxy = "http://config-proxy:8080"
            "#;
            let temp_dir = create_temp_config(toml_content);
            let args =
                with_isolated_global_config(CliArgs::parse_from_test_args(["test-crate"]), temp_dir.path());

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.timeout, Duration::from_secs(120));
            assert_eq!(config.http.retries, 5);
            assert_eq!(config.http.proxy, Some("http://config-proxy:8080".to_string()));
        }

        #[sealed_test(env = [("CARGO_HTTP_TIMEOUT", "not-a-number")])]
        /// Verifies invalid `CARGO_HTTP_TIMEOUT` falls back to the built-in default timeout.
        fn test_invalid_env_timeout_falls_back_to_default() {
            let temp_dir = tempfile::tempdir().unwrap();
            let args =
                with_isolated_global_config(CliArgs::parse_from_test_args(["test-crate"]), temp_dir.path());

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.timeout, DEFAULT_HTTP_TIMEOUT);
        }

        #[sealed_test(env = [("CARGO_NET_RETRY", "not-a-number")])]
        /// Verifies invalid `CARGO_NET_RETRY` falls back to the built-in default retries value.
        fn test_invalid_env_retries_falls_back_to_default() {
            let temp_dir = tempfile::tempdir().unwrap();
            let args =
                with_isolated_global_config(CliArgs::parse_from_test_args(["test-crate"]), temp_dir.path());

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();
            assert_eq!(config.http.retries, DEFAULT_HTTP_RETRIES);
        }
    }

    mod build_http_config_direct_tests {
        use super::*;

        #[test]
        fn test_config_file_timeout_overrides_defaults() {
            let config_file = HttpConfigFile {
                timeout: Some(Duration::from_secs(120)),
                ..Default::default()
            };
            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let http = Config::build_http_config(&config_file, &args).unwrap();
            assert_eq!(http.timeout, Duration::from_secs(120));
            assert_eq!(http.retries, DEFAULT_HTTP_RETRIES);
        }

        #[test]
        fn test_config_file_retries_overrides_defaults() {
            let config_file = HttpConfigFile {
                retries: Some(10),
                ..Default::default()
            };
            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let http = Config::build_http_config(&config_file, &args).unwrap();
            assert_eq!(http.retries, 10);
        }

        #[test]
        fn test_config_file_proxy_overrides_defaults() {
            let config_file = HttpConfigFile {
                proxy: Some("http://proxy:3128".to_string()),
                ..Default::default()
            };
            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let http = Config::build_http_config(&config_file, &args).unwrap();
            assert_eq!(http.proxy, Some("http://proxy:3128".to_string()));
        }

        #[test]
        fn test_cli_timeout_overrides_config_file() {
            let config_file = HttpConfigFile {
                timeout: Some(Duration::from_secs(120)),
                ..Default::default()
            };
            let args = CliArgs::parse_from_test_args(["--http-timeout", "10s", "test-crate"]);
            let http = Config::build_http_config(&config_file, &args).unwrap();
            assert_eq!(http.timeout, Duration::from_secs(10));
        }

        #[test]
        fn test_cli_retries_overrides_config_file() {
            let config_file = HttpConfigFile {
                retries: Some(10),
                ..Default::default()
            };
            let args = CliArgs::parse_from_test_args(["--http-retries", "0", "test-crate"]);
            let http = Config::build_http_config(&config_file, &args).unwrap();
            assert_eq!(http.retries, 0);
        }

        #[test]
        fn test_cli_proxy_overrides_config_file() {
            let config_file = HttpConfigFile {
                proxy: Some("http://old:3128".to_string()),
                ..Default::default()
            };
            let args = CliArgs::parse_from_test_args(["--http-proxy", "socks5://new:1080", "test-crate"]);
            let http = Config::build_http_config(&config_file, &args).unwrap();
            assert_eq!(http.proxy, Some("socks5://new:1080".to_string()));
        }

        #[test]
        fn test_empty_config_file_yields_defaults() {
            let config_file = HttpConfigFile::default();
            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let http = Config::build_http_config(&config_file, &args).unwrap();
            assert_eq!(http.timeout, DEFAULT_HTTP_TIMEOUT);
            assert_eq!(http.retries, DEFAULT_HTTP_RETRIES);
            assert_eq!(http.backoff_base, DEFAULT_HTTP_BACKOFF_BASE);
            assert_eq!(http.backoff_max, DEFAULT_HTTP_BACKOFF_MAX);
            assert_eq!(http.proxy, None);
        }

        #[test]
        fn test_backoff_from_config_file() {
            let config_file = HttpConfigFile {
                backoff_base: Some(Duration::from_secs(2)),
                backoff_max: Some(Duration::from_secs(60)),
                ..Default::default()
            };
            let args = CliArgs::parse_from_test_args(["test-crate"]);
            let http = Config::build_http_config(&config_file, &args).unwrap();
            assert_eq!(http.backoff_base, Duration::from_secs(2));
            assert_eq!(http.backoff_max, Duration::from_secs(60));
        }
    }

    mod error_tests {
        use super::*;
        use assert_matches::assert_matches;

        #[test]
        fn test_invalid_toml_syntax() {
            let test_case = crate::testdata::ConfigTestCase::invalid_toml();

            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.config_file = Some(test_case.path().to_path_buf());

            let result = Config::load(&args);
            assert_matches!(result, Err(crate::error::Error::ConfigExtract { .. }));
        }

        #[test]
        fn test_invalid_config_options_raise_error() {
            let test_case = crate::testdata::ConfigTestCase::invalid_options();

            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.config_file = Some(test_case.path().to_path_buf());

            let result = Config::load(&args);
            assert_matches!(result, Err(crate::error::Error::ConfigExtract { .. }));
        }

        #[test]
        fn test_nonexistent_explicit_config_file() {
            let test_case = crate::testdata::ConfigTestCase::nonexistent();

            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            args.config_file = Some(test_case.path().to_path_buf());

            let config = Config::load(&args).unwrap();

            assert_eq!(config.resolve_cache_timeout, Duration::from_secs(60 * 60));
        }

        #[test]
        fn test_no_config_files_uses_defaults() {
            let temp_dir = tempfile::tempdir().unwrap();

            let mut args = CliArgs::parse_from_test_args(["test-crate"]);
            // Ensure isolation from developer's real cgx config on their system.
            // Without these overrides, this test would load ~/.config/cgx/cgx.toml if it exists,
            // causing the test to fail with config values from the developer's actual config.
            args.system_config_dir = Some(temp_dir.path().join("system"));
            args.user_config_dir = Some(temp_dir.path().join("user"));

            let config = Config::load_from_dir(temp_dir.path(), &args).unwrap();

            assert_eq!(config.resolve_cache_timeout, Duration::from_secs(60 * 60));
            assert!(!config.offline);
            assert!(config.locked); // Default is true per issue #55
            assert_eq!(config.toolchain, None);
            assert_eq!(config.tools.len(), 0);
            assert_eq!(config.aliases.len(), 0);
        }
    }
}