materials_for_mc 0.2.0

Material builder for Monte Carlo simulations
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
// Struct representing a nuclide, matching the JSON file structure
// Update the fields as needed to match all JSON entries
use crate::reaction::Reaction;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::sync::{Arc, Mutex};

// Global cache for nuclides to avoid reloading
static GLOBAL_NUCLIDE_CACHE: Lazy<Mutex<HashMap<String, Arc<Nuclide>>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Enum to represent either an MT number or reaction name for flexible reaction identification
#[derive(Debug, Clone)]
pub enum ReactionIdentifier {
    Mt(i32),
    Name(String),
}

impl From<i32> for ReactionIdentifier {
    fn from(mt: i32) -> Self {
        ReactionIdentifier::Mt(mt)
    }
}

impl From<String> for ReactionIdentifier {
    fn from(name: String) -> Self {
        ReactionIdentifier::Name(name)
    }
}

impl From<&str> for ReactionIdentifier {
    fn from(name: &str) -> Self {
        ReactionIdentifier::Name(name.to_string())
    }
}

/// Clear the global nuclide cache (used by tests and Python to ensure deterministic selective temperature behavior)
#[allow(dead_code)]
pub fn clear_nuclide_cache() {
    match GLOBAL_NUCLIDE_CACHE.lock() {
        Ok(mut cache) => cache.clear(),
        Err(poisoned) => {
            // Handle poisoned mutex by clearing the data anyway
            let mut cache = poisoned.into_inner();
            cache.clear();
        }
    }
}

/// Core data model for a single nuclide and its reaction cross section data.
///
/// A `Nuclide` mirrors (and is deserialized from) a JSON schema containing
/// metadata plus reaction channel data at one or more temperatures. Reaction
/// data are organized by temperature key (e.g. "294") and then by ENDF/MT
/// number. Each [`Reaction`] holds its own threshold information and (possibly
/// truncated) energy grid relative to the top‑level temperature energy grid.
///
/// Temperatures:
/// * `available_temperatures` always lists every temperature present in the
///   source JSON file – even if a filtered load only materialized a subset.
/// * `loaded_temperatures` tracks the subset actually parsed into `reactions`
///   and `energy` according to caller filtering semantics.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Nuclide {
    /// Canonical nuclide name (e.g. "Li6"). May be derived when absent.
    pub name: Option<String>,
    /// Optional human readable element name (legacy field; may be absent).
    pub element: Option<String>,
    /// Element symbol, e.g. "Li".
    pub atomic_symbol: Option<String>,
    /// Atomic (proton) number Z.
    pub atomic_number: Option<u32>,
    /// Neutron number N (may be computed from A - Z if missing).
    pub neutron_number: Option<u32>,
    /// Mass number A.
    pub mass_number: Option<u32>,
    /// Origin / library identifier (e.g. JEFF, ENDF, custom tag).
    pub library: Option<String>,
    /// Top‑level energy grid per temperature (full grid; per‑reaction grids may be threshold‑truncated).
    pub energy: Option<HashMap<String, Vec<f64>>>,
    /// temperature -> MT number -> reaction data.
    #[serde(default)]
    pub reactions: HashMap<String, HashMap<i32, Reaction>>, // temperature -> mt (i32) -> Reaction
    /// True if any fission MT channel is present.
    pub fissionable: bool,
    /// All temperatures present in the JSON file regardless of filtering.
    #[serde(skip, default)]
    pub available_temperatures: Vec<String>, // All temps listed in the JSON (even if not loaded)
    /// Subset of temperatures actually loaded into `reactions` / `energy`.
    #[serde(skip, default)]
    pub loaded_temperatures: Vec<String>, // Subset actually loaded into reactions/energy
    /// Optional path the JSON was read from (None for in‑memory sources / WASM).
    #[serde(skip, default)]
    pub data_path: Option<String>, // Path JSON was loaded from (for potential future extension)
}

impl Nuclide {
    /// Sample the top-level reaction type (fission, absorption, elastic, inelastic, other) at a given energy and temperature
    pub fn sample_reaction<R: rand::Rng + ?Sized>(
        &self,
        energy: f64,
        temperature: &str,
        rng: &mut R,
    ) -> Option<&Reaction> {
        // Try temperature as given, then with 'K' appended, then any available
        let temp_reactions = if let Some(r) = self.reactions.get(temperature) {
            r
        } else if let Some(r) = self.reactions.get(&format!("{}K", temperature)) {
            r
        } else if let Some((temp, r)) = self.reactions.iter().next() {
            println!("[sample_reaction] Requested temperature '{}' not found. Using available temperature '{}'.", temperature, temp);
            r
        } else {
            println!("[sample_reaction] No reaction data available for any temperature.");
            return None;
        };

        // Define MTs for each event type
        let total_mt = 1;
        let fission_mt = 18;
        let absorption_mt = 101;
        let elastic_mt = 2;
        let nonelastic_mt = 3;

        // Helper to get xs for a given MT using Reaction::cross_section_at
        let get_xs = |mt: i32| -> f64 {
            temp_reactions
                .get(&mt)
                .and_then(|reaction| reaction.cross_section_at(energy))
                .unwrap_or(0.0)
        };

        let total_xs = get_xs(total_mt);
        if total_xs <= 0.0 {
            return None;
        }

        let xi = rng.gen_range(0.0..total_xs);
        let mut accum = 0.0;

        // Absorption

        let xs_absorption = get_xs(absorption_mt);
        accum += xs_absorption;
        if xi < accum && xs_absorption > 0.0 {
            return temp_reactions.get(&absorption_mt);
        }

        // Elastic
        let xs_elastic = get_xs(elastic_mt);
        accum += xs_elastic;
        if xi < accum && xs_elastic > 0.0 {
            return temp_reactions.get(&elastic_mt);
        }

        // Fission (only if nuclide is fissionable, checked last)
        let xs_fission = if self.fissionable {
            get_xs(fission_mt)
        } else {
            0.0
        };
        accum += xs_fission;
        if xi < accum && xs_fission > 0.0 {
            return temp_reactions.get(&fission_mt);
        }

        // Non-elastic selection as fallback
        temp_reactions.get(&nonelastic_mt)
    }
    /// Get the energy grid for a specific temperature
    pub fn energy_grid(&self, temperature: &str) -> Option<&Vec<f64>> {
        self.energy
            .as_ref()
            .and_then(|energy_map| energy_map.get(temperature))
    }

    /// Get a list of available temperatures
    pub fn temperatures(&self) -> Option<Vec<String>> {
        let mut temps = std::collections::HashSet::new();

        // Check reactions first
        for temp in self.reactions.keys() {
            temps.insert(temp.clone());
        }

        // Also check energy map
        if let Some(energy_map) = &self.energy {
            for temp in energy_map.keys() {
                temps.insert(temp.clone());
            }
        }

        if temps.is_empty() {
            None
        } else {
            let mut temps_vec: Vec<String> = temps.into_iter().collect();
            temps_vec.sort();
            Some(temps_vec)
        }
    }

    /// Get a list of available MT numbers
    pub fn reaction_mts(&self) -> Option<Vec<i32>> {
        let mut mts = std::collections::HashSet::new();
        for temp_reactions in self.reactions.values() {
            for &mt in temp_reactions.keys() {
                mts.insert(mt);
            }
        }
        if mts.is_empty() {
            None
        } else {
            let mut mts_vec: Vec<i32> = mts.into_iter().collect();
            mts_vec.sort();
            Some(mts_vec)
        }
    }

    /// Get microscopic cross section data for a specific reaction and temperature.
    /// Returns a tuple of (cross_section_values, energy_grid).
    /// If temperature is None, uses the single loaded temperature if only one exists.
    /// Automatically loads data if not already loaded, using the nuclide name and config.
    /// 
    /// # Arguments
    /// * `reaction` - Either an MT number (i32) or reaction name (String/&str) like "(n,gamma)" or "fission"
    /// * `temperature` - Optional temperature string
    pub fn microscopic_cross_section<R>(
        &mut self,
        reaction: R,
        temperature: Option<&str>,
    ) -> Result<(Vec<f64>, Vec<f64>), Box<dyn std::error::Error>> 
    where
        R: Into<ReactionIdentifier>,
    {
        // Convert the reaction parameter to an MT number
        let mt = match reaction.into() {
            ReactionIdentifier::Mt(mt_num) => mt_num,
            ReactionIdentifier::Name(name) => {
                // Use the REACTION_MT mapping to convert string to MT number
                crate::data::REACTION_MT.get(name.as_str())
                    .copied()
                    .ok_or_else(|| format!("Unknown reaction name '{}'. Available reactions can be found in REACTION_MT mapping.", name))?
            }
        };
        // Check if we need to load data automatically
        if self.loaded_temperatures.is_empty() {
            // No data loaded yet - try to load it automatically
            if let Some(name) = self.name.clone() {
                self.auto_load_from_config(&name, temperature)?;
            } else {
                return Err("No data loaded and no nuclide name available for automatic loading".into());
            }
        }

        // Check if we need to load additional temperature
        if let Some(temp) = temperature {
            let temp_normalized = format!("{}K", temp);
            let temp_without_k = if temp.ends_with('K') { &temp[..temp.len()-1] } else { temp };
            
            // Check if the requested temperature is available but not loaded
            let needs_temp_load = !self.loaded_temperatures.contains(&temp.to_string()) 
                && !self.loaded_temperatures.contains(&temp_normalized)
                && !self.loaded_temperatures.contains(&temp_without_k.to_string())
                && (self.available_temperatures.contains(&temp.to_string()) 
                    || self.available_temperatures.contains(&temp_normalized)
                    || self.available_temperatures.contains(&temp_without_k.to_string()));
            
            if needs_temp_load {
                if let Some(name) = self.name.clone() {
                    self.auto_load_additional_temperature(&name, temp)?;
                }
            }
        }

        // Now proceed with the original logic
        self.get_microscopic_cross_section_data(mt, temperature)
    }

