jacs 0.9.12

JACS JSON AI Communication Standard
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
// Allow deprecated functions within this module - they call each other during migration
#![allow(deprecated)]

use crate::error::JacsError;
use crate::schema::utils::{CONFIG_SCHEMA_STRING, EmbeddedSchemaResolver};
use crate::storage::jenv::{EnvError, get_env_var, get_required_env_var};
use getset::Getters;
use jsonschema::{Draft, Validator};
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::str::FromStr;
use tracing::{error, info, warn};

use crate::validation::split_agent_id;

/// Source for resolving public keys during signature verification.
///
/// This enum represents the different sources from which JACS can retrieve
/// public keys when verifying document signatures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyResolutionSource {
    /// Local filesystem (default). Keys are stored in the data directory
    /// under `public_keys/{hash}.pem`.
    Local,
    /// DNS TXT record verification. Requires the agent to have a domain
    /// configured and the public key hash published in DNS.
    Dns,
    /// Remote registry key service. Fetches public keys from a configured
    /// remote key distribution service (JACS_KEYS_BASE_URL).
    Registry,
}

impl fmt::Display for KeyResolutionSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyResolutionSource::Local => write!(f, "local"),
            KeyResolutionSource::Dns => write!(f, "dns"),
            KeyResolutionSource::Registry => write!(f, "registry"),
        }
    }
}

/// Network capabilities that require explicit opt-in.
///
/// JACS keeps network access disabled by default. Callers must set either the
/// capability-specific environment variable or the umbrella
/// `JACS_ALLOW_NETWORK=true` override before any network activity is permitted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NetworkCapability {
    DnsLookup,
    RemoteKeyFetch,
    RegistryLookup,
    RemoteSchemaFetch,
    JwksFetch,
    AgentCardFetch,
}

impl NetworkCapability {
    pub fn env_var(self) -> &'static str {
        match self {
            NetworkCapability::DnsLookup => "JACS_ALLOW_DNS",
            NetworkCapability::RemoteKeyFetch => "JACS_ALLOW_REMOTE_KEY_FETCH",
            NetworkCapability::RegistryLookup => "JACS_ALLOW_REGISTRY",
            NetworkCapability::RemoteSchemaFetch => "JACS_ALLOW_REMOTE_SCHEMA_FETCH",
            NetworkCapability::JwksFetch => "JACS_ALLOW_JWKS_FETCH",
            NetworkCapability::AgentCardFetch => "JACS_ALLOW_AGENT_CARD_FETCH",
        }
    }

    pub fn description(self) -> &'static str {
        match self {
            NetworkCapability::DnsLookup => "DNS lookup",
            NetworkCapability::RemoteKeyFetch => "remote public-key fetch",
            NetworkCapability::RegistryLookup => "registry lookup",
            NetworkCapability::RemoteSchemaFetch => "remote schema fetch",
            NetworkCapability::JwksFetch => "JWKS fetch",
            NetworkCapability::AgentCardFetch => "A2A Agent Card fetch",
        }
    }
}

impl fmt::Display for NetworkCapability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.description())
    }
}

impl FromStr for NetworkCapability {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "dns" | "dns_lookup" => Ok(NetworkCapability::DnsLookup),
            "remote_key_fetch" | "key_fetch" | "public_key_fetch" | "registry_key_fetch" => {
                Ok(NetworkCapability::RemoteKeyFetch)
            }
            "registry" | "registry_lookup" => Ok(NetworkCapability::RegistryLookup),
            "schema" | "schema_fetch" | "remote_schema_fetch" => {
                Ok(NetworkCapability::RemoteSchemaFetch)
            }
            "jwks" | "jwks_fetch" => Ok(NetworkCapability::JwksFetch),
            "agent_card" | "agent_card_fetch" | "a2a_discovery" | "agent_discovery" => {
                Ok(NetworkCapability::AgentCardFetch)
            }
            other => Err(format!(
                "Unknown network capability '{}'. Valid values are: dns, remote_key_fetch, registry, remote_schema_fetch, jwks, agent_card_fetch",
                other
            )),
        }
    }
}

fn env_var_truthy(key: &str) -> bool {
    match get_env_var(key, false) {
        Ok(Some(value)) => matches!(
            value.trim().to_ascii_lowercase().as_str(),
            "1" | "true" | "yes" | "on"
        ),
        _ => false,
    }
}

/// Returns whether the requested network capability is explicitly allowed.
pub fn is_network_access_allowed(capability: NetworkCapability) -> bool {
    env_var_truthy("JACS_ALLOW_NETWORK") || env_var_truthy(capability.env_var())
}

/// Enforce explicit opt-in before any network access occurs.
pub fn ensure_network_access(capability: NetworkCapability) -> Result<(), JacsError> {
    if is_network_access_allowed(capability) {
        return Ok(());
    }

    Err(JacsError::ConfigError(format!(
        "{} is disabled by default. Set {}=true to allow it, or JACS_ALLOW_NETWORK=true to allow all JACS network access.",
        capability.description(),
        capability.env_var(),
    )))
}

impl FromStr for KeyResolutionSource {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "local" => Ok(KeyResolutionSource::Local),
            "dns" => Ok(KeyResolutionSource::Dns),
            "registry" => Ok(KeyResolutionSource::Registry),
            other => Err(format!(
                "Unknown key resolution source '{}'. Valid options are: local, dns, registry",
                other
            )),
        }
    }
}

/// Returns the configured key resolution order from the `JACS_KEY_RESOLUTION` environment variable.
///
/// The order determines which sources are tried (and in what sequence) when resolving
/// public keys for signature verification.
///
/// # Environment Variable
///
/// `JACS_KEY_RESOLUTION` - Comma-separated list of sources to try in order.
///
/// # Valid Values
///
/// - `local` - Local filesystem (keys in `public_keys/` directory)
/// - `dns` - DNS TXT record verification
/// - `registry` - Remote registry key service (JACS_KEYS_BASE_URL)
///
/// # Examples
///
/// ```bash
/// # Default: try local first, then registry
/// JACS_KEY_RESOLUTION=local,registry
///
/// # Include DNS verification
/// JACS_KEY_RESOLUTION=local,dns,registry
///
/// # Air-gapped mode (local only)
/// JACS_KEY_RESOLUTION=local
///
/// # Registry only (for testing or cloud-native deployments)
/// JACS_KEY_RESOLUTION=registry
/// ```
///
/// # Default
///
/// If the environment variable is not set or empty, returns `[Local, Registry]`.
///
/// # Behavior
///
/// - Invalid source names are logged as warnings and skipped
/// - Duplicate sources are preserved (first occurrence is used)
/// - If parsing results in an empty list, falls back to the default
pub fn get_key_resolution_order() -> Vec<KeyResolutionSource> {
    let default_order = vec![KeyResolutionSource::Local, KeyResolutionSource::Registry];

    let order_str = match get_env_var("JACS_KEY_RESOLUTION", false) {
        Ok(Some(val)) if !val.is_empty() => val,
        _ => return default_order,
    };

    let mut sources = Vec::new();
    for part in order_str.split(',') {
        match KeyResolutionSource::from_str(part) {
            Ok(source) => sources.push(source),
            Err(e) => {
                warn!("JACS_KEY_RESOLUTION: {}", e);
            }
        }
    }

    if sources.is_empty() {
        warn!(
            "JACS_KEY_RESOLUTION resulted in empty list after parsing '{}', using default (local,registry)",
            order_str
        );
        return default_order;
    }

    info!("Key resolution order: {:?}", sources);
    sources
}

pub mod constants;

/*
Config is embedded in agents and may have private information.

Configuration Loading (12-Factor App Pattern)
=============================================

JACS follows the 12-Factor App methodology for configuration (https://12factor.net/config).
Configuration is loaded in the following order, with later sources overriding earlier ones:

1. DEFAULTS: Sensible defaults are built into the code
2. CONFIG FILE: Optional JSON file provides project-specific defaults
3. ENVIRONMENT VARIABLES: Always take highest precedence (12-Factor compliance)

This allows:
- Development: Use config file for convenience
- Production: Override with environment variables for security and flexibility
- CI/CD: Set environment variables in deployment scripts

Environment Variables Supported:
- JACS_USE_SECURITY
- JACS_DATA_DIRECTORY
- JACS_KEY_DIRECTORY
- JACS_AGENT_PRIVATE_KEY_FILENAME
- JACS_AGENT_PUBLIC_KEY_FILENAME
- JACS_AGENT_KEY_ALGORITHM
- JACS_PRIVATE_KEY_PASSWORD (NEVER put in config file!)
- JACS_AGENT_ID_AND_VERSION
- JACS_DEFAULT_STORAGE
- JACS_AGENT_DOMAIN
- JACS_DNS_VALIDATE
- JACS_DNS_STRICT
- JACS_DNS_REQUIRED
- JACS_KEY_RESOLUTION (comma-separated: local,dns,registry - controls key lookup order)
- JACS_ALLOW_NETWORK
- JACS_ALLOW_DNS
- JACS_ALLOW_REMOTE_KEY_FETCH
- JACS_ALLOW_REGISTRY
- JACS_ALLOW_REMOTE_SCHEMA_FETCH
- JACS_ALLOW_JWKS_FETCH
- JACS_ALLOW_AGENT_CARD_FETCH

Usage:
```rust
// Recommended: 12-Factor compliant loading
let config = load_config_12factor(Some("jacs.config.json"))?;

// Or with just defaults and env vars (no config file)
let config = load_config_12factor(None)?;
```

*/