    /// Helper method to automatically load data from config
    fn auto_load_from_config(&mut self, nuclide_name: &str, temperature: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
        // Try to load using the nuclide name and config
        let path_or_url = {
            let cfg = crate::config::CONFIG.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
            cfg.get_cross_section(nuclide_name)
        };
        
        if let Some(path_or_url) = path_or_url {
            // Determine which temperatures to load
            let temps_to_load = if let Some(temp) = temperature {
                let mut temps = std::collections::HashSet::new();
                temps.insert(temp.to_string());
                Some(temps)
            } else {
                None // Load all temperatures
            };
            
            // Load the data
            let loaded_nuclide = if crate::url_cache::is_keyword(&path_or_url) {
                load_nuclide_for_python(Some(&path_or_url), Some(nuclide_name), temps_to_load.as_ref())?
            } else {
                load_nuclide_for_python(Some(&path_or_url), None, temps_to_load.as_ref())?
            };
            
            // Update self with the loaded data
            *self = loaded_nuclide;
            Ok(())
        } else {
            Err(format!("No configuration found for nuclide '{}'. Use Config.set_cross_sections() to configure data sources.", nuclide_name).into())
        }
    }

    /// Helper method to load additional temperature
    fn auto_load_additional_temperature(&mut self, nuclide_name: &str, temperature: &str) -> Result<(), Box<dyn std::error::Error>> {
        let path_or_url = {
            let cfg = crate::config::CONFIG.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
            cfg.get_cross_section(nuclide_name)
        };
        
        if let Some(path_or_url) = path_or_url {
            // Create union of current loaded temperatures plus the new one
            let mut temps_to_load = std::collections::HashSet::new();
            for temp in &self.loaded_temperatures {
                temps_to_load.insert(temp.clone());
            }
            temps_to_load.insert(temperature.to_string());
            
            // Reload with the expanded temperature set
            let loaded_nuclide = if crate::url_cache::is_keyword(&path_or_url) {
                load_nuclide_for_python(Some(&path_or_url), Some(nuclide_name), Some(&temps_to_load))?
            } else {
                load_nuclide_for_python(Some(&path_or_url), None, Some(&temps_to_load))?
            };
            
            // Update self with the reloaded data
            *self = loaded_nuclide;
            Ok(())
        } else {
            Err(format!("No configuration found for nuclide '{}' to load additional temperature", nuclide_name).into())
        }
    }

    /// Core method that extracts the cross section data (unchanged logic)
    fn get_microscopic_cross_section_data(
        &self,
        mt: i32,
        temperature: Option<&str>,
    ) -> Result<(Vec<f64>, Vec<f64>), Box<dyn std::error::Error>> {
        // Determine which temperature to use
        let temp_key = if let Some(temp) = temperature {
            // Try the provided temperature as-is, then with 'K' suffix
            if self.reactions.contains_key(temp) {
                temp
            } else if self.reactions.contains_key(&format!("{}K", temp)) {
                &format!("{}K", temp)
            } else {
                return Err(format!(
                    "Temperature '{}' not found in loaded data. Available temperatures: [{}]", 
                    temp, 
                    self.loaded_temperatures.join(", ")
                ).into());
            }
        } else {
            // No temperature provided - use single loaded temperature if available
            if self.loaded_temperatures.len() == 1 {
                &self.loaded_temperatures[0]
            } else if self.loaded_temperatures.is_empty() {
                return Err("No temperatures loaded in nuclide data".into());
            } else {
                return Err(format!(
                    "Multiple temperatures loaded [{}], must specify which one to use",
                    self.loaded_temperatures.join(", ")
                ).into());
            }
        };

        // Get the reaction data for this temperature and MT
        let temp_reactions = self.reactions.get(temp_key)
            .ok_or_else(|| format!(
                "Temperature '{}' not found in reactions. Available temperatures: [{}]", 
                temp_key, 
                self.loaded_temperatures.join(", ")
            ))?;
        
        let reaction = temp_reactions.get(&mt)
            .ok_or_else(|| {
                // Get available MTs for this temperature
                let available_mts: Vec<String> = temp_reactions.keys()
                    .map(|mt| mt.to_string())
                    .collect();
                format!(
                    "MT {} not found for temperature '{}'. Available MTs: [{}]", 
                    mt, 
                    temp_key, 
                    available_mts.join(", ")
                )
            })?;

        // Return the cross section and energy data
        if reaction.cross_section.is_empty() {
            return Err(format!("No cross section data available for MT {} at temperature '{}'", mt, temp_key).into());
        }

        if reaction.energy.is_empty() {
            return Err(format!("No energy grid available for MT {} at temperature '{}'", mt, temp_key).into());
        }

        Ok((reaction.cross_section.clone(), reaction.energy.clone()))
    }
}