#[derive(Serialize, Deserialize, Debug, Clone, Getters)]
pub struct Config {
    #[serde(rename = "$schema")]
    #[serde(default = "default_schema")]
    #[getset(get)]
    schema: String,
    #[getset(get = "pub")]
    #[serde(default = "default_security")]
    jacs_use_security: Option<String>,
    #[getset(get = "pub")]
    #[serde(default = "default_data_directory")]
    jacs_data_directory: Option<String>,
    #[getset(get = "pub")]
    #[serde(default = "default_key_directory")]
    jacs_key_directory: Option<String>,
    #[getset(get = "pub")]
    jacs_agent_private_key_filename: Option<String>,
    #[getset(get = "pub")]
    jacs_agent_public_key_filename: Option<String>,
    #[getset(get = "pub")]
    #[serde(default = "default_algorithm")]
    jacs_agent_key_algorithm: Option<String>,
    /// DEPRECATED: Password should NEVER be stored in config files.
    /// Use the JACS_PRIVATE_KEY_PASSWORD environment variable instead.
    /// This field is kept for backwards compatibility to detect and warn about insecure configs.
    #[serde(default, skip_serializing)]
    jacs_private_key_password: Option<String>,
    #[getset(get = "pub")]
    jacs_agent_id_and_version: Option<String>,
    #[getset(get = "pub")]
    #[serde(default = "default_storage")]
    jacs_default_storage: Option<String>,
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_agent_domain: Option<String>,
    // DNS policy
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_dns_validate: Option<bool>,
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_dns_strict: Option<bool>,
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_dns_required: Option<bool>,
    /// OS keychain backend: "auto", "macos-keychain", "linux-secret-service", or "disabled".
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_keychain_backend: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observability: Option<ObservabilityConfig>,
    // Database storage configuration
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_database_url: Option<String>,
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_database_max_connections: Option<u32>,
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_database_min_connections: Option<u32>,
    #[getset(get = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    jacs_database_connect_timeout_secs: Option<u64>,
    /// Directory containing the config file. Set automatically by `Config::from_file()`.
    /// Used by `load_by_config` to calculate `storage_root` without re-deriving from path.
    /// Not serialized — this is runtime-only metadata.
    #[serde(skip)]
    config_dir: Option<std::path::PathBuf>,
}

fn default_schema() -> String {
    "https://hai.ai/schemas/jacs.config.schema.json".to_string()
}

/// Macro to generate default functions that check an environment variable with a fallback value.
/// This reduces repetition across the simple default_* functions.
macro_rules! env_default {
    ($fn_name:ident, $env_var:literal, $default:expr) => {
        fn $fn_name() -> Option<String> {
            match get_env_var($env_var, false) {
                Ok(Some(val)) if !val.is_empty() => Some(val),
                _ => Some($default.to_string()),
            }
        }
    };
}

env_default!(default_storage, "JACS_DEFAULT_STORAGE", "fs");
env_default!(default_algorithm, "JACS_AGENT_KEY_ALGORITHM", "pq2025");
/// Check `JACS_ENABLE_FILESYSTEM_QUARANTINE` (preferred) first,
/// fall back to legacy `JACS_USE_SECURITY` with a deprecation warning.
fn default_security() -> Option<String> {
    // Preferred new name
    if let Ok(Some(val)) = get_env_var("JACS_ENABLE_FILESYSTEM_QUARANTINE", false) {
        if !val.is_empty() {
            return Some(val);
        }
    }
    // Legacy name (backwards compatible)
    if let Ok(Some(val)) = get_env_var("JACS_USE_SECURITY", false) {
        if !val.is_empty() {
            eprintln!(
                "DEPRECATION WARNING: JACS_USE_SECURITY is deprecated. \
                Use JACS_ENABLE_FILESYSTEM_QUARANTINE instead. \
                This env var only controls filesystem quarantine of executable files, \
                not cryptographic verification."
            );
            return Some(val);
        }
    }
    Some("false".to_string())
}

/// Helper to compute a directory default with CWD resolution for filesystem storage.
/// Falls back to a relative path if CWD cannot be determined or storage is not "fs".
fn default_directory_with_cwd(env_var: &str, dir_name: &str) -> Option<String> {
    match get_env_var(env_var, false) {
        Ok(Some(val)) if !val.is_empty() => Some(val),
        _ => {
            let fallback = format!("./{}", dir_name);
            if default_storage() == Some("fs".to_string()) {
                match std::env::current_dir() {
                    Ok(cur_dir) => Some(cur_dir.join(dir_name).to_string_lossy().to_string()),
                    Err(_) => Some(fallback),
                }
            } else {
                Some(fallback)
            }
        }
    }
}

fn default_data_directory() -> Option<String> {
    default_directory_with_cwd("JACS_DATA_DIRECTORY", "jacs_data")
}

fn default_key_directory() -> Option<String> {
    default_directory_with_cwd("JACS_KEY_DIRECTORY", "jacs_keys")
}

impl Default for Config {
    fn default() -> Self {
        Config {
            schema: default_schema(),
            jacs_use_security: default_security(),
            jacs_data_directory: default_data_directory(),
            jacs_key_directory: default_key_directory(),
            jacs_agent_private_key_filename: None,
            jacs_agent_public_key_filename: None,
            jacs_agent_key_algorithm: default_algorithm(),
            jacs_private_key_password: None,
            jacs_agent_id_and_version: None,
            jacs_default_storage: default_storage(),
            jacs_agent_domain: None,
            jacs_dns_validate: None,
            jacs_dns_strict: None,
            jacs_dns_required: None,
            jacs_keychain_backend: None,
            observability: None,
            jacs_database_url: None,
            jacs_database_max_connections: None,
            jacs_database_min_connections: None,
            jacs_database_connect_timeout_secs: None,
            config_dir: None,
        }
    }
}

/// Builder for creating Config instances with a fluent API.
///
/// # Example
/// ```rust,ignore
/// let config = Config::builder()
///     .key_algorithm("Ed25519")
///     .key_directory("/custom/keys")
///     .data_directory("/custom/data")
///     .use_security(true)
///     .build();
/// ```
#[derive(Debug, Default)]
pub struct ConfigBuilder {
    agent_id_and_version: Option<String>,
    key_algorithm: Option<String>,
    private_key_filename: Option<String>,
    public_key_filename: Option<String>,
    key_directory: Option<String>,
    data_directory: Option<String>,
    default_storage: Option<String>,
    use_security: Option<bool>,
    agent_domain: Option<String>,
    dns_validate: Option<bool>,
    dns_strict: Option<bool>,
    dns_required: Option<bool>,
    observability: Option<ObservabilityConfig>,
}

impl ConfigBuilder {
    /// Create a new ConfigBuilder with no values set.
    /// All fields will use sensible defaults when `build()` is called.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the agent ID and version (format: "UUID:UUID").
    pub fn agent_id_and_version(mut self, id_version: &str) -> Self {
        self.agent_id_and_version = Some(id_version.to_string());
        self
    }

    /// Set the key algorithm (e.g., "RSA-PSS", "Ed25519", "pq2025").
    pub fn key_algorithm(mut self, algo: &str) -> Self {
        self.key_algorithm = Some(algo.to_string());
        self
    }

    /// Set the private key filename.
    pub fn private_key_filename(mut self, filename: &str) -> Self {
        self.private_key_filename = Some(filename.to_string());
        self
    }

    /// Set the public key filename.
    pub fn public_key_filename(mut self, filename: &str) -> Self {
        self.public_key_filename = Some(filename.to_string());
        self
    }

    /// Set the directory where keys are stored.
    pub fn key_directory(mut self, dir: &str) -> Self {
        self.key_directory = Some(dir.to_string());
        self
    }

    /// Set the directory where data is stored.
    pub fn data_directory(mut self, dir: &str) -> Self {
        self.data_directory = Some(dir.to_string());
        self
    }

    /// Set the default storage backend (e.g., "fs", "memory").
    pub fn default_storage(mut self, storage: &str) -> Self {
        self.default_storage = Some(storage.to_string());
        self
    }

    /// Enable or disable security features.
    pub fn use_security(mut self, enabled: bool) -> Self {
        self.use_security = Some(enabled);
        self
    }

    /// Set the agent domain for DNS validation.
    pub fn agent_domain(mut self, domain: &str) -> Self {
        self.agent_domain = Some(domain.to_string());
        self
    }

    /// Enable or disable DNS validation.
    pub fn dns_validate(mut self, enabled: bool) -> Self {
        self.dns_validate = Some(enabled);
        self
    }

    /// Enable or disable strict DNS mode.
    pub fn dns_strict(mut self, enabled: bool) -> Self {
        self.dns_strict = Some(enabled);
        self
    }

    /// Enable or disable DNS requirement.
    pub fn dns_required(mut self, required: bool) -> Self {
        self.dns_required = Some(required);
        self
    }

    /// Set the observability configuration.
    pub fn observability(mut self, config: ObservabilityConfig) -> Self {
        self.observability = Some(config);
        self
    }

    /// Build the Config instance.
    ///
    /// Fields not explicitly set will use sensible defaults:
    /// - `key_algorithm`: "pq2025"
    /// - `key_directory`: "./jacs_keys"
    /// - `data_directory`: "./jacs_data"
    /// - `default_storage`: "fs"
    /// - `use_security`: false
    pub fn build(self) -> Config {
        Config {
            schema: default_schema(),
            jacs_use_security: Some(
                self.use_security
                    .map(|b| b.to_string())
                    .unwrap_or_else(|| "false".to_string()),
            ),
            jacs_data_directory: Some(
                self.data_directory
                    .unwrap_or_else(|| "./jacs_data".to_string()),
            ),
            jacs_key_directory: Some(
                self.key_directory
                    .unwrap_or_else(|| "./jacs_keys".to_string()),
            ),
            jacs_agent_private_key_filename: self.private_key_filename,
            jacs_agent_public_key_filename: self.public_key_filename,
            jacs_agent_key_algorithm: Some(
                self.key_algorithm.unwrap_or_else(|| "pq2025".to_string()),
            ),
            jacs_private_key_password: None, // Never store password in config
            jacs_agent_id_and_version: self.agent_id_and_version,
            jacs_default_storage: Some(self.default_storage.unwrap_or_else(|| "fs".to_string())),
            jacs_agent_domain: self.agent_domain,
            jacs_dns_validate: self.dns_validate,
            jacs_dns_strict: self.dns_strict,
            jacs_dns_required: self.dns_required,
            jacs_keychain_backend: None,
            observability: self.observability,
            jacs_database_url: None,
            jacs_database_max_connections: None,
            jacs_database_min_connections: None,
            jacs_database_connect_timeout_secs: None,
            config_dir: None,
        }
    }
}