// Internal: parse a nuclide from a JSON value with optional temperature filter.
// If `temps_filter` is Some, only those temperatures will have reaction/energy data
// materialized into the returned struct. `available_temperatures` will always list
// the full set present in the file for deterministic behavior.
fn parse_nuclide_from_json_value(
    json_value: serde_json::Value,
    temps_filter: Option<&std::collections::HashSet<String>>,
) -> Result<Nuclide, Box<dyn std::error::Error>> {
    let mut nuclide = Nuclide {
        name: None,
        element: None,
        atomic_symbol: None,
        atomic_number: None,
        neutron_number: None,
        mass_number: None,
        library: None,
        energy: None,
        reactions: HashMap::new(),
        fissionable: false,
        available_temperatures: Vec::new(),
        loaded_temperatures: Vec::new(),
        data_path: None,
    };

    // Parse basic metadata
    if let Some(name) = json_value.get("name").and_then(|v| v.as_str()) {
        nuclide.name = Some(name.to_string());
    }

    if let Some(element) = json_value.get("element").and_then(|v| v.as_str()) {
        nuclide.element = Some(element.to_string());
    }

    if let Some(symbol) = json_value.get("atomic_symbol").and_then(|v| v.as_str()) {
        nuclide.atomic_symbol = Some(symbol.to_string());
        // For backward compatibility, set element to "lithium" if atomic_symbol is "Li"
        if symbol == "Li" && nuclide.element.is_none() {
            nuclide.element = Some("lithium".to_string());
        }
    }

    if let Some(num) = json_value.get("atomic_number").and_then(|v| v.as_u64()) {
        nuclide.atomic_number = Some(num as u32);
    }

    if let Some(num) = json_value.get("mass_number").and_then(|v| v.as_u64()) {
        nuclide.mass_number = Some(num as u32);
    }

    if let Some(num) = json_value.get("neutron_number").and_then(|v| v.as_u64()) {
        nuclide.neutron_number = Some(num as u32);
    } else if nuclide.mass_number.is_some() && nuclide.atomic_number.is_some() {
        // Calculate neutron_number = mass_number - atomic_number
        nuclide.neutron_number =
            Some(nuclide.mass_number.unwrap() - nuclide.atomic_number.unwrap());
    }

    if let Some(lib) = json_value.get("library").and_then(|v| v.as_str()) {
        nuclide.library = Some(lib.to_string());
    }

    // First, collect ALL available temperatures from multiple locations in the JSON
    let mut all_temperatures = std::collections::HashSet::new();

    // IMPORTANT: We currently do not support Doppler broadening and therefore ignore
    // all temperature "0" (0 Kelvin) data present in JSON files. At absolute zero,
    // nuclear cross sections would require special handling that we don't implement.
    // This filtering occurs throughout the temperature processing below.

    // Step 1: Check the dedicated "temperatures" array (this is the source of truth)
    // The "temperatures" array in the JSON is the authoritative source of all available temperatures
    if let Some(temps_array) = json_value.get("temperatures").and_then(|v| v.as_array()) {
        for temp_value in temps_array {
            if let Some(temp_str) = temp_value.as_str() {
                // Filter out 0K temperature data - we don't currently support Doppler broadening
                if temp_str != "0" {
                    all_temperatures.insert(temp_str.to_string());
                }
            }
        }
    }

    // Step 2: Also check the reactions object for temperatures
    if let Some(reactions_obj) = json_value.get("reactions").and_then(|v| v.as_object()) {
        for temp in reactions_obj.keys() {
            // Filter out 0K temperature data - we don't currently support Doppler broadening
            if temp != "0" {
                all_temperatures.insert(temp.clone());
            }
        }
    }

    // Step 3: Also check energy object for temperatures
    if let Some(energy_obj) = json_value.get("energy").and_then(|v| v.as_object()) {
        for temp in energy_obj.keys() {
            // Filter out 0K temperature data - we don't currently support Doppler broadening
            if temp != "0" {
                all_temperatures.insert(temp.clone());
            }
        }
    }

    // Store all available temperatures (regardless of filtering)
    let mut available_temps: Vec<String> = all_temperatures.iter().cloned().collect();
    available_temps.sort();
    nuclide.available_temperatures = available_temps;

    // Check if we have the format with "reactions" field
    if let Some(reactions_obj) = json_value.get("reactions").and_then(|v| v.as_object()) {
        for (temp, mt_reactions) in reactions_obj {
            // Filter out 0K temperature data - we don't currently support Doppler broadening
            if temp == "0" {
                continue;
            }

            // Skip temperatures not in the filter if a filter is provided and non-empty
            if let Some(filter) = temps_filter {
                if !filter.is_empty() && !filter.contains(temp) {
                    continue;
                }
            }

            let mut temp_reactions: HashMap<i32, Reaction> = HashMap::new();

            // Process all MT reactions for this temperature
            if let Some(mt_obj) = mt_reactions.as_object() {
                for (mt, reaction_data) in mt_obj {
                    if let Some(reaction_obj) = reaction_data.as_object() {
                        let mut reaction = Reaction {
                            cross_section: Vec::new(),
                            threshold_idx: 0,
                            interpolation: Vec::new(),
                            energy: Vec::new(),
                            mt_number: 0,
                        };

                        // Get cross section (might be named "xs" in old format)
                        if let Some(xs) = reaction_obj
                            .get("cross_section")
                            .or_else(|| reaction_obj.get("xs"))
                        {
                            if let Some(xs_arr) = xs.as_array() {
                                reaction.cross_section =
                                    xs_arr.iter().filter_map(|v| v.as_f64()).collect();
                            }
                        }

                        // Get threshold_idx
                        if let Some(idx) =
                            reaction_obj.get("threshold_idx").and_then(|v| v.as_u64())
                        {
                            reaction.threshold_idx = idx as usize;
                        }

                        // Get interpolation
                        if let Some(interp) = reaction_obj.get("interpolation") {
                            if let Some(interp_arr) = interp.as_array() {
                                reaction.interpolation = interp_arr
                                    .iter()
                                    .filter_map(|v| v.as_i64().map(|i| i as i32))
                                    .collect();
                            }
                        }

                        // Get energy (some reactions may have their own energy grid)
                        if let Some(energy) = reaction_obj.get("energy") {
                            if let Some(energy_arr) = energy.as_array() {
                                reaction.energy =
                                    energy_arr.iter().filter_map(|v| v.as_f64()).collect();
                            }
                        }

                        // Calculate energy grid from threshold_idx and main energy grid if not already set
                        if reaction.energy.is_empty() {
                            if let Some(energy_grids) = &nuclide.energy {
                                if let Some(energy_grid) = energy_grids.get(temp) {
                                    if reaction.threshold_idx < energy_grid.len() {
                                        reaction.energy =
                                            energy_grid[reaction.threshold_idx..].to_vec();
                                    }
                                }
                            }
                        }

                        if let Ok(mt_int) = mt.parse::<i32>() {
                            reaction.mt_number = mt_int;
                            temp_reactions.insert(mt_int, reaction);
                        }
                    }
                }
            }

            // Only insert if we found reactions
            if !temp_reactions.is_empty() {
                nuclide.reactions.insert(temp.clone(), temp_reactions);
            }
        }
    }

    // Process energy (after reactions so we know which temps to keep)
    if let Some(energy_obj) = json_value.get("energy").and_then(|v| v.as_object()) {
        let mut energy_map = HashMap::new();

        for (temp, energy_arr) in energy_obj {
            // Filter out 0K temperature data - we don't currently support Doppler broadening
            if temp == "0" {
                continue;
            }

            // Skip temperatures not in the filter if a filter is provided and non-empty
            if let Some(filter) = temps_filter {
                if !filter.is_empty() && !filter.contains(temp) {
                    continue;
                }
            }

            if let Some(energy_values) = energy_arr.as_array() {
                let energy_vec: Vec<f64> =
                    energy_values.iter().filter_map(|v| v.as_f64()).collect();
                energy_map.insert(temp.clone(), energy_vec);
            }
        }
        if !energy_map.is_empty() {
            nuclide.energy = Some(energy_map);
        }
    }

    // Validate temperature sets: if both reactions and energy present, they must match exactly.
    if let Some(energy_map) = &nuclide.energy {
        use std::collections::HashSet;
        let reaction_temps: HashSet<String> = nuclide.reactions.keys().cloned().collect();
        let energy_temps: HashSet<String> = energy_map.keys().cloned().collect();

        if reaction_temps.is_empty() && !energy_temps.is_empty() {
            return Err(format!(
                "Energy grid has temperatures {:?} but no reactions were loaded.",
                energy_temps
            )
            .into());
        }
        if !reaction_temps.is_empty() && energy_temps.is_empty() {
            return Err(format!(
                "Reactions have temperatures {:?} but no energy grids were loaded.",
                reaction_temps
            )
            .into());
        }

        if reaction_temps != energy_temps {
            let only_in_reactions: Vec<String> =
                reaction_temps.difference(&energy_temps).cloned().collect();
            let only_in_energy: Vec<String> =
                energy_temps.difference(&reaction_temps).cloned().collect();
            return Err(format!(
                "Mismatched temperature sets. Only in reactions: {:?}. Only in energy: {:?}.",
                only_in_reactions, only_in_energy
            )
            .into());
        }

        // Don't override available_temperatures here - it should preserve all temps from JSON
        // available_temperatures was already set earlier from the full JSON parsing
    } else if !nuclide.reactions.is_empty() {
        // Reactions present but no energy map created (legacy / missing). Treat as error per requirement.
        let temps: Vec<String> = nuclide.reactions.keys().cloned().collect();
        return Err(format!(
            "Reactions contain temperatures {:?} but no top-level energy map present.",
            temps
        )
        .into());
    } else {
        nuclide.available_temperatures.clear();
    }

    // If we have no energy map but have reactions, try to create an energy map
    if nuclide.energy.is_none() && !nuclide.reactions.is_empty() {
        let mut energy_grids = HashMap::new();

        for (temp, temp_reactions) in &nuclide.reactions {
            if let Some((_, reaction)) = temp_reactions.iter().next() {
                if !reaction.energy.is_empty() {
                    energy_grids.insert(temp.clone(), reaction.energy.clone());
                }
            }
        }

        if !energy_grids.is_empty() {
            nuclide.energy = Some(energy_grids);
        }
    }

    // At this point we should have both reactions and (possibly) an energy map.
    // Populate per-reaction energy grids if they are still empty so that
    // cross_section_at() works correctly for sampling.
    if let Some(energy_map) = &nuclide.energy {
        for (temp, temp_reactions) in nuclide.reactions.iter_mut() {
            if let Some(energy_grid) = energy_map.get(temp) {
                for reaction in temp_reactions.values_mut() {
                    if reaction.energy.is_empty() {
                        if reaction.threshold_idx < energy_grid.len() {
                            reaction.energy = energy_grid[reaction.threshold_idx..].to_vec();
                        }
                    }
                }
            }
        }
    }

    // Fallback: derive name if still None (e.g., from atomic_symbol + mass_number)
    if nuclide.name.is_none() {
        if let (Some(symbol), Some(mass)) = (&nuclide.atomic_symbol, nuclide.mass_number) {
            nuclide.name = Some(format!("{}{}", symbol, mass));
        }
    }

    // Determine fissionable status now that reactions are loaded
    let fission_mt_list = [18, 19, 20, 21, 38];
    if nuclide
        .reactions
        .values()
        .any(|temp_reactions| temp_reactions.keys().any(|mt| fission_mt_list.contains(mt)))
    {
        nuclide.fissionable = true;
    }

    // Set loaded_temperatures based on what was actually loaded
    let mut loaded_temps: Vec<String> = nuclide.reactions.keys().cloned().collect();
    loaded_temps.sort();
    nuclide.loaded_temperatures = loaded_temps;

    Ok(nuclide)
}

// Read a single nuclide either from an explicit JSON file path, or if the input is not a file path,
// treat the argument as a nuclide name and look up the path in the global CONFIG.cross_sections map.

/// Read a single nuclide either from an explicit JSON file path, or if the input is not a file path,
/// treat the argument as a nuclide name and look up the path in the global CONFIG.cross_sections map.
/// Optional temperature filtering is supported. URLs are automatically downloaded and cached.
pub fn read_nuclide_from_json<P: AsRef<Path>>(
    path_or_name: P,
    temps: Option<&std::collections::HashSet<String>>,
) -> Result<Nuclide, Box<dyn std::error::Error>> {
    // If path_or_name is a keyword, set config mapping for this nuclide
    let candidate_ref = path_or_name.as_ref();
    let candidate_str = candidate_ref.to_string_lossy();
    if crate::url_cache::is_keyword(&candidate_str) {
        let mut cfg = crate::config::CONFIG.lock().unwrap();
        cfg.set_cross_section(candidate_str.as_ref(), Some(&candidate_str));
    }
    read_nuclide_from_json_with_name(path_or_name, temps, None)
}