impl Config {
    /// Create a ConfigBuilder for fluent configuration.
    ///
    /// # Example
    /// ```rust,ignore
    /// let config = Config::builder()
    ///     .key_algorithm("Ed25519")
    ///     .key_directory("/custom/keys")
    ///     .use_security(true)
    ///     .build();
    /// ```
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }

    /// Create a new Config.
    ///
    /// # Arguments
    /// * `jacs_private_key_password` - DEPRECATED: This parameter is ignored.
    ///   Passwords should be set via the JACS_PRIVATE_KEY_PASSWORD environment variable only.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        jacs_use_security: Option<String>,
        jacs_data_directory: Option<String>,
        jacs_key_directory: Option<String>,
        jacs_agent_private_key_filename: Option<String>,
        jacs_agent_public_key_filename: Option<String>,
        jacs_agent_key_algorithm: Option<String>,
        jacs_private_key_password: Option<String>,
        jacs_agent_id_and_version: Option<String>,
        jacs_default_storage: Option<String>,
    ) -> Config {
        // Warn if password is passed - it will be ignored
        if jacs_private_key_password.is_some() {
            warn!(
                "SECURITY WARNING: Password passed to Config::new() is deprecated and will be ignored. \
                Use the JACS_PRIVATE_KEY_PASSWORD environment variable instead."
            );
        }
        Config {
            schema: default_schema(),
            jacs_use_security,
            jacs_data_directory,
            jacs_key_directory,
            jacs_agent_private_key_filename,
            jacs_agent_public_key_filename,
            jacs_agent_key_algorithm,
            jacs_private_key_password: None, // Never store password in config
            jacs_agent_id_and_version,
            jacs_default_storage,
            jacs_agent_domain: None,
            jacs_dns_validate: None,
            jacs_dns_strict: None,
            jacs_dns_required: None,
            jacs_keychain_backend: None,
            observability: None,
            jacs_database_url: None,
            jacs_database_max_connections: None,
            jacs_database_min_connections: None,
            jacs_database_connect_timeout_secs: None,
            config_dir: None,
        }
    }

    pub fn get_key_algorithm(&self) -> Result<String, JacsError> {
        // 1. Try getting from config
        if let Some(algo_str) = self.jacs_agent_key_algorithm().as_deref() {
            // Config exists and has the key algorithm string
            return Ok(algo_str.to_string());
        }
        get_required_env_var("JACS_AGENT_KEY_ALGORITHM", true)
            .map_err(|e| JacsError::ConfigError(e.to_string()))
    }

    /// Returns the directory containing the config file, if set.
    ///
    /// This is set automatically by `Config::from_file()` to the parent directory
    /// of the config file path. It is used by `load_by_config` to correctly
    /// calculate `storage_root` without requiring the caller to pass the original
    /// path or set environment variables as a side-channel.
    pub fn config_dir(&self) -> Option<&std::path::Path> {
        self.config_dir.as_deref()
    }

    /// Sets the config directory explicitly.
    ///
    /// Normally set automatically by `Config::from_file()`. Use this when
    /// constructing a Config programmatically and you need `load_by_config`
    /// to resolve storage paths relative to a specific directory.
    pub fn set_config_dir(&mut self, dir: Option<std::path::PathBuf>) {
        self.config_dir = dir;
    }

    fn replace_if_some<T>(target: &mut Option<T>, incoming: Option<T>) {
        if incoming.is_some() {
            *target = incoming;
        }
    }

    fn env_opt(key: &str) -> Option<String> {
        match get_env_var(key, false) {
            Ok(Some(val)) if !val.is_empty() => Some(val),
            _ => None,
        }
    }

    fn env_opt_bool(key: &str) -> Option<bool> {
        match Self::env_opt(key) {
            Some(val) => Some(val.to_lowercase() == "true" || val == "1"),
            None => None,
        }
    }

    fn apply_string_override(target: &mut Option<String>, key: &str) {
        if let Some(val) = Self::env_opt(key) {
            *target = Some(val);
        }
    }

    fn apply_bool_override(target: &mut Option<bool>, key: &str) {
        if let Some(val) = Self::env_opt_bool(key) {
            *target = Some(val);
        }
    }

    fn apply_parsed_override<T>(target: &mut Option<T>, key: &str)
    where
        T: std::str::FromStr,
    {
        if let Some(val) = Self::env_opt(key)
            && let Ok(parsed) = val.parse::<T>()
        {
            *target = Some(parsed);
        }
    }

    /// Merge another config into this one.
    /// Values from `other` will override values in `self` if they are Some.
    pub fn merge(&mut self, other: Config) {
        let Config {
            schema: _,
            jacs_use_security,
            jacs_data_directory,
            jacs_key_directory,
            jacs_agent_private_key_filename,
            jacs_agent_public_key_filename,
            jacs_agent_key_algorithm,
            jacs_private_key_password: _,
            jacs_agent_id_and_version,
            jacs_default_storage,
            jacs_agent_domain,
            jacs_dns_validate,
            jacs_dns_strict,
            jacs_dns_required,
            jacs_keychain_backend,
            observability,
            jacs_database_url,
            jacs_database_max_connections,
            jacs_database_min_connections,
            jacs_database_connect_timeout_secs,
            config_dir,
        } = other;

        Self::replace_if_some(&mut self.jacs_use_security, jacs_use_security);
        Self::replace_if_some(&mut self.jacs_data_directory, jacs_data_directory);
        Self::replace_if_some(&mut self.jacs_key_directory, jacs_key_directory);
        Self::replace_if_some(
            &mut self.jacs_agent_private_key_filename,
            jacs_agent_private_key_filename,
        );
        Self::replace_if_some(
            &mut self.jacs_agent_public_key_filename,
            jacs_agent_public_key_filename,
        );
        Self::replace_if_some(&mut self.jacs_agent_key_algorithm, jacs_agent_key_algorithm);
        Self::replace_if_some(
            &mut self.jacs_agent_id_and_version,
            jacs_agent_id_and_version,
        );
        Self::replace_if_some(&mut self.jacs_default_storage, jacs_default_storage);
        Self::replace_if_some(&mut self.jacs_agent_domain, jacs_agent_domain);
        Self::replace_if_some(&mut self.jacs_dns_validate, jacs_dns_validate);
        Self::replace_if_some(&mut self.jacs_dns_strict, jacs_dns_strict);
        Self::replace_if_some(&mut self.jacs_dns_required, jacs_dns_required);
        Self::replace_if_some(&mut self.jacs_keychain_backend, jacs_keychain_backend);
        Self::replace_if_some(&mut self.observability, observability);
        Self::replace_if_some(&mut self.jacs_database_url, jacs_database_url);
        Self::replace_if_some(
            &mut self.jacs_database_max_connections,
            jacs_database_max_connections,
        );
        Self::replace_if_some(
            &mut self.jacs_database_min_connections,
            jacs_database_min_connections,
        );
        Self::replace_if_some(
            &mut self.jacs_database_connect_timeout_secs,
            jacs_database_connect_timeout_secs,
        );
        // config_dir from the incoming config takes precedence if set
        Self::replace_if_some(&mut self.config_dir, config_dir);
    }

    /// Apply environment variable overrides to this config.
    /// Environment variables always take precedence (12-Factor compliance).
    ///
    /// This method reads from the following environment variables:
    /// - JACS_USE_SECURITY
    /// - JACS_DATA_DIRECTORY
    /// - JACS_KEY_DIRECTORY
    /// - JACS_AGENT_PRIVATE_KEY_FILENAME
    /// - JACS_AGENT_PUBLIC_KEY_FILENAME
    /// - JACS_AGENT_KEY_ALGORITHM
    /// - JACS_AGENT_ID_AND_VERSION
    /// - JACS_DEFAULT_STORAGE
    /// - JACS_AGENT_DOMAIN
    /// - JACS_DNS_VALIDATE
    /// - JACS_DNS_STRICT
    /// - JACS_DNS_REQUIRED
    ///
    /// Note: JACS_PRIVATE_KEY_PASSWORD is intentionally NOT loaded into config.
    /// It should be read directly from environment when needed for security.
    pub fn apply_env_overrides(&mut self) {
        Self::apply_string_override(&mut self.jacs_use_security, "JACS_USE_SECURITY");
        Self::apply_string_override(&mut self.jacs_data_directory, "JACS_DATA_DIRECTORY");
        Self::apply_string_override(&mut self.jacs_key_directory, "JACS_KEY_DIRECTORY");
        Self::apply_string_override(
            &mut self.jacs_agent_private_key_filename,
            "JACS_AGENT_PRIVATE_KEY_FILENAME",
        );
        Self::apply_string_override(
            &mut self.jacs_agent_public_key_filename,
            "JACS_AGENT_PUBLIC_KEY_FILENAME",
        );
        Self::apply_string_override(
            &mut self.jacs_agent_key_algorithm,
            "JACS_AGENT_KEY_ALGORITHM",
        );
        Self::apply_string_override(
            &mut self.jacs_agent_id_and_version,
            "JACS_AGENT_ID_AND_VERSION",
        );
        Self::apply_string_override(&mut self.jacs_default_storage, "JACS_DEFAULT_STORAGE");
        Self::apply_string_override(&mut self.jacs_agent_domain, "JACS_AGENT_DOMAIN");

        Self::apply_bool_override(&mut self.jacs_dns_validate, "JACS_DNS_VALIDATE");
        Self::apply_bool_override(&mut self.jacs_dns_strict, "JACS_DNS_STRICT");
        Self::apply_bool_override(&mut self.jacs_dns_required, "JACS_DNS_REQUIRED");

        Self::apply_string_override(&mut self.jacs_database_url, "JACS_DATABASE_URL");
        Self::apply_parsed_override(
            &mut self.jacs_database_max_connections,
            "JACS_DATABASE_MAX_CONNECTIONS",
        );
        Self::apply_parsed_override(
            &mut self.jacs_database_min_connections,
            "JACS_DATABASE_MIN_CONNECTIONS",
        );
        Self::apply_parsed_override(
            &mut self.jacs_database_connect_timeout_secs,
            "JACS_DATABASE_CONNECT_TIMEOUT_SECS",
        );

        // Note: Password is intentionally NOT loaded from env into config
        // It should be read directly from env when needed via get_env_var("JACS_PRIVATE_KEY_PASSWORD", true)
    }

    // publish_to_env() deleted: Agent now carries key_paths from config,
    // and FsEncryptedStore uses Agent.key_paths() instead of env reads.
    // See ENV_SECURITY_PRD Task 008.

    /// Create a Config with only hardcoded defaults (no env var lookups).
    /// This is useful for testing or when you want explicit control.
    pub fn with_defaults() -> Self {
        Config {
            schema: default_schema(),
            jacs_use_security: Some("false".to_string()),
            jacs_data_directory: Some("./jacs_data".to_string()),
            jacs_key_directory: Some("./jacs_keys".to_string()),
            jacs_agent_private_key_filename: None,
            jacs_agent_public_key_filename: None,
            jacs_agent_key_algorithm: Some("pq2025".to_string()),
            jacs_private_key_password: None,
            jacs_agent_id_and_version: None,
            jacs_default_storage: Some("fs".to_string()),
            jacs_agent_domain: None,
            jacs_dns_validate: None,
            jacs_dns_strict: None,
            jacs_dns_required: None,
            jacs_keychain_backend: None,
            observability: None,
            jacs_database_url: None,
            jacs_database_max_connections: None,
            jacs_database_min_connections: None,
            jacs_database_connect_timeout_secs: None,
            config_dir: None,
        }
    }

    /// Load config from a JSON file without applying environment overrides.
    ///
    /// This is the recommended way to load a config file. For 12-Factor compliance,
    /// call `config.apply_env_overrides()` after loading, then `Agent::from_config(config, password)`.
    pub fn from_file(path: &str) -> Result<Config, JacsError> {
        let json_str = fs::read_to_string(path).map_err(|e| {
            let help = match e.kind() {
                std::io::ErrorKind::NotFound => {
                    format!(
                        "Config file not found at '{}'. Create a jacs.config.json file or use \
                            environment variables (JACS_DATA_DIRECTORY, JACS_KEY_DIRECTORY, etc.) \
                            to configure JACS without a file.",
                        path
                    )
                }
                std::io::ErrorKind::PermissionDenied => {
                    format!(
                        "Permission denied reading config file '{}'. Check file permissions.",
                        path
                    )
                }
                _ => {
                    format!("Failed to read config file '{}': {}", path, e)
                }
            };
            JacsError::ConfigError(help)
        })?;
        let validated_value: Value = validate_config(&json_str)
            .map_err(|e| JacsError::ConfigError(format!("Invalid config at '{}': {}", path, e)))?;
        let mut config: Config = serde_json::from_value(validated_value.clone()).map_err(|e| {
            // This can happen if the JSON structure doesn't match our Config struct
            JacsError::ConfigError(format!(
                "Config structure error at '{}': {}. The JSON may have valid syntax but incorrect field types.",
                path, e
            ))
        })?;

        // Warn if password is in config file
        if config.jacs_private_key_password.is_some() {
            warn!(
                "SECURITY WARNING: Password found in config file '{}'. \
                This is insecure - passwords should only be set via JACS_PRIVATE_KEY_PASSWORD \
                environment variable. The password in the config file will be ignored.",
                path
            );
        }

        // Set config_dir to the parent directory of the config file path.
        // This allows load_by_config to resolve storage paths correctly
        // without requiring callers to pass the path or use env var side-channels.
        config.config_dir = std::path::Path::new(path)
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .map(std::path::PathBuf::from);

        Ok(config)
    }
}

impl fmt::Display for Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            r#"
        Loading JACS config variables of:
            JACS_USE_SECURITY:               {},
            JACS_DATA_DIRECTORY:             {},
            JACS_KEY_DIRECTORY:              {},
            JACS_AGENT_PRIVATE_KEY_FILENAME: {},
            JACS_AGENT_PUBLIC_KEY_FILENAME:  {},
            JACS_AGENT_KEY_ALGORITHM:        {},
            JACS_PRIVATE_KEY_PASSWORD:       REDACTED,
            JACS_AGENT_ID_AND_VERSION:       {},
            JACS_DEFAULT_STORAGE:            {},
            JACS_DATABASE_URL:               {},
        "#,
            self.jacs_use_security.as_deref().unwrap_or(""),
            self.jacs_data_directory.as_deref().unwrap_or(""),
            self.jacs_key_directory.as_deref().unwrap_or(""),
            self.jacs_agent_private_key_filename
                .as_deref()
                .unwrap_or(""),
            self.jacs_agent_public_key_filename.as_deref().unwrap_or(""),
            self.jacs_agent_key_algorithm.as_deref().unwrap_or(""),
            self.jacs_agent_id_and_version.as_deref().unwrap_or(""),
            self.jacs_default_storage.as_deref().unwrap_or(""),
            if self.jacs_database_url.is_some() {
                "REDACTED"
            } else {
                ""
            }
        )
    }
}

/// Load configuration following 12-Factor App principles.
///
/// Configuration is loaded in this order (later sources override earlier):
/// 1. Hardcoded defaults
/// 2. Config file (if provided and exists)
/// 3. Environment variables (always take highest precedence)
///
/// # Arguments
/// * `config_path` - Optional path to a JSON config file
///
/// # Example
/// ```rust,ignore
/// // Load with config file and env overrides
/// let config = load_config_12factor(Some("jacs.config.json"))?;
///
/// // Load with just defaults and env overrides
/// let config = load_config_12factor(None)?;
/// ```
#[deprecated(
    since = "0.9.8",
    note = "Use Config::from_file(path) + config.apply_env_overrides() + Agent::from_config(config, password) instead"
)]
pub fn load_config_12factor(config_path: Option<&str>) -> Result<Config, JacsError> {
    // Step 1: Start with hardcoded defaults
    let mut config = Config::with_defaults();

    // Step 2: If config file provided, merge those values
    if let Some(path) = config_path {
        match Config::from_file(path) {
            Ok(file_config) => {
                info!("Loaded config file: {}", path);
                config.merge(file_config);
            }
            Err(e) => {
                // File was specified but couldn't be loaded - this is an error
                return Err(e);
            }
        }
    }

    // Step 3: Environment variables override everything (12-Factor compliance)
    config.apply_env_overrides();

    info!("Final config (12-Factor):{}", config);
    Ok(config)
}

/// Load configuration from a config file only, **without** applying env/jenv overrides.
///
/// This is the isolation-safe counterpart of `load_config_12factor`: the caller
/// already constructed a pristine config file and does not want ambient JACS_*
/// environment variables to override it.  Used by standalone verification
/// (Issue 008) so that concurrent callers cannot interfere through shared
/// global jenv state.
///
/// # Arguments
/// * `config_path` - Path to a JSON config file (required, must exist)
#[deprecated(
    since = "0.9.8",
    note = "Use Config::from_file(path) directly. Skip apply_env_overrides() for file-only loading."
)]
pub fn load_config_file_only(config_path: &str) -> Result<Config, JacsError> {
    let mut config = Config::with_defaults();
    let file_config = Config::from_file(config_path)?;
    config.merge(file_config);
    // Deliberately skip apply_env_overrides() — the config file is authoritative.
    info!("Loaded config (file-only, no env overrides): {}", config);
    Ok(config)
}

/// Load configuration with 12-Factor compliance, with optional config file that may not exist.
///
/// Unlike `load_config_12factor`, this function does not fail if the config file doesn't exist.
/// It will log a warning and continue with defaults + env vars.
///
/// # Arguments
/// * `config_path` - Optional path to a JSON config file (won't fail if missing)
#[deprecated(
    since = "0.9.8",
    note = "Use Config::from_file(path) + config.apply_env_overrides() + Agent::from_config(config, password) instead"
)]
pub fn load_config_12factor_optional(config_path: Option<&str>) -> Result<Config, JacsError> {
    // Step 1: Start with hardcoded defaults
    let mut config = Config::with_defaults();

    // Step 2: If config file provided and exists, merge those values
    if let Some(path) = config_path {
        if std::path::Path::new(path).exists() {
            match Config::from_file(path) {
                Ok(file_config) => {
                    info!("Loaded config file: {}", path);
                    config.merge(file_config);
                }
                Err(e) => {
                    warn!(
                        "Failed to parse config file '{}': {}. Using defaults.",
                        path, e
                    );
                }
            }
        } else {
            info!(
                "Config file '{}' not found. Using defaults and environment variables.",
                path
            );
        }
    }

    // Step 3: Environment variables override everything (12-Factor compliance)
    config.apply_env_overrides();

    info!("Final config (12-Factor):{}", config);
    Ok(config)
}