/// Read a single nuclide with an optional nuclide name hint for URL caching
pub fn read_nuclide_from_json_with_name<P: AsRef<Path>>(
    path_or_name: P,
    temps: Option<&std::collections::HashSet<String>>,
    nuclide_name_hint: Option<&str>,
) -> Result<Nuclide, Box<dyn std::error::Error>> {
    // Load the JSON file
    let candidate_ref = path_or_name.as_ref();
    let candidate_str = candidate_ref.to_string_lossy();
    
    let resolved_path = if candidate_ref.exists() {
        // Direct file path exists
        candidate_ref.to_path_buf()
    } else if crate::url_cache::is_url(&candidate_str) {
        // It's a URL, download and cache it
        if let Some(name) = nuclide_name_hint {
            crate::url_cache::resolve_path_or_url(&candidate_str, name)?
        } else {
            return Err("Direct URL loading without nuclide name not yet supported. Use config approach instead.".into());
        }
    } else if crate::url_cache::is_keyword(&candidate_str) {
        // It's a keyword: treat as data source for the nuclide name
        let nuclide_name = nuclide_name_hint.unwrap_or(candidate_str.as_ref());
        crate::url_cache::resolve_path_or_url(&candidate_str, nuclide_name)?
    } else {
        // Treat as nuclide name, look up in config
        let cfg = crate::config::CONFIG.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        let path_or_url = cfg
            .cross_sections
            .get(candidate_str.as_ref())
            .ok_or_else(|| {
                format!(
                    "Input '{}' is neither an existing file nor a key in Config cross_sections",
                    candidate_str
                )
            })?;
        // The config value might be a URL or local path
        crate::url_cache::resolve_path_or_url(path_or_url, candidate_str.as_ref())?
    };

    let file = File::open(&resolved_path)?;
    let reader = BufReader::new(file);
    let json_value: serde_json::Value = serde_json::from_reader(reader)?;

    // Use the filtering version of parse_nuclide_from_json_value
    let mut nuclide = parse_nuclide_from_json_value(json_value, temps)?;
    nuclide.data_path = Some(resolved_path.to_string_lossy().to_string());

    Ok(nuclide)
}

// Read a nuclide from a JSON string, used by WASM
pub fn read_nuclide_from_json_str(
    json_content: &str,
) -> Result<Nuclide, Box<dyn std::error::Error>> {
    // Parse the JSON string
    let json_value: serde_json::Value = serde_json::from_str(json_content)?;

    // Use the shared parsing function
    let mut nuclide = parse_nuclide_from_json_value(json_value, None)?;
    // No file path available
    nuclide.data_path = None;
    Ok(nuclide)
}

/// Read (or fetch from cache) a nuclide, optionally keeping only a specified subset of temperatures.
/// Records the full `available_temperatures` and tracks the actually retained subset in `loaded_temperatures`.
///
/// This function ensures that:
/// 1. All temperatures present in the JSON file are recorded in `available_temperatures` regardless of filtering
/// 2. Only the temperatures that pass the filter are loaded into `loaded_temperatures` and the actual data structures
///
/// Unified loader semantics:
/// - `temperatures_to_include`: `None` or `Some(empty)` => load all temperatures.
/// - `Some(nonempty)` => ensure those temperatures are loaded; if previously loaded with fewer temps, reload & prune to the union.
///
/// Implementation note: This function performs two passes on the JSON data when filtering:
/// - First pass with no filter to determine all available temperatures
/// - Second pass with the filter to load only the requested temperatures
pub fn get_or_load_nuclide(
    nuclide_name: &str,
    json_path_map: &HashMap<String, String>,
    temperatures_to_include: Option<&std::collections::HashSet<String>>,
) -> Result<Arc<Nuclide>, Box<dyn std::error::Error>> {
    use std::collections::HashSet;
    let requested: HashSet<String> = temperatures_to_include
        .map(|s| s.iter().cloned().collect())
        .unwrap_or_else(HashSet::new);

    // Determine data source for cache key
    let mut path_or_url = json_path_map.get(nuclide_name).cloned();
    if path_or_url.is_none() && crate::url_cache::is_keyword(nuclide_name) {
        let mut cfg = crate::config::CONFIG.lock().unwrap();
        cfg.set_cross_section(nuclide_name, Some(nuclide_name));
        path_or_url = Some(nuclide_name.to_string());
    }
    let path_or_url = path_or_url.ok_or_else(|| {
        format!(
            "No JSON file provided for nuclide '{}'. Please supply a path for all nuclides.",
            nuclide_name
        )
    })?;
    
    // Resolve URL/keyword to actual path first to create consistent cache keys
    let resolved_path = crate::url_cache::resolve_path_or_url(&path_or_url, nuclide_name)?;
    
    // Create cache key using the resolved path for consistency
    // This ensures "tendl-21" and the actual downloaded path use the same cache entry
    let normalized_source = match std::fs::canonicalize(&resolved_path) {
        Ok(canonical) => canonical.to_string_lossy().to_string(),
        Err(_) => {
            // If canonicalization fails, use the resolved path as-is
            resolved_path.to_string_lossy().to_string()
        }
    };
    let cache_key = format!("{}@{}", nuclide_name, normalized_source);

    // Fast path: cache hit with sufficient temps
    {
        let cache = match GLOBAL_NUCLIDE_CACHE.lock() {
            Ok(cache) => cache,
            Err(poisoned) => poisoned.into_inner()
        };
        if let Some(existing) = cache.get(&cache_key) {
            if requested.is_empty()
                || requested.is_subset(&existing.loaded_temperatures.iter().cloned().collect())
            {
                return Ok(Arc::clone(existing));
            }
        }
    }
    // Determine union (existing loaded + requested)
    let mut union_set = requested.clone();
    {
        let cache = match GLOBAL_NUCLIDE_CACHE.lock() {
            Ok(cache) => cache,
            Err(poisoned) => poisoned.into_inner()
        };
        if let Some(existing) = cache.get(&cache_key) {
            for t in &existing.loaded_temperatures {
                union_set.insert(t.clone());
            }
        }
    }
    // Load directly with temperature filtering
    // (resolved_path already determined above for cache key)

    // Load the JSON file once
    let file = File::open(&resolved_path)?;
    let reader = BufReader::new(file);
    let json_value: serde_json::Value = serde_json::from_reader(reader)?;

    // Parse with temperature filter if needed
    let filter_option = if union_set.is_empty() {
        None
    } else {
        Some(&union_set)
    };

    // First, do a parse with no filtering to get all available temperatures
    let all_temps_nuclide = parse_nuclide_from_json_value(json_value.clone(), None)?;

    // Now parse with the filter to get the loaded data
    let mut nuclide = parse_nuclide_from_json_value(json_value, filter_option)?;
    nuclide.data_path = Some(resolved_path.to_string_lossy().to_string());

    // Copy the available_temperatures from the unfiltered parse
    nuclide.available_temperatures = all_temps_nuclide.available_temperatures;

    // Print loading info
    let name_disp = nuclide.name.as_deref().unwrap_or(nuclide_name);
    println!(
        "Reading {} from {}, available temperatures: {}, loaded temperatures: {}",
        name_disp,
        resolved_path.to_string_lossy(),
        nuclide.available_temperatures.len(),
        nuclide.loaded_temperatures.len()
    );
    let arc = Arc::new(nuclide);
    {
        let mut cache = match GLOBAL_NUCLIDE_CACHE.lock() {
            Ok(cache) => cache,
            Err(poisoned) => poisoned.into_inner()
        };
        cache.insert(cache_key, Arc::clone(&arc));
    }
    Ok(arc)
}

/// Load a nuclide with Python wrapper semantics - handles both path and name parameters
/// and preserves available_temperatures when filtering. This method consolidates the logic
/// previously scattered in the Python wrapper.
#[allow(dead_code)]
pub fn load_nuclide_for_python(
    path_or_keyword: Option<&str>,
    nuclide_name: Option<&str>,
    temperatures: Option<&std::collections::HashSet<String>>,
) -> Result<Nuclide, Box<dyn std::error::Error>> {
    // Determine the identifier - path takes precedence, then name
    let identifier = if let Some(p) = path_or_keyword {
        p
    } else if let Some(n) = nuclide_name {
        n
    } else {
        return Err("Either path or nuclide name must be provided".into());
    };

    // Check if identifier is a keyword and set up config if needed
    if crate::url_cache::is_keyword(identifier) {
        let mut cfg = crate::config::CONFIG.lock().unwrap();
        cfg.set_cross_section(identifier, Some(identifier));
    }

    // Load without temperature filtering first to get all available temperatures
    let full_nuclide = if path_or_keyword.is_some() && nuclide_name.is_some() {
        // We have both path and name - use the version with name hint
        read_nuclide_from_json_with_name(identifier, None, nuclide_name)?
    } else {
        read_nuclide_from_json(identifier, None)?
    };

    // Now load with temperature filtering if specified
    let mut filtered_nuclide = if temperatures.is_some() {
        if path_or_keyword.is_some() && nuclide_name.is_some() {
            read_nuclide_from_json_with_name(identifier, temperatures, nuclide_name)?
        } else {
            read_nuclide_from_json(identifier, temperatures)?
        }
    } else {
        full_nuclide.clone()
    };

    // Always preserve the full available_temperatures from the unfiltered load
    filtered_nuclide.available_temperatures = full_nuclide.available_temperatures;
    
    Ok(filtered_nuclide)
}