/// DEPRECATED: Use `load_config_12factor` instead for 12-Factor compliant loading.
///
/// This function loads config from file only, without applying environment overrides.
/// It exists for backwards compatibility but does not follow 12-Factor principles.
#[deprecated(
    since = "0.2.0",
    note = "Use load_config_12factor() for 12-Factor compliant config loading"
)]
pub fn load_config(config_path: &str) -> Result<Config, JacsError> {
    Config::from_file(config_path)
}

/// Splits an ID string in "id:version" format into its components.
///
/// # Deprecated
///
/// Use [`crate::validation::split_agent_id`] instead for new code.
#[deprecated(
    since = "0.3.0",
    note = "Use crate::validation::split_agent_id instead"
)]
pub fn split_id(input: &str) -> Option<(&str, &str)> {
    split_agent_id(input)
}

/// Known config fields with their expected formats for helpful error messages
const CONFIG_FIELD_HELP: &[(&str, &str)] = &[
    (
        "jacs_agent_key_algorithm",
        "Expected one of: RSA-PSS, ring-Ed25519, pq2025",
    ),
    ("jacs_default_storage", "Expected one of: fs, aws"),
    (
        "jacs_use_security",
        "Expected 'true' or 'false' as a string",
    ),
    ("jacs_data_directory", "Expected a valid directory path"),
    ("jacs_key_directory", "Expected a valid directory path"),
    (
        "jacs_agent_private_key_filename",
        "Expected a filename (e.g., 'rsa_pss_private.pem')",
    ),
    (
        "jacs_agent_public_key_filename",
        "Expected a filename (e.g., 'rsa_pss_public.pem')",
    ),
    (
        "jacs_agent_id_and_version",
        "Expected format: UUID:UUID (e.g., '550e8400-e29b-41d4-a716-446655440000:550e8400-e29b-41d4-a716-446655440001')",
    ),
    (
        "jacs_agent_domain",
        "Expected a domain name (e.g., 'example.com')",
    ),
    ("jacs_dns_validate", "Expected a boolean (true/false)"),
    ("jacs_dns_strict", "Expected a boolean (true/false)"),
    ("jacs_dns_required", "Expected a boolean (true/false)"),
];

/// Get help text for a config field
fn get_field_help(field_name: &str) -> Option<&'static str> {
    CONFIG_FIELD_HELP
        .iter()
        .find(|(name, _)| field_name.contains(name))
        .map(|(_, help)| *help)
}

/// Format a schema validation error with actionable context
fn format_validation_error(error: &jsonschema::ValidationError, instance: &Value) -> String {
    let path = error.instance_path.to_string();
    let field_name = if path.is_empty() || path == "/" {
        "root".to_string()
    } else {
        path.trim_start_matches('/').to_string()
    };

    // Extract the actual invalid value from the instance using the path
    let invalid_value: Option<String> = if !path.is_empty() && path != "/" {
        // Try to get the value at the path from the instance
        let path_parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
        let mut current = instance;
        for part in &path_parts {
            if let Some(obj) = current.as_object() {
                if let Some(val) = obj.get(*part) {
                    current = val;
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        if current != instance {
            let s = current.to_string();
            if s.len() > 50 {
                Some(format!("{}...", &s[..47]))
            } else {
                Some(s)
            }
        } else {
            None
        }
    } else {
        None
    };

    // Build the error message
    let mut msg = format!("Config validation error at '{}': {}", field_name, error);

    // Add the invalid value if we have it
    if let Some(val) = invalid_value {
        msg.push_str(&format!(" (got: {})", val));
    }

    // Add helpful guidance for known fields
    if let Some(help) = get_field_help(&field_name) {
        msg.push_str(&format!(". {}", help));
    }

    // Special handling for missing required fields
    let error_str = error.to_string();
    if error_str.contains("required") {
        // List required fields for context
        msg.push_str(". Required fields: jacs_data_directory, jacs_key_directory, jacs_agent_private_key_filename, jacs_agent_public_key_filename, jacs_agent_key_algorithm, jacs_default_storage");
    }

    // Special handling for enum violations
    if error_str.contains("is not one of") {
        if field_name.contains("jacs_agent_key_algorithm") {
            msg.push_str(". Valid algorithms: RSA-PSS, ring-Ed25519, pq2025");
        } else if field_name.contains("jacs_default_storage") {
            msg.push_str(". Valid storage options: fs, aws");
        }
    }

    msg
}

pub fn validate_config(config_json: &str) -> Result<Value, JacsError> {
    let jacsconfigschema_result: Value = serde_json::from_str(CONFIG_SCHEMA_STRING)
        .map_err(|e| JacsError::ConfigError(format!("Failed to parse config schema: {}", e)))?;

    let jacsconfigschema = Validator::options()
        .with_draft(Draft::Draft7)
        .with_retriever(EmbeddedSchemaResolver::new())
        .build(&jacsconfigschema_result)
        .map_err(|e| JacsError::ConfigError(format!("Failed to compile config schema: {}", e)))?;

    let instance: Value = serde_json::from_str(config_json).map_err(|e| {
        // Provide detailed JSON parse error with line/column
        let category = match e.classify() {
            serde_json::error::Category::Io => "IO error",
            serde_json::error::Category::Syntax => "syntax error",
            serde_json::error::Category::Data => "data type error",
            serde_json::error::Category::Eof => "unexpected end of file",
        };
        let err_msg = format!(
            "Config JSON parse error at line {}, column {}: {} - {}. \
            Ensure the config file contains valid JSON syntax (check for missing commas, quotes, or brackets).",
            e.line(),
            e.column(),
            category,
            e
        );
        error!("{}", err_msg);
        JacsError::ConfigError(err_msg)
    })?;

    // Validate and provide detailed error messages
    if let Err(e) = jacsconfigschema.validate(&instance) {
        let err_msg = format_validation_error(&e, &instance);
        error!("{}", err_msg);
        return Err(JacsError::ConfigError(err_msg));
    }

    Ok(instance)
}

pub fn check_env_vars(ignore_agent_id: bool) -> Result<String, EnvError> {
    let vars = [
        ("JACS_USE_SECURITY", true),
        ("JACS_DATA_DIRECTORY", true),
        ("JACS_KEY_DIRECTORY", true),
        ("JACS_AGENT_PRIVATE_KEY_FILENAME", true),
        ("JACS_AGENT_PUBLIC_KEY_FILENAME", true),
        ("JACS_AGENT_KEY_ALGORITHM", true),
        ("JACS_PRIVATE_KEY_PASSWORD", true),
        ("JACS_AGENT_ID_AND_VERSION", true),
    ];

    let mut message = String::from("\nChecking JACS environment variables:\n");
    let mut missing_vars = Vec::new();

    for (var_name, required) in vars.iter() {
        if var_name == &"JACS_AGENT_ID_AND_VERSION" && ignore_agent_id {
            message.push_str(&format!(
                "    {:<35} {}\n",
                var_name.to_string() + ":",
                "SKIPPED (ignore_agent_id=true)"
            ));
            continue;
        }

        let value = get_env_var(var_name, *required)?;
        let status = match value {
            Some(val) => {
                if *var_name == "JACS_PRIVATE_KEY_PASSWORD" {
                    "REDACTED".to_string()
                } else {
                    val
                }
            }
            None => {
                if *required {
                    missing_vars.push(var_name);
                }
                "MISSING".to_string()
            }
        };
        message.push_str(&format!(
            "    {:<35} {}\n",
            var_name.to_string() + ":",
            status
        ));
    }

    if !missing_vars.is_empty() {
        message.push_str("\nMissing required environment variables:\n");
        for var in missing_vars {
            message.push_str(&format!("    {}\n", var));
        }
    }

    Ok(message)
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ObservabilityConfig {
    #[serde(default)]
    pub logs: LogConfig,
    #[serde(default)]
    pub metrics: MetricsConfig,
    #[serde(default)]
    pub tracing: Option<TracingConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default = "default_log_level")]
    pub level: String,
    #[serde(default = "default_log_destination")]
    pub destination: LogDestination,
    #[serde(default)]
    pub headers: Option<HashMap<String, String>>,
}

impl Default for LogConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            level: "info".to_string(),
            destination: LogDestination::Stderr,
            headers: None,
        }
    }
}

fn default_true() -> bool {
    true
}
fn default_log_level() -> String {
    "info".to_string()
}
fn default_log_destination() -> LogDestination {
    LogDestination::Stderr
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub destination: MetricsDestination,
    pub export_interval_seconds: Option<u64>,
    #[serde(default)]
    pub headers: Option<HashMap<String, String>>,
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            destination: MetricsDestination::Stdout,
            export_interval_seconds: None,
            headers: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracingConfig {
    pub enabled: bool,
    #[serde(default)]
    pub sampling: SamplingConfig,
    #[serde(default)]
    pub resource: Option<ResourceConfig>,
    #[serde(default)]
    pub destination: Option<TracingDestination>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SamplingConfig {
    #[serde(default = "default_sampling_ratio")]
    pub ratio: f64,
    #[serde(default)]
    pub parent_based: bool,
    #[serde(default)]
    pub rate_limit: Option<u32>, // samples per second
}

impl Default for SamplingConfig {
    fn default() -> Self {
        Self {
            ratio: 1.0, // Sample everything by default
            parent_based: true,
            rate_limit: None,
        }
    }
}

fn default_sampling_ratio() -> f64 {
    1.0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceConfig {
    pub service_name: String,
    pub service_version: Option<String>,
    pub environment: Option<String>,
    #[serde(default)]
    pub attributes: HashMap<String, String>,
}

// Update the destination enums to support headers
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum LogDestination {
    #[serde(rename = "stderr")]
    Stderr,
    #[serde(rename = "file")]
    File { path: String },
    #[serde(rename = "otlp")]
    Otlp {
        endpoint: String,
        #[serde(default)]
        headers: Option<HashMap<String, String>>,
    },
    #[serde(rename = "null")]
    Null,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub enum MetricsDestination {
    #[serde(rename = "otlp")]
    Otlp {
        endpoint: String,
        #[serde(default)]
        headers: Option<HashMap<String, String>>,
    },
    #[serde(rename = "prometheus")]
    Prometheus {
        endpoint: String,
        #[serde(default)]
        headers: Option<HashMap<String, String>>,
    },
    #[serde(rename = "file")]
    File { path: String },
    #[serde(rename = "stdout")]
    #[default]
    Stdout,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TracingDestination {
    #[serde(rename = "otlp")]
    Otlp {
        endpoint: String,
        #[serde(default)]
        headers: Option<HashMap<String, String>>,
    },
    #[serde(rename = "jaeger")]
    Jaeger {
        endpoint: String,
        #[serde(default)]
        headers: Option<HashMap<String, String>>,
    },
}

impl Default for TracingDestination {
    fn default() -> Self {
        TracingDestination::Otlp {
            endpoint: "http://localhost:4318".to_string(),
            headers: None,
        }
    }
}

#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
    use super::*;
    use crate::storage::jenv::{clear_env_var, set_env_var};
    use serial_test::serial;

    /// Helper to clear all JACS env vars for test isolation
    fn clear_jacs_env_vars() {
        let vars = [
            "JACS_USE_SECURITY",
            "JACS_DATA_DIRECTORY",
            "JACS_KEY_DIRECTORY",
            "JACS_AGENT_PRIVATE_KEY_FILENAME",
            "JACS_AGENT_PUBLIC_KEY_FILENAME",
            "JACS_AGENT_KEY_ALGORITHM",
            "JACS_PRIVATE_KEY_PASSWORD",
            "JACS_AGENT_ID_AND_VERSION",
            "JACS_DEFAULT_STORAGE",
            "JACS_AGENT_DOMAIN",
            "JACS_DNS_VALIDATE",
            "JACS_DNS_STRICT",
            "JACS_DNS_REQUIRED",
            "JACS_ALLOW_NETWORK",
            "JACS_ALLOW_DNS",
            "JACS_ALLOW_REMOTE_KEY_FETCH",
            "JACS_ALLOW_REGISTRY",
            "JACS_ALLOW_REMOTE_SCHEMA_FETCH",
            "JACS_ALLOW_JWKS_FETCH",
            "JACS_ALLOW_AGENT_CARD_FETCH",
        ];
        for var in vars {
            let _ = clear_env_var(var);
            unsafe {
                std::env::remove_var(var);
            }
        }
    }

    #[test]
    fn test_config_with_defaults() {
        // This test doesn't use env vars, so no serial needed
        let config = Config::with_defaults();
        assert_eq!(config.jacs_use_security, Some("false".to_string()));
        assert_eq!(config.jacs_data_directory, Some("./jacs_data".to_string()));
        assert_eq!(config.jacs_key_directory, Some("./jacs_keys".to_string()));
        assert_eq!(config.jacs_agent_key_algorithm, Some("pq2025".to_string()));
        assert_eq!(config.jacs_default_storage, Some("fs".to_string()));
        // Password should never be in config
        assert!(config.jacs_private_key_password.is_none());
    }

    #[test]
    fn test_config_merge() {
        // This test doesn't use env vars, so no serial needed
        let mut base = Config::with_defaults();
        let override_config = Config {
            schema: default_schema(),
            jacs_use_security: Some("true".to_string()),
            jacs_data_directory: Some("/custom/data".to_string()),
            jacs_key_directory: None, // Should not override
            jacs_agent_private_key_filename: Some("custom.pem".to_string()),
            jacs_agent_public_key_filename: None,
            jacs_agent_key_algorithm: Some("pq2025".to_string()),
            jacs_private_key_password: None,
            jacs_agent_id_and_version: None,
            jacs_default_storage: None, // Should not override
            jacs_agent_domain: Some("example.com".to_string()),
            jacs_dns_validate: Some(true),
            jacs_dns_strict: None,
            jacs_dns_required: None,
            jacs_keychain_backend: None,
            observability: None,
            jacs_database_url: None,
            jacs_database_max_connections: None,
            jacs_database_min_connections: None,
            jacs_database_connect_timeout_secs: None,
            config_dir: None,
        };

        base.merge(override_config);

        // Values that were Some should be overridden
        assert_eq!(base.jacs_use_security, Some("true".to_string()));
        assert_eq!(base.jacs_data_directory, Some("/custom/data".to_string()));
        assert_eq!(
            base.jacs_agent_private_key_filename,
            Some("custom.pem".to_string())
        );
        assert_eq!(base.jacs_agent_key_algorithm, Some("pq2025".to_string()));
        assert_eq!(base.jacs_agent_domain, Some("example.com".to_string()));
        assert_eq!(base.jacs_dns_validate, Some(true));

        // Values that were None should retain original
        assert_eq!(base.jacs_key_directory, Some("./jacs_keys".to_string()));
        assert_eq!(base.jacs_default_storage, Some("fs".to_string()));
    }

    #[test]
    #[serial(jacs_env)]
    fn test_apply_env_overrides() {
        clear_jacs_env_vars();

        // Set some env vars
        set_env_var("JACS_DATA_DIRECTORY", "/env/data").unwrap();
        set_env_var("JACS_AGENT_KEY_ALGORITHM", "Ed25519").unwrap();
        set_env_var("JACS_DNS_VALIDATE", "true").unwrap();
        set_env_var("JACS_DNS_STRICT", "1").unwrap();

        let mut config = Config::with_defaults();
        config.apply_env_overrides();

        // Env vars should override defaults
        assert_eq!(config.jacs_data_directory, Some("/env/data".to_string()));
        assert_eq!(config.jacs_agent_key_algorithm, Some("Ed25519".to_string()));
        assert_eq!(config.jacs_dns_validate, Some(true));
        assert_eq!(config.jacs_dns_strict, Some(true));

        // Values not in env should remain default
        assert_eq!(config.jacs_key_directory, Some("./jacs_keys".to_string()));
        assert_eq!(config.jacs_default_storage, Some("fs".to_string()));

        clear_jacs_env_vars();
    }

    #[test]
    #[serial(jacs_env)]
    fn test_env_overrides_config_file() {
        clear_jacs_env_vars();

        // Simulate: defaults -> config file -> env vars
        // Config file would set algorithm to pq2025
        // Env var should override to Ed25519

        let mut config = Config::with_defaults();

        // Simulate config file merge
        let file_config = Config {
            schema: default_schema(),
            jacs_use_security: None,
            jacs_data_directory: Some("/config/data".to_string()),
            jacs_key_directory: Some("/config/keys".to_string()),
            jacs_agent_private_key_filename: None,
            jacs_agent_public_key_filename: None,
            jacs_agent_key_algorithm: Some("pq2025".to_string()),
            jacs_private_key_password: None,
            jacs_agent_id_and_version: None,
            jacs_default_storage: None,
            jacs_agent_domain: None,
            jacs_dns_validate: None,
            jacs_dns_strict: None,
            jacs_dns_required: None,
            jacs_keychain_backend: None,
            observability: None,
            jacs_database_url: None,
            jacs_database_max_connections: None,
            jacs_database_min_connections: None,
            jacs_database_connect_timeout_secs: None,
            config_dir: None,
        };
        config.merge(file_config);

        // At this point, config has file values
        assert_eq!(config.jacs_data_directory, Some("/config/data".to_string()));
        assert_eq!(config.jacs_agent_key_algorithm, Some("pq2025".to_string()));

        // Now env vars override (12-Factor: env vars win)
        set_env_var("JACS_AGENT_KEY_ALGORITHM", "ring-Ed25519").unwrap();
        set_env_var("JACS_DATA_DIRECTORY", "/env/override/data").unwrap();

        config.apply_env_overrides();

        // Env vars should win (12-Factor compliance)
        assert_eq!(
            config.jacs_agent_key_algorithm,
            Some("ring-Ed25519".to_string())
        );
        assert_eq!(
            config.jacs_data_directory,
            Some("/env/override/data".to_string())
        );

        // Config file value not overridden by env should remain
        assert_eq!(config.jacs_key_directory, Some("/config/keys".to_string()));

        clear_jacs_env_vars();
    }

    #[test]
    #[serial(jacs_env)]
    fn test_load_config_12factor_no_file() {
        clear_jacs_env_vars();

        // Set env vars
        set_env_var("JACS_USE_SECURITY", "true").unwrap();
        set_env_var("JACS_DATA_DIRECTORY", "/production/data").unwrap();

        // Load without config file
        let config = load_config_12factor(None).expect("Should load successfully");

        // Should have defaults overridden by env vars
        assert_eq!(config.jacs_use_security, Some("true".to_string()));
        assert_eq!(
            config.jacs_data_directory,
            Some("/production/data".to_string())
        );
        // Non-overridden defaults
        assert_eq!(config.jacs_key_directory, Some("./jacs_keys".to_string()));

        clear_jacs_env_vars();
    }

    #[test]
    #[serial(jacs_env)]
    fn test_load_config_12factor_optional_missing_file() {
        clear_jacs_env_vars();

        // Set env vars
        set_env_var("JACS_AGENT_KEY_ALGORITHM", "pq2025").unwrap();

        // Load with non-existent config file - should NOT fail
        let config = load_config_12factor_optional(Some("/nonexistent/config.json"))
            .expect("Should load successfully even with missing file");

        // Should have defaults overridden by env vars
        assert_eq!(config.jacs_agent_key_algorithm, Some("pq2025".to_string()));
        assert_eq!(config.jacs_use_security, Some("false".to_string())); // default

        clear_jacs_env_vars();
    }

    #[test]
    #[serial(jacs_env)]
    fn test_boolean_env_var_parsing() {
        clear_jacs_env_vars();

        // Test various boolean representations
        let mut config = Config::with_defaults();

        set_env_var("JACS_DNS_VALIDATE", "true").unwrap();
        config.apply_env_overrides();
        assert_eq!(config.jacs_dns_validate, Some(true));

        set_env_var("JACS_DNS_VALIDATE", "TRUE").unwrap();
        config.apply_env_overrides();
        assert_eq!(config.jacs_dns_validate, Some(true));

        set_env_var("JACS_DNS_VALIDATE", "1").unwrap();
        config.apply_env_overrides();
        assert_eq!(config.jacs_dns_validate, Some(true));

        set_env_var("JACS_DNS_VALIDATE", "false").unwrap();
        config.apply_env_overrides();
        assert_eq!(config.jacs_dns_validate, Some(false));

        set_env_var("JACS_DNS_VALIDATE", "0").unwrap();
        config.apply_env_overrides();
        assert_eq!(config.jacs_dns_validate, Some(false));

        clear_jacs_env_vars();
    }

    #[test]
    #[serial(jacs_env)]
    fn test_apply_env_overrides_ignores_empty_string_values() {
        clear_jacs_env_vars();

        let mut config = Config::with_defaults();
        let original_data_dir = config.jacs_data_directory.clone();

        set_env_var("JACS_DATA_DIRECTORY", "").unwrap();
        config.apply_env_overrides();

        assert_eq!(config.jacs_data_directory, original_data_dir);

        clear_jacs_env_vars();
    }

    #[test]
    #[serial(jacs_env)]
    fn test_apply_env_overrides_ignores_invalid_database_numbers() {
        clear_jacs_env_vars();

        let mut config = Config::with_defaults();
        config.jacs_database_max_connections = Some(10);
        config.jacs_database_min_connections = Some(2);
        config.jacs_database_connect_timeout_secs = Some(30);

        set_env_var("JACS_DATABASE_MAX_CONNECTIONS", "not-a-number").unwrap();
        set_env_var("JACS_DATABASE_MIN_CONNECTIONS", "bad").unwrap();
        set_env_var("JACS_DATABASE_CONNECT_TIMEOUT_SECS", "oops").unwrap();
        config.apply_env_overrides();

        assert_eq!(config.jacs_database_max_connections, Some(10));
        assert_eq!(config.jacs_database_min_connections, Some(2));
        assert_eq!(config.jacs_database_connect_timeout_secs, Some(30));

        clear_jacs_env_vars();
    }

    #[test]
    #[serial(jacs_env)]
    fn test_apply_env_overrides_preserves_config_dir() {
        clear_jacs_env_vars();

        let mut config = Config::with_defaults();
        let test_dir = std::path::PathBuf::from("/some/config/dir");
        config.set_config_dir(Some(test_dir.clone()));

        // Set some env overrides to trigger actual work
        set_env_var("JACS_DATA_DIRECTORY", "/env/data").unwrap();

        config.apply_env_overrides();

        // config_dir must survive apply_env_overrides — it is runtime metadata
        // that Agent::from_config uses for storage_root calculation.
        // If this is wiped, storage resolves to CWD or "/" (Issue 024).
        assert_eq!(
            config.config_dir(),
            Some(test_dir.as_path()),
            "config_dir must be preserved through apply_env_overrides"
        );

        clear_jacs_env_vars();
    }

    #[test]
    fn test_config_builder_defaults() {
        // Builder with no options set should produce sensible defaults
        let config = Config::builder().build();

        assert_eq!(config.jacs_use_security, Some("false".to_string()));
        assert_eq!(config.jacs_data_directory, Some("./jacs_data".to_string()));
        assert_eq!(config.jacs_key_directory, Some("./jacs_keys".to_string()));
        assert_eq!(config.jacs_agent_key_algorithm, Some("pq2025".to_string()));
        assert_eq!(config.jacs_default_storage, Some("fs".to_string()));
        // Password should never be in config
        assert!(config.jacs_private_key_password.is_none());
        // Optional fields should be None
        assert!(config.jacs_agent_private_key_filename.is_none());
        assert!(config.jacs_agent_public_key_filename.is_none());
        assert!(config.jacs_agent_id_and_version.is_none());
        assert!(config.jacs_agent_domain.is_none());
    }

    #[test]
    fn test_config_builder_custom_values() {
        let config = Config::builder()
            .key_algorithm("Ed25519")
            .key_directory("/custom/keys")
            .data_directory("/custom/data")
            .default_storage("memory")
            .use_security(true)
            .private_key_filename("my_private.pem")
            .public_key_filename("my_public.pem")
            .agent_id_and_version(
                "550e8400-e29b-41d4-a716-446655440000:550e8400-e29b-41d4-a716-446655440001",
            )
            .agent_domain("example.com")
            .dns_validate(true)
            .dns_strict(false)
            .dns_required(true)
            .build();

        assert_eq!(config.jacs_agent_key_algorithm, Some("Ed25519".to_string()));
        assert_eq!(config.jacs_key_directory, Some("/custom/keys".to_string()));
        assert_eq!(config.jacs_data_directory, Some("/custom/data".to_string()));
        assert_eq!(config.jacs_default_storage, Some("memory".to_string()));
        assert_eq!(config.jacs_use_security, Some("true".to_string()));
        assert_eq!(
            config.jacs_agent_private_key_filename,
            Some("my_private.pem".to_string())
        );
        assert_eq!(
            config.jacs_agent_public_key_filename,
            Some("my_public.pem".to_string())
        );
        assert_eq!(
            config.jacs_agent_id_and_version,
            Some(
                "550e8400-e29b-41d4-a716-446655440000:550e8400-e29b-41d4-a716-446655440001"
                    .to_string()
            )
        );
        assert_eq!(config.jacs_agent_domain, Some("example.com".to_string()));
        assert_eq!(config.jacs_dns_validate, Some(true));
        assert_eq!(config.jacs_dns_strict, Some(false));
        assert_eq!(config.jacs_dns_required, Some(true));
    }

    #[test]
    fn test_config_builder_partial() {
        // Test that partial configuration works - only set some values
        let config = Config::builder()
            .key_algorithm("pq2025")
            .use_security(true)
            .build();

        // Explicitly set values
        assert_eq!(config.jacs_agent_key_algorithm, Some("pq2025".to_string()));
        assert_eq!(config.jacs_use_security, Some("true".to_string()));

        // Default values for unset fields
        assert_eq!(config.jacs_data_directory, Some("./jacs_data".to_string()));
        assert_eq!(config.jacs_key_directory, Some("./jacs_keys".to_string()));
        assert_eq!(config.jacs_default_storage, Some("fs".to_string()));
    }

    #[test]
    fn test_config_builder_method_chaining() {
        // Ensure method chaining works correctly
        let builder = ConfigBuilder::new()
            .key_algorithm("Ed25519")
            .key_directory("/keys")
            .data_directory("/data");

        let config = builder.build();

        assert_eq!(config.jacs_agent_key_algorithm, Some("Ed25519".to_string()));
        assert_eq!(config.jacs_key_directory, Some("/keys".to_string()));
        assert_eq!(config.jacs_data_directory, Some("/data".to_string()));
    }

    #[test]
    fn test_config_builder_vs_with_defaults() {
        // Builder defaults should match with_defaults() for the core fields
        let builder_config = Config::builder().build();
        let defaults_config = Config::with_defaults();

        // Core fields should have same default values
        assert_eq!(
            builder_config.jacs_use_security,
            defaults_config.jacs_use_security
        );
        assert_eq!(
            builder_config.jacs_agent_key_algorithm,
            defaults_config.jacs_agent_key_algorithm
        );
        assert_eq!(
            builder_config.jacs_default_storage,
            defaults_config.jacs_default_storage
        );
        // Note: data_directory and key_directory may differ due to CWD resolution
        // in with_defaults(), but builder uses static defaults
    }

    #[test]
    fn test_validate_config_invalid_json_error_message() {
        // Test that JSON parse errors include line/column info
        let invalid_json = r#"{
  "jacs_data_directory": "/data",
  "jacs_key_directory": "/keys"
  "jacs_agent_key_algorithm": "RSA-PSS"
}"#;
        let result = validate_config(invalid_json);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        // Should include line number, column, and helpful message
        assert!(
            err.contains("line"),
            "Error should include line number: {}",
            err
        );
        assert!(
            err.contains("column"),
            "Error should include column: {}",
            err
        );
        assert!(
            err.contains("syntax"),
            "Error should mention syntax issue: {}",
            err
        );
        assert!(err.contains("JSON"), "Error should mention JSON: {}", err);
    }

    #[test]
    fn test_validate_config_invalid_algorithm_error_message() {
        // Test that invalid enum values show valid options
        let invalid_algo = r#"{
  "jacs_data_directory": "/data",
  "jacs_key_directory": "/keys",
  "jacs_agent_private_key_filename": "private.pem",
  "jacs_agent_public_key_filename": "public.pem",
  "jacs_agent_key_algorithm": "INVALID_ALGO",
  "jacs_default_storage": "fs"
}"#;
        let result = validate_config(invalid_algo);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        // Should mention the field name and valid options
        assert!(
            err.contains("jacs_agent_key_algorithm"),
            "Error should mention field name: {}",
            err
        );
        assert!(
            err.contains("RSA-PSS") || err.contains("Valid algorithms"),
            "Error should mention valid algorithms: {}",
            err
        );
    }

    #[test]
    fn test_validate_config_missing_required_field_error_message() {
        // Test that missing required fields are clearly indicated
        let missing_field = r#"{
  "jacs_data_directory": "/data"
}"#;
        let result = validate_config(missing_field);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        // Should mention required fields
        assert!(
            err.contains("required") || err.contains("Required"),
            "Error should mention required fields: {}",
            err
        );
    }

    #[test]
    fn test_validate_config_invalid_storage_error_message() {
        // Test that invalid storage values show valid options
        let invalid_storage = r#"{
  "jacs_data_directory": "/data",
  "jacs_key_directory": "/keys",
  "jacs_agent_private_key_filename": "private.pem",
  "jacs_agent_public_key_filename": "public.pem",
  "jacs_agent_key_algorithm": "RSA-PSS",
  "jacs_default_storage": "invalid_storage"
}"#;
        let result = validate_config(invalid_storage);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        // Should mention the field name
        assert!(
            err.contains("jacs_default_storage"),
            "Error should mention field name: {}",
            err
        );
        assert!(
            err.contains("fs") || err.contains("Valid storage"),
            "Error should mention valid storage options: {}",
            err
        );
    }

    #[test]
    fn test_config_from_file_not_found_error_message() {
        // Test that file not found errors are actionable
        let result = Config::from_file("/nonexistent/path/jacs.config.json");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        // Should include path and guidance
        assert!(
            err.contains("nonexistent"),
            "Error should include path: {}",
            err
        );
        assert!(
            err.contains("environment") || err.contains("not found"),
            "Error should provide guidance: {}",
            err
        );
    }

    #[test]
    fn test_get_field_help() {
        // Test the field help function returns appropriate guidance
        assert!(
            get_field_help("jacs_agent_key_algorithm")
                .unwrap()
                .contains("RSA-PSS")
        );
        assert!(
            get_field_help("jacs_default_storage")
                .unwrap()
                .contains("fs")
        );
        assert!(
            get_field_help("jacs_data_directory")
                .unwrap()
                .contains("path")
        );
        assert!(
            get_field_help("jacs_agent_id_and_version")
                .unwrap()
                .contains("UUID")
        );
        assert!(get_field_help("unknown_field").is_none());
    }

    // =========================================================================
    // Key Resolution Order Tests
    // =========================================================================

    #[test]
    fn test_key_resolution_source_from_str() {
        assert_eq!(
            KeyResolutionSource::from_str("local").unwrap(),
            KeyResolutionSource::Local
        );
        assert_eq!(
            KeyResolutionSource::from_str("LOCAL").unwrap(),
            KeyResolutionSource::Local
        );
        assert_eq!(
            KeyResolutionSource::from_str("Local").unwrap(),
            KeyResolutionSource::Local
        );
        assert_eq!(
            KeyResolutionSource::from_str("dns").unwrap(),
            KeyResolutionSource::Dns
        );
        assert_eq!(
            KeyResolutionSource::from_str("DNS").unwrap(),
            KeyResolutionSource::Dns
        );
        assert_eq!(
            KeyResolutionSource::from_str("registry").unwrap(),
            KeyResolutionSource::Registry
        );
        assert_eq!(
            KeyResolutionSource::from_str("REGISTRY").unwrap(),
            KeyResolutionSource::Registry
        );
        assert_eq!(
            KeyResolutionSource::from_str(" registry ").unwrap(),
            KeyResolutionSource::Registry
        );
        // "hai" is no longer a valid key resolution source (removed in architecture upgrade)
        assert!(
            KeyResolutionSource::from_str("hai").is_err(),
            "\"hai\" should be rejected as a key resolution source"
        );
        assert!(
            KeyResolutionSource::from_str("HAI").is_err(),
            "\"HAI\" should be rejected as a key resolution source"
        );

        // Invalid sources
        assert!(KeyResolutionSource::from_str("invalid").is_err());
        assert!(KeyResolutionSource::from_str("").is_err());
    }

    #[test]
    fn test_key_resolution_source_display() {
        assert_eq!(format!("{}", KeyResolutionSource::Local), "local");
        assert_eq!(format!("{}", KeyResolutionSource::Dns), "dns");
        assert_eq!(format!("{}", KeyResolutionSource::Registry), "registry");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_default() {
        clear_jacs_env_vars();
        let _ = clear_env_var("JACS_KEY_RESOLUTION");

        let order = get_key_resolution_order();
        assert_eq!(
            order,
            vec![KeyResolutionSource::Local, KeyResolutionSource::Registry]
        );
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_local_only() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", "local").unwrap();

        let order = get_key_resolution_order();
        assert_eq!(order, vec![KeyResolutionSource::Local]);

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_registry_only() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", "registry").unwrap();

        let order = get_key_resolution_order();
        assert_eq!(order, vec![KeyResolutionSource::Registry]);

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_hai_is_rejected() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", "hai").unwrap();

        // "hai" should be silently skipped (invalid source), resulting in empty order
        // which falls back to default
        let order = get_key_resolution_order();
        // Since "hai" is no longer valid, it should be skipped and order should be empty
        // (the get_key_resolution_order function logs a warning and skips invalid sources)
        assert!(
            !order.iter().any(|s| format!("{}", s) == "hai"),
            "\"hai\" should not appear in key resolution order"
        );

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_with_dns() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", "local,dns,registry").unwrap();

        let order = get_key_resolution_order();
        assert_eq!(
            order,
            vec![
                KeyResolutionSource::Local,
                KeyResolutionSource::Dns,
                KeyResolutionSource::Registry,
            ]
        );

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_case_insensitive() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", "LOCAL,DNS,REGISTRY").unwrap();

        let order = get_key_resolution_order();
        assert_eq!(
            order,
            vec![
                KeyResolutionSource::Local,
                KeyResolutionSource::Dns,
                KeyResolutionSource::Registry,
            ]
        );

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_skips_invalid() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", "local,invalid,registry").unwrap();

        let order = get_key_resolution_order();
        // Should skip "invalid" but include valid sources
        assert_eq!(
            order,
            vec![KeyResolutionSource::Local, KeyResolutionSource::Registry]
        );

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_all_invalid_falls_back() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", "invalid,also_invalid").unwrap();

        let order = get_key_resolution_order();
        // Should fall back to default when all sources are invalid
        assert_eq!(
            order,
            vec![KeyResolutionSource::Local, KeyResolutionSource::Registry]
        );

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_empty_string_falls_back() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", "").unwrap();

        let order = get_key_resolution_order();
        // Should fall back to default for empty string
        assert_eq!(
            order,
            vec![KeyResolutionSource::Local, KeyResolutionSource::Registry]
        );

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_get_key_resolution_order_whitespace_handling() {
        clear_jacs_env_vars();
        set_env_var("JACS_KEY_RESOLUTION", " local , registry ").unwrap();

        let order = get_key_resolution_order();
        assert_eq!(
            order,
            vec![KeyResolutionSource::Local, KeyResolutionSource::Registry]
        );

        let _ = clear_env_var("JACS_KEY_RESOLUTION");
    }

    #[test]
    fn test_network_capability_from_str() {
        assert_eq!(
            NetworkCapability::from_str("dns").unwrap(),
            NetworkCapability::DnsLookup
        );
        assert_eq!(
            NetworkCapability::from_str("public_key_fetch").unwrap(),
            NetworkCapability::RemoteKeyFetch
        );
        assert_eq!(
            NetworkCapability::from_str("registry").unwrap(),
            NetworkCapability::RegistryLookup
        );
        assert_eq!(
            NetworkCapability::from_str("schema_fetch").unwrap(),
            NetworkCapability::RemoteSchemaFetch
        );
        assert_eq!(
            NetworkCapability::from_str("jwks").unwrap(),
            NetworkCapability::JwksFetch
        );
        assert_eq!(
            NetworkCapability::from_str("agent_card_fetch").unwrap(),
            NetworkCapability::AgentCardFetch
        );
        assert!(NetworkCapability::from_str("unknown").is_err());
    }

    #[test]
    #[serial(jacs_env)]
    fn test_network_access_defaults_to_disabled() {
        clear_jacs_env_vars();

        assert!(!is_network_access_allowed(NetworkCapability::DnsLookup));
        let err = ensure_network_access(NetworkCapability::DnsLookup).unwrap_err();
        assert!(err.to_string().contains("JACS_ALLOW_DNS"));
    }

    #[test]
    #[serial(jacs_env)]
    fn test_network_access_capability_override() {
        clear_jacs_env_vars();
        set_env_var("JACS_ALLOW_JWKS_FETCH", "true").unwrap();

        assert!(is_network_access_allowed(NetworkCapability::JwksFetch));
        assert!(ensure_network_access(NetworkCapability::JwksFetch).is_ok());
        assert!(!is_network_access_allowed(
            NetworkCapability::RemoteKeyFetch
        ));

        let _ = clear_env_var("JACS_ALLOW_JWKS_FETCH");
    }

    #[test]
    #[serial(jacs_env)]
    fn test_network_access_global_override() {
        clear_jacs_env_vars();
        set_env_var("JACS_ALLOW_NETWORK", "true").unwrap();

        assert!(is_network_access_allowed(NetworkCapability::DnsLookup));
        assert!(is_network_access_allowed(
            NetworkCapability::RemoteSchemaFetch
        ));
        assert!(ensure_network_access(NetworkCapability::AgentCardFetch).is_ok());

        let _ = clear_env_var("JACS_ALLOW_NETWORK");
    }
}