/// Load a nuclide from a path or keyword for the standalone Python function
/// This handles keyword detection and resolution automatically
#[allow(dead_code)]
pub fn load_nuclide_from_path_or_keyword(
    path_or_keyword: &str,
) -> Result<Nuclide, Box<dyn std::error::Error>> {
    // Check if it's a keyword and set up config if needed
    if crate::url_cache::is_keyword(path_or_keyword) {
        let mut cfg = crate::config::CONFIG.lock().unwrap();
        cfg.set_cross_section(path_or_keyword, Some(path_or_keyword));
    }
    
    // Load the nuclide with all temperatures
    read_nuclide_from_json(path_or_keyword, None)
}

mod tests {
    #[test]
    fn test_get_or_load_nuclide_uses_cache() {
        use std::collections::HashMap;
        let li6_path = std::path::Path::new("tests/Li6.json");
        assert!(li6_path.exists(), "tests/Li6.json missing");
        // Only remove Li6 from cache, don't clear all (avoid race with other tests)
        {
            let mut cache = match super::GLOBAL_NUCLIDE_CACHE.lock() {
                Ok(cache) => cache,
                Err(poisoned) => poisoned.into_inner()
            };
            // Remove any Li6 entries (handle both normalized and non-normalized paths)
            let keys_to_remove: Vec<String> = cache.keys()
                .filter(|k| k.starts_with("Li6@") && k.contains("Li6.json"))
                .cloned()
                .collect();
            for key in keys_to_remove {
                cache.remove(&key);
            }
        }
        let raw = super::read_nuclide_from_json(li6_path, None).expect("Direct read failed");
        assert_eq!(raw.name.as_deref(), Some("Li6"));
        // Don't assert cache state here (other tests may be using it)
        let mut json_map = HashMap::new();
        json_map.insert("Li6".to_string(), "tests/Li6.json".to_string());
        let first =
            super::get_or_load_nuclide("Li6", &json_map, None).expect("Initial cached load failed");
        // Ensure Li6 now present in cache with the correct cache key
        {
            let cache = match super::GLOBAL_NUCLIDE_CACHE.lock() {
                Ok(cache) => cache,
                Err(poisoned) => poisoned.into_inner()
            };
            
            // Check for Li6 cache key (path may be normalized)
            let found = cache.keys().any(|k| k.starts_with("Li6@") && k.contains("Li6.json"));
            assert!(found, "Li6 should be present after cached load");
        }
        let second =
            super::get_or_load_nuclide("Li6", &json_map, None).expect("Second cached load failed");
        assert!(
            std::sync::Arc::ptr_eq(&first, &second),
            "Expected identical Arc pointer from cache on second load"
        );
        assert_eq!(
            first.name.as_deref(),
            raw.name.as_deref(),
            "Names differ between raw and cached"
        );
    }

    #[cfg(test)]
    #[test]
    fn test_sample_reaction_li6() {
        use rand::rngs::StdRng;
        use rand::SeedableRng;
        let path = std::path::Path::new("tests/Li6.json");
        let nuclide = super::read_nuclide_from_json(path, None).expect("Failed to load Li6.json");
        let temperature = "294";

        // Vary energy from 1.0 to 15e6 (10 steps)
        let energies = (0..10).map(|i| 1.0 + i as f64 * (15e6 - 1e6) / 9.0);

        for energy in energies {
            let mut rng1 = StdRng::seed_from_u64(42);
            let mut rng2 = StdRng::seed_from_u64(42);
            let mut rng3 = StdRng::seed_from_u64(43); // Different seed

            let reaction1 = nuclide.sample_reaction(energy, temperature, &mut rng1);
            let reaction2 = nuclide.sample_reaction(energy, temperature, &mut rng2);
            let reaction3 = nuclide.sample_reaction(energy, temperature, &mut rng3);

            // Ensure reactions were sampled successfully
            assert!(
                reaction1.is_some(),
                "sample_reaction returned None at energy {}",
                energy
            );
            assert!(
                reaction2.is_some(),
                "Repeat sample with same seed returned None at energy {}",
                energy
            );
            assert!(
                reaction3.is_some(),
                "Sample with different seed returned None at energy {}",
                energy
            );

            let reaction1 = reaction1.unwrap();
            let reaction2 = reaction2.unwrap();
            let reaction3 = reaction3.unwrap();

            // Ensure same-seed reactions are the same (determinism)
            assert_eq!(
                reaction1.mt_number, reaction2.mt_number,
                "Different MT for same seed at energy {}",
                energy
            );
            assert_eq!(
                reaction1.cross_section, reaction2.cross_section,
                "Different cross_section for same seed at energy {}",
                energy
            );

            // Print info about the third reaction (with different seed)
            println!(
                "Energy: {:e}, MT (seed 42): {}, MT (seed 43): {}",
                energy, reaction1.mt_number, reaction3.mt_number
            );

            // Ensure basic validity
            assert!(
                reaction1.mt_number > 0,
                "Sampled reaction has invalid MT number at energy {}",
                energy
            );
            assert!(
                !reaction1.cross_section.is_empty(),
                "Sampled reaction has empty cross section at energy {}",
                energy
            );
        }
    }

    #[test]
    fn test_reaction_mts_li6() {
        // Load Li6 nuclide from test JSON
        let path = std::path::Path::new("tests/Li6.json");
        let nuclide = super::read_nuclide_from_json(path, None).expect("Failed to load Li6.json");
        let mts = nuclide.reaction_mts().expect("No MTs found");
        let expected = vec![
            102, 103, 105, 2, 203, 204, 205, 207, 24, 301, 444, 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,
        ];
        for mt in &expected {
            assert!(mts.contains(mt), "Expected MT {} in Li6", mt);
        }
        // Optionally, check the total number of MTs if you want strictness
        // assert_eq!(mts.len(), expected.len());
    }

    #[test]
    fn test_reaction_mts_li7() {
        // Load Li7 nuclide from test JSON
        let path = std::path::Path::new("tests/Li7.json");
        let nuclide = super::read_nuclide_from_json(path, None).expect("Failed to load Li7.json");
        let mts = nuclide.reaction_mts().expect("No MTs found");
        // Check for presence of key hierarchical and explicit MTs
        assert!(mts.contains(&1), "MT=1 should be present");
        assert!(mts.contains(&3), "MT=3 should be present");
        assert!(mts.contains(&4), "MT=4 should be present");
        assert!(mts.contains(&27), "MT=27 should be present");
        assert!(mts.contains(&101), "MT=101 should be present");
        assert!(mts.contains(&2), "MT=2 should be present");
        assert!(mts.contains(&16), "MT=16 should be present");
        assert!(mts.contains(&24), "MT=24 should be present");
        assert!(mts.contains(&51), "MT=51 should be present");
        assert!(!mts.is_empty(), "MT list should not be empty");
    }

    #[test]
    fn test_fissionable_false_for_be9_and_fe58() {
        let nuclide_be9 =
            super::read_nuclide_from_json("tests/Be9.json", None).expect("Failed to load Be9.json");
        assert_eq!(
            nuclide_be9.fissionable, false,
            "Be9 should not be fissionable"
        );

        let path_fe58 = std::path::Path::new("tests/Fe58.json");
        let nuclide_fe58 =
            super::read_nuclide_from_json(path_fe58, None).expect("Failed to load Fe58.json");
        assert_eq!(
            nuclide_fe58.fissionable, false,
            "Fe58 should not be fissionable"
        );
    }

    #[test]
    fn test_li6_reactions_contain_specific_mts() {
        // Load Li6 nuclide from test JSON
        let path = std::path::Path::new("tests/Li6.json");
        let nuclide = super::read_nuclide_from_json(path, None).expect("Failed to load Li6.json");

        // Check that required MTs are present and mt_number is not 0
        let required = [2, 24, 51, 444];
        for mt in &required {
            let mut found = false;
            for temp_reactions in nuclide.reactions.values() {
                if let Some(reaction) = temp_reactions.get(mt) {
                    assert_ne!(
                        reaction.mt_number, 0,
                        "Reaction MT number for MT {} is 0",
                        mt
                    );
                    found = true;
                    break;
                }
            }
            assert!(found, "MT {} not found in any temperature reactions", mt);
        }
    }

    #[test]
    fn test_available_temperatures_be9() {
        let path_be9 = std::path::Path::new("tests/Be9.json");
        let nuclide_be9 =
            super::read_nuclide_from_json(path_be9, None).expect("Failed to load Be9.json");
        assert_eq!(
            nuclide_be9.available_temperatures,
            vec!["294".to_string(), "300".to_string()],
            "available_temperatures should be ['294','300']"
        );
        assert_eq!(
            nuclide_be9.loaded_temperatures,
            vec!["294".to_string(), "300".to_string()],
            "By default all temps are loaded"
        );
        let temps_method = nuclide_be9
            .temperatures()
            .expect("temperatures() returned None");
        assert_eq!(
            temps_method,
            vec!["294".to_string(), "300".to_string()],
            "temperatures() should return ['294','300']"
        );
    }

    #[test]
    fn test_be9_mt_numbers_per_temperature() {
        let path_be9 = std::path::Path::new("tests/Be9.json");
        let nuclide_be9 =
            super::read_nuclide_from_json(path_be9, None).expect("Failed to load Be9.json");

        // Expected full MT list at 294 K (extended set including higher MTs)
        let mut expected_294: Vec<i32> = vec![
            1, 2, 3, 16, 27, 101, 102, 103, 104, 105, 107, 203, 204, 205, 207, 301, 444, 875, 876,
            877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890,
        ];
        expected_294.sort();

        // Expected reduced MT list at 300 K
        let mut expected_300: Vec<i32> = vec![
            1, 2, 3, 16, 27, 101, 102, 103, 104, 105, 107, 203, 204, 205, 207, 301,
        ];
        expected_300.sort();

        // Helper closure to extract and sort MT list for a temperature
        let get_sorted_mts = |temp: &str| -> Vec<i32> {
            let mut mts: Vec<i32> = nuclide_be9
                .reactions
                .get(temp)
                .expect("Temperature not found in reactions")
                .keys()
                .cloned()
                .collect();
            mts.sort();
            mts
        };

        let mts_294 = get_sorted_mts("294");
        let mts_300 = get_sorted_mts("300");

        assert_eq!(
            mts_294, expected_294,
            "Be9 294K MT list mismatch. Got {:?}",
            mts_294
        );
        assert_eq!(
            mts_300, expected_300,
            "Be9 300K MT list mismatch. Got {:?}",
            mts_300
        );

        // Ensure there are no overlapping unexpected MTs unique to 300 K
        for mt in &mts_300 {
            assert!(
                expected_294.contains(mt),
                "MT {} at 300K not present in 294K expected list (unexpected new MT)",
                mt
            );
        }
    }

    #[test]
    fn test_available_temperatures_fe56_includes_294() {
        let nuclide_fe56 = super::read_nuclide_from_json("tests/Fe56.json", None)
            .expect("Failed to load Fe56.json");
        assert!(
            nuclide_fe56
                .available_temperatures
                .iter()
                .any(|t| t == "294"),
            "Fe56 available_temperatures should contain '294'"
        );
        let temps_method = nuclide_fe56
            .temperatures()
            .expect("temperatures() returned None");
        assert!(
            temps_method.iter().any(|t| t == "294"),
            "Fe56 temperatures() should contain '294'"
        );
    }

    #[test]
    fn test_clear_nuclide_cache() {
        // Insert a test nuclide into the cache
        let li6_path = std::path::Path::new("tests/Li6.json");
        let nuclide =
            super::read_nuclide_from_json(li6_path, None).expect("Failed to load Li6.json");
        let nuclide_arc = std::sync::Arc::new(nuclide);

        {
            let mut cache = match super::GLOBAL_NUCLIDE_CACHE.lock() {
                Ok(cache) => cache,
                Err(poisoned) => poisoned.into_inner()
            };
            cache.insert(
                "Test_Nuclide".to_string(),
                std::sync::Arc::clone(&nuclide_arc),
            );

            // Verify it's in the cache
            assert!(
                cache.contains_key("Test_Nuclide"),
                "Test nuclide should be in cache before clearing"
            );
        }

        // Call the clear function
        super::clear_nuclide_cache();

        // Verify cache is now empty
        let cache = match super::GLOBAL_NUCLIDE_CACHE.lock() {
            Ok(cache) => cache,
            Err(poisoned) => poisoned.into_inner()
        };
        assert!(
            cache.is_empty(),
            "Cache should be empty after calling clear_nuclide_cache"
        );
    }

    #[test]
    #[cfg(feature = "download")]
    fn test_nuclide_from_url_energy_grid_positive() {
        // Clear the config to start fresh
        {
            let mut cfg = crate::config::CONFIG.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
            cfg.cross_sections.clear();
        }

        // Add Li6 using keyword to config
        {
            let mut cfg = crate::config::CONFIG.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
            cfg.set_cross_section("Li6", Some("tendl-21"));
        }

        // Load the nuclide using the keyword
        let nuclide = super::read_nuclide_from_json("Li6", None)
            .expect("Failed to load Li6 from keyword");

        // Get available temperatures
        let temps = nuclide.temperatures()
            .expect("Nuclide should have temperatures available");
        assert!(
            !temps.is_empty(),
            "Nuclide should have at least one temperature"
        );

        // Use the first available temperature to get the energy grid
        let temp = &temps[0];
        let energy_grid = nuclide.energy_grid(temp)
            .expect("Energy grid should be available for the temperature");

        // Check that the energy grid exists and contains positive numbers
        assert!(
            !energy_grid.is_empty(),
            "Energy grid should not be empty"
        );

        for (i, &energy) in energy_grid.iter().enumerate() {
            assert!(
                energy > 0.0,
                "Energy at index {} should be positive, but got {}",
                i,
                energy
            );
        }

        // Additional check: energy grid should be sorted in ascending order
        for i in 1..energy_grid.len() {
            assert!(
                energy_grid[i] >= energy_grid[i - 1],
                "Energy grid should be sorted: energy[{}] = {} < energy[{}] = {}",
                i,
                energy_grid[i],
                i - 1,
                energy_grid[i - 1]
            );
        }

        println!(
            "Successfully loaded Li6 from URL with {} energy points at temperature {}",
            energy_grid.len(),
            temp
        );
    }

    #[test]
    fn test_microscopic_cross_section_with_temperature() {
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Test with specific temperature
        let result = nuclide.microscopic_cross_section(2, Some("294"));
        assert!(result.is_ok(), "Should successfully get MT=2 data for 294K");
        
        let (xs, energy) = result.unwrap();
        assert!(!xs.is_empty(), "Cross section data should not be empty");
        assert!(!energy.is_empty(), "Energy data should not be empty");
        assert_eq!(xs.len(), energy.len(), "Cross section and energy arrays should have same length");
        
        // Test with different temperature
        let result_300 = nuclide.microscopic_cross_section(2, Some("300"));
        assert!(result_300.is_ok(), "Should successfully get MT=2 data for 300K");
        
        let (xs_300, energy_300) = result_300.unwrap();
        assert!(!xs_300.is_empty(), "Cross section data should not be empty for 300K");
        assert!(!energy_300.is_empty(), "Energy data should not be empty for 300K");
    }

    #[test]
    fn test_microscopic_cross_section_single_temperature() {
        // Load Be9 with only one temperature
        let temps_filter = std::collections::HashSet::from(["294".to_string()]);
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", Some(&temps_filter))
            .expect("Failed to load Be9.json with temperature filter");

        // Should work without specifying temperature since only one is loaded
        let result = nuclide.microscopic_cross_section(2, None);
        assert!(result.is_ok(), "Should successfully get MT=2 data without temperature");
        
        let (xs, energy) = result.unwrap();
        assert!(!xs.is_empty(), "Cross section data should not be empty");
        assert!(!energy.is_empty(), "Energy data should not be empty");
        assert_eq!(xs.len(), energy.len(), "Cross section and energy arrays should have same length");
    }

    #[test]
    fn test_microscopic_cross_section_multiple_temperatures_error() {
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Should fail when no temperature specified with multiple loaded
        let result = nuclide.microscopic_cross_section(2, None);
        assert!(result.is_err(), "Should error when multiple temperatures loaded without specifying");
        
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("Multiple temperatures loaded"), 
               "Error should mention multiple temperatures: {}", error_msg);
        assert!(error_msg.contains("[294, 300]"), 
               "Error should list the loaded temperatures: {}", error_msg);
    }

    #[test]
    fn test_microscopic_cross_section_invalid_temperature() {
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Should fail for non-existent temperature
        let result = nuclide.microscopic_cross_section(2, Some("500"));
        assert!(result.is_err(), "Should error for invalid temperature");
        
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("Temperature '500' not found"), 
               "Error should mention temperature not found: {}", error_msg);
        assert!(error_msg.contains("Available temperatures:"), 
               "Error should list available temperatures: {}", error_msg);
        assert!(error_msg.contains("294") && error_msg.contains("300"), 
               "Error should list the actual available temperatures: {}", error_msg);
    }

    #[test]
    fn test_microscopic_cross_section_invalid_mt() {
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Should fail for non-existent MT
        let result = nuclide.microscopic_cross_section(9999, Some("294"));
        assert!(result.is_err(), "Should error for invalid MT number");
        
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("MT 9999 not found"), 
               "Error should mention MT not found: {}", error_msg);
        assert!(error_msg.contains("Available MTs:"), 
               "Error should list available MTs: {}", error_msg);
        // Check that some common MTs are listed
        assert!(error_msg.contains("1") && error_msg.contains("2"), 
               "Error should list some actual available MTs: {}", error_msg);
    }

    #[test]
    fn test_microscopic_cross_section_multiple_mt_numbers() {
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Test common MT numbers that should exist in Be9
        let test_mts = [1, 2, 3, 16, 27, 101, 102];
        
        for mt in test_mts {
            let result = nuclide.microscopic_cross_section(mt, Some("294"));
            if result.is_ok() {
                let (xs, energy) = result.unwrap();
                assert!(!xs.is_empty(), "MT={} should have cross section data", mt);
                assert!(!energy.is_empty(), "MT={} should have energy data", mt);
                assert_eq!(xs.len(), energy.len(), "MT={} data length mismatch", mt);
                
                // Validate data quality
                for &e in &energy {
                    assert!(e > 0.0, "MT={} energy values should be positive", mt);
                }
                for &x in &xs {
                    assert!(x >= 0.0, "MT={} cross sections should be non-negative", mt);
                }
            }
            // Some MT numbers might not exist, which is fine
        }
    }

    #[test]
    fn test_microscopic_cross_section_lithium() {
        let mut nuclide = super::read_nuclide_from_json("tests/Li6.json", None)
            .expect("Failed to load Li6.json");

        // Li6 should have only one temperature, so no temperature needed
        let result = nuclide.microscopic_cross_section(2, None);
        assert!(result.is_ok(), "Should successfully get Li6 elastic scattering data");
        
        let (xs, energy) = result.unwrap();
        assert!(!xs.is_empty(), "Li6 elastic scattering data should not be empty");
        assert!(!energy.is_empty(), "Li6 energy data should not be empty");
        
        // Test with explicit temperature too
        let result_explicit = nuclide.microscopic_cross_section(2, Some("294"));
        assert!(result_explicit.is_ok(), "Should work with explicit temperature");
        
        let (xs_explicit, energy_explicit) = result_explicit.unwrap();
        assert_eq!(xs, xs_explicit, "Results should be identical with/without explicit temperature");
        assert_eq!(energy, energy_explicit, "Energy should be identical with/without explicit temperature");
    }

    #[test]
    fn test_microscopic_cross_section_temperature_with_k_suffix() {
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Test that temperature matching works with 'K' suffix
        let result_without_k = nuclide.microscopic_cross_section(2, Some("294"));
        let result_with_k = nuclide.microscopic_cross_section(2, Some("294K"));
        
        // Both should work (though one might fail if the data uses different format)
        if result_without_k.is_ok() && result_with_k.is_ok() {
            let (xs1, energy1) = result_without_k.unwrap();
            let (xs2, energy2) = result_with_k.unwrap();
            assert_eq!(xs1, xs2, "Temperature with/without K suffix should give same result");
            assert_eq!(energy1, energy2, "Energy with/without K suffix should give same result");
        } else {
            // At least one should work
            assert!(result_without_k.is_ok() || result_with_k.is_ok(), 
                   "At least one temperature format should work");
        }
    }

    #[test]
    fn test_auto_loading_from_config() {
        // Clear cache to ensure clean test
        super::clear_nuclide_cache();
        
        // Set up config for auto-loading
        {
            let mut cfg = crate::config::CONFIG.lock().unwrap();
            cfg.set_cross_section("Be9", Some("tests/Be9.json"));
        }

        // Create empty nuclide with name but no data loaded
        let mut nuclide = super::Nuclide {
            name: Some("Be9".to_string()),
            element: None,
            atomic_symbol: None,
            atomic_number: None,
            neutron_number: None,
            mass_number: None,
            library: None,
            energy: None,
            reactions: std::collections::HashMap::new(),
            fissionable: false,
            available_temperatures: Vec::new(),
            loaded_temperatures: Vec::new(),
            data_path: None,
        };

        // Verify no data is loaded initially
        assert!(nuclide.loaded_temperatures.is_empty(), "Should start with no loaded temperatures");
        assert!(nuclide.reactions.is_empty(), "Should start with no reactions");

        // Call microscopic_cross_section - should auto-load data
        let result = nuclide.microscopic_cross_section(2, Some("294"));
        assert!(result.is_ok(), "Auto-loading should succeed: {:?}", result.err());
        
        let (xs, energy) = result.unwrap();
        assert!(!xs.is_empty(), "Auto-loaded cross section data should not be empty");
        assert!(!energy.is_empty(), "Auto-loaded energy data should not be empty");
        
        // Verify data was actually loaded into the nuclide
        assert!(!nuclide.loaded_temperatures.is_empty(), "Should have loaded temperatures after auto-load");
        assert!(!nuclide.reactions.is_empty(), "Should have reactions after auto-load");
        assert!(nuclide.available_temperatures.contains(&"294".to_string()), "Should know 294 is available");
        assert!(nuclide.available_temperatures.contains(&"300".to_string()), "Should know 300 is available");

        // Clean up
        {
            let mut cfg = crate::config::CONFIG.lock().unwrap();
            cfg.cross_sections.remove("Be9");
        }
    }

    #[test]
    fn test_auto_loading_additional_temperature() {
        // Clear cache to ensure clean test
        super::clear_nuclide_cache();
        
        // Set up config for auto-loading
        {
            let mut cfg = crate::config::CONFIG.lock().unwrap();
            cfg.set_cross_section("Be9", Some("tests/Be9.json"));
        }

        // Load Be9 with only 294K initially
        let temps_filter = std::collections::HashSet::from(["294".to_string()]);
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", Some(&temps_filter))
            .expect("Failed to load Be9.json with temperature filter");
        
        // Verify only 294K is loaded initially
        assert_eq!(nuclide.loaded_temperatures, vec!["294".to_string()], "Should only have 294K loaded");
        assert!(nuclide.available_temperatures.contains(&"300".to_string()), "Should know 300K is available");
        
        // Request 300K data - should auto-load additional temperature
        let result = nuclide.microscopic_cross_section(2, Some("300"));
        assert!(result.is_ok(), "Auto-loading additional temperature should succeed: {:?}", result.err());
        
        let (xs, energy) = result.unwrap();
        assert!(!xs.is_empty(), "Auto-loaded 300K cross section data should not be empty");
        assert!(!energy.is_empty(), "Auto-loaded 300K energy data should not be empty");
        
        // Verify both temperatures are now loaded
        assert!(nuclide.loaded_temperatures.contains(&"294".to_string()), "Should still have 294K");
        assert!(nuclide.loaded_temperatures.contains(&"300".to_string()), "Should now have 300K");

        // Clean up
        {
            let mut cfg = crate::config::CONFIG.lock().unwrap();
            cfg.cross_sections.remove("Be9");
        }
    }

    #[test]
    fn test_auto_loading_without_config_fails() {
        // Clear cache to ensure clean test
        super::clear_nuclide_cache();
        
        // Make sure no config exists for our test nuclide
        {
            let mut cfg = crate::config::CONFIG.lock().unwrap();
            cfg.cross_sections.remove("TestNuclide");
        }

        // Create empty nuclide with name but no config
        let mut nuclide = super::Nuclide {
            name: Some("TestNuclide".to_string()),
            element: None,
            atomic_symbol: None,
            atomic_number: None,
            neutron_number: None,
            mass_number: None,
            library: None,
            energy: None,
            reactions: std::collections::HashMap::new(),
            fissionable: false,
            available_temperatures: Vec::new(),
            loaded_temperatures: Vec::new(),
            data_path: None,
        };

        // Call microscopic_cross_section - should fail with helpful error
        let result = nuclide.microscopic_cross_section(2, Some("294"));
        assert!(result.is_err(), "Auto-loading without config should fail");
        
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("No configuration found"), "Error should mention missing configuration");
        assert!(error_msg.contains("TestNuclide"), "Error should mention the nuclide name");
        assert!(error_msg.contains("Config.set_cross_sections"), "Error should suggest how to fix it");
    }

    #[test]
    fn test_cache_optimization_keyword_vs_path() {
        // Test that accessing the same file via keyword vs direct path uses same cache entry
        use std::collections::HashMap;
        
        super::clear_nuclide_cache();

        // Load Li6 from local file first
        let mut li6_map = HashMap::new();
        li6_map.insert("Li6".to_string(), "tests/Li6.json".to_string());
        let _first = super::get_or_load_nuclide("Li6", &li6_map, None)
            .expect("Initial file load failed");

        // Now try to load the same file by its absolute path
        let absolute_path = std::fs::canonicalize("tests/Li6.json").unwrap();
        let mut abs_map = HashMap::new();
        abs_map.insert("Li6".to_string(), absolute_path.to_string_lossy().to_string());
        let _second = super::get_or_load_nuclide("Li6", &abs_map, None)
            .expect("Absolute path load failed");

        // Verify both entries use the same cache key (should only be one entry)
        {
            let cache = match super::GLOBAL_NUCLIDE_CACHE.lock() {
                Ok(cache) => cache,
                Err(poisoned) => poisoned.into_inner()
            };
            
            // Should only have one cache entry since both resolve to the same file
            let li6_entries: Vec<_> = cache.keys()
                .filter(|k| k.starts_with("Li6@") && k.contains("Li6.json"))
                .collect();
            
            assert_eq!(li6_entries.len(), 1, 
                "Expected exactly 1 cache entry for Li6, found: {:?}", li6_entries);
        }
    }

    #[test]
    fn test_auto_loading_no_name_fails() {
        // Create empty nuclide without name
        let mut nuclide = super::Nuclide {
            name: None,
            element: None,
            atomic_symbol: None,
            atomic_number: None,
            neutron_number: None,
            mass_number: None,
            library: None,
            energy: None,
            reactions: std::collections::HashMap::new(),
            fissionable: false,
            available_temperatures: Vec::new(),
            loaded_temperatures: Vec::new(),
            data_path: None,
        };

        // Call microscopic_cross_section - should fail because no name for auto-loading
        let result = nuclide.microscopic_cross_section(2, Some("294"));
        assert!(result.is_err(), "Auto-loading without nuclide name should fail");
        
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("no nuclide name available"), "Error should mention missing name");
    }

    #[test]
    fn test_fendl_3_2c_keyword() {
        // Test that the fendl-3.2c keyword is recognized and can be used
        use crate::url_cache::is_keyword;
        
        // Check that the keyword is recognized
        assert!(is_keyword("fendl-3.2c"), "fendl-3.2c should be a recognized keyword");
        
        #[cfg(feature = "download")]
        {
            use crate::url_cache::expand_keyword_to_url;
            
            // Check that keyword expansion works correctly
            let expanded = expand_keyword_to_url("fendl-3.2c", "Li6");
            assert!(expanded.is_some(), "fendl-3.2c keyword should expand to URL");
            
            let url = expanded.unwrap();
            assert!(url.contains("https://raw.githubusercontent.com/fusion-neutronics/cross_section_data_fendl_3.2c"), 
                    "Expanded URL should contain correct base URL");
            assert!(url.ends_with("Li6.json"), "Expanded URL should end with nuclide name and .json");
            assert_eq!(url, "https://raw.githubusercontent.com/fusion-neutronics/cross_section_data_fendl_3.2c/refs/heads/main/fendl3.2c_data/Li6.json");
        }
    }

    #[test]
    fn test_microscopic_cross_section_string_reactions() {
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Test with MT number (existing functionality)
        let result_mt = nuclide.microscopic_cross_section(2, Some("294"));
        assert!(result_mt.is_ok(), "Should work with MT number");
        let (xs_mt, energy_mt) = result_mt.unwrap();

        // Test with reaction name string
        let result_str = nuclide.microscopic_cross_section("(n,elastic)", Some("294"));
        assert!(result_str.is_ok(), "Should work with reaction name string");
        let (xs_str, energy_str) = result_str.unwrap();

        // Results should be identical
        assert_eq!(xs_mt, xs_str, "Cross section data should be identical for MT 2 and '(n,elastic)'");
        assert_eq!(energy_mt, energy_str, "Energy data should be identical for MT 2 and '(n,elastic)'");

        // Test other common reaction strings
        let test_cases = vec![
            ("(n,gamma)", 102),
            ("(n,p)", 103),
            ("(n,a)", 107),
        ];

        for (reaction_name, expected_mt) in test_cases {
            let result_str = nuclide.microscopic_cross_section(reaction_name, Some("294"));
            let result_mt = nuclide.microscopic_cross_section(expected_mt, Some("294"));
            
            // If both succeed, they should give identical results
            if result_str.is_ok() && result_mt.is_ok() {
                let (xs_str, energy_str) = result_str.unwrap();
                let (xs_mt, energy_mt) = result_mt.unwrap();
                assert_eq!(xs_str, xs_mt, "Cross section should match for {} and MT {}", reaction_name, expected_mt);
                assert_eq!(energy_str, energy_mt, "Energy should match for {} and MT {}", reaction_name, expected_mt);
            }
            // If one fails, both should fail (reaction not available in this nuclide)
            else {
                assert_eq!(result_str.is_ok(), result_mt.is_ok(), 
                          "String and MT results should both succeed or both fail for {} vs MT {}", 
                          reaction_name, expected_mt);
            }
        }
    }

    #[test]
    fn test_microscopic_cross_section_invalid_reaction_string() {
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Test with invalid reaction name
        let result = nuclide.microscopic_cross_section("(n,invalid)", Some("294"));
        assert!(result.is_err(), "Should fail for invalid reaction name");
        
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("Unknown reaction name"), "Error should mention unknown reaction name");
        assert!(error_msg.contains("(n,invalid)"), "Error should include the invalid reaction name");
        assert!(error_msg.contains("REACTION_MT"), "Error should mention where to find available reactions");
    }

    #[test]
    fn test_microscopic_cross_section_fission_alias() {
        // Note: Be9 is not fissionable, so we'll just test the string recognition
        // The fission alias should map to MT 18
        let mut nuclide = super::read_nuclide_from_json("tests/Be9.json", None)
            .expect("Failed to load Be9.json");

        // Test that "fission" string is recognized (even though Be9 doesn't have fission reactions)
        let result = nuclide.microscopic_cross_section("fission", Some("294"));
        
        // Should fail because Be9 doesn't have MT 18, but the error should be about missing MT, not unknown reaction
        assert!(result.is_err(), "Should fail because Be9 doesn't have fission reactions");
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("MT 18 not found"), "Error should be about missing MT 18, not unknown reaction name");
    }

    #[test]
    fn test_nuclide_different_data_sources() {
        // Test that loading the same nuclide from different sources gives different results
        
        // Clear cache to ensure fresh loads
        crate::nuclide::clear_nuclide_cache();

        // For this test, we'll use different file paths as data sources
        // since network calls in tests are unreliable
        let mut li6_file = super::read_nuclide_from_json("tests/Li6.json", None)
            .expect("Failed to load Li6 from file");
        
        let mut li7_file = super::read_nuclide_from_json("tests/Li7.json", None)  
            .expect("Failed to load Li7 from file");

        // Get cross sections from both (different nuclides will have different data)
        let (xs_li6, _) = li6_file.microscopic_cross_section("(n,gamma)", Some("294"))
            .expect("Failed to get Li6 cross section");
        let (xs_li7, _) = li7_file.microscopic_cross_section("(n,gamma)", Some("294"))
            .expect("Failed to get Li7 cross section");

        // Should have different data since they're different nuclides
        let data_different = xs_li6.len() != xs_li7.len() || 
                            xs_li6.iter().zip(&xs_li7).any(|(a, b)| (a - b).abs() > 1e-10);
        
        assert!(data_different, "Li6 and Li7 data should be different");
        println!("Li6: {} points, Li7: {} points", xs_li6.len(), xs_li7.len());
    }

    #[test]
    fn test_nuclide_file_vs_keyword_sources() {
        // Test that file paths and keywords can coexist in cache
        
        crate::nuclide::clear_nuclide_cache();

        // Load Li6 from local file
        let mut li6_file = super::read_nuclide_from_json("tests/Li6.json", None)
            .expect("Failed to load Li6 from file");

        // Load Li7 from local file (different nuclide, different source)
        let mut li7_file = super::read_nuclide_from_json("tests/Li7.json", None)
            .expect("Failed to load Li7 from file");

        assert_eq!(li6_file.name.as_deref(), Some("Li6"));
        assert_eq!(li7_file.name.as_deref(), Some("Li7"));
        
        // Verify we can load cross sections from both
        let (xs_li6, _) = li6_file.microscopic_cross_section("(n,gamma)", Some("294"))
            .expect("Failed to get Li6 cross section");
        let (xs_li7, _) = li7_file.microscopic_cross_section("(n,gamma)", Some("294"))
            .expect("Failed to get Li7 cross section");

        assert!(!xs_li6.is_empty() && !xs_li7.is_empty(), "Both should have cross section data");
    }

    #[test]
    fn test_nuclide_cache_respects_data_source_boundaries() {
        // Test that the cache properly separates different data sources
        
        crate::nuclide::clear_nuclide_cache();

        // Load Li6 from file first time
        let mut li6_1 = super::read_nuclide_from_json("tests/Li6.json", None)
            .expect("Failed to load Li6 first time");

        // Load Li7 from file (different nuclide/source)
        let mut li7 = super::read_nuclide_from_json("tests/Li7.json", None)
            .expect("Failed to load Li7");

        // Load Li6 from file again (should use cache)
        let mut li6_2 = super::read_nuclide_from_json("tests/Li6.json", None)
            .expect("Failed to load Li6 second time");

        // Get cross sections
        let (xs_li6_1, _) = li6_1.microscopic_cross_section("(n,gamma)", Some("294"))
            .expect("Failed to get Li6 cross section first time");
        let (xs_li7, _) = li7.microscopic_cross_section("(n,gamma)", Some("294"))
            .expect("Failed to get Li7 cross section");
        let (xs_li6_2, _) = li6_2.microscopic_cross_section("(n,gamma)", Some("294"))
            .expect("Failed to get Li6 cross section second time");

        // Li6 loads should be identical (cache working)
        assert_eq!(xs_li6_1, xs_li6_2, "Li6 loads should be identical (cache working)");

        // Li6 vs Li7 should be different (different nuclides)
        let li6_vs_li7_different = xs_li6_1.len() != xs_li7.len() || 
                                  xs_li6_1.iter().zip(&xs_li7).any(|(a, b)| (a - b).abs() > 1e-10);
        assert!(li6_vs_li7_different, "Li6 and Li7 should have different data");
    }
}