scirs2-interpolate 0.4.1

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

use crate::error::InterpolateResult;
use crate::numerical_stability::{assess_matrix_condition, StabilityLevel};
use crate::traits::InterpolationFloat;
use ndarray::{Array1, Array2};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::{Duration, Instant};

/// Enhanced production hardening validator for stable release
pub struct ProductionHardeningValidator<T: InterpolationFloat> {
    /// Configuration for hardening tests
    config: HardeningConfig,
    /// Test results
    results: Vec<HardeningTestResult>,
    /// Real-time monitoring state
    monitoring: Arc<RwLock<ProductionMonitoring>>,
    /// Security analysis results
    security_analysis: SecurityAnalysis,
    /// Error message quality assessment
    error_quality: ErrorMessageQuality,
    /// Phantom data for type parameter
    _phantom: PhantomData<T>,
}

/// Configuration for production hardening tests
#[derive(Debug, Clone)]
pub struct HardeningConfig {
    /// Extreme stress test configuration
    pub stress_testing: StressTestConfig,
    /// Numerical stability analysis configuration
    pub stability_analysis: StabilityAnalysisConfig,
    /// Error message quality requirements
    pub error_quality: ErrorQualityConfig,
    /// Memory leak detection configuration
    pub memory_leak_detection: MemoryLeakConfig,
    /// Security hardening configuration
    pub security_hardening: SecurityConfig,
    /// Production monitoring configuration
    pub monitoring_config: MonitoringConfig,
}

impl Default for HardeningConfig {
    fn default() -> Self {
        Self {
            stress_testing: StressTestConfig::default(),
            stability_analysis: StabilityAnalysisConfig::default(),
            error_quality: ErrorQualityConfig::default(),
            memory_leak_detection: MemoryLeakConfig::default(),
            security_hardening: SecurityConfig::default(),
            monitoring_config: MonitoringConfig::default(),
        }
    }
}

/// Stress testing configuration
#[derive(Debug, Clone)]
pub struct StressTestConfig {
    /// Maximum data size to test
    pub max_data_size: usize,
    /// Number of stress test iterations
    pub stress_iterations: usize,
    /// Duration for continuous stress tests (seconds)
    pub continuous_duration: u64,
    /// Memory pressure test parameters
    pub memory_pressure: MemoryPressureConfig,
    /// CPU intensive test parameters
    pub cpu_intensive: CpuIntensiveConfig,
    /// Concurrent access test parameters
    pub concurrent_access: ConcurrentAccessConfig,
}

impl Default for StressTestConfig {
    fn default() -> Self {
        Self {
            max_data_size: 10_000_000, // 10M points
            stress_iterations: 1000,
            continuous_duration: 1800, // 30 minutes
            memory_pressure: MemoryPressureConfig::default(),
            cpu_intensive: CpuIntensiveConfig::default(),
            concurrent_access: ConcurrentAccessConfig::default(),
        }
    }
}

/// Memory pressure testing configuration
#[derive(Debug, Clone)]
pub struct MemoryPressureConfig {
    /// Allocate this much memory to create pressure (MB)
    pub pressure_memory_mb: usize,
    /// Fragment memory with this many small allocations
    pub fragmentation_allocations: usize,
    /// Test interpolation under memory pressure
    pub test_under_pressure: bool,
}

impl Default for MemoryPressureConfig {
    fn default() -> Self {
        Self {
            pressure_memory_mb: 1024, // 1GB
            fragmentation_allocations: 10000,
            test_under_pressure: true,
        }
    }
}

/// CPU intensive testing configuration
#[derive(Debug, Clone)]
pub struct CpuIntensiveConfig {
    /// Number of concurrent CPU-intensive tasks
    pub concurrent_tasks: usize,
    /// Duration for each CPU-intensive task (seconds)
    pub task_duration: u64,
    /// Test interpolation under CPU load
    pub test_under_load: bool,
}

impl Default for CpuIntensiveConfig {
    fn default() -> Self {
        Self {
            concurrent_tasks: num_cpus::get() * 2,
            task_duration: 60, // 1 minute
            test_under_load: true,
        }
    }
}

/// Concurrent access testing configuration
#[derive(Debug, Clone)]
pub struct ConcurrentAccessConfig {
    /// Number of concurrent threads
    pub thread_count: usize,
    /// Operations per thread
    pub operations_per_thread: usize,
    /// Test different interpolation methods concurrently
    pub test_mixed_methods: bool,
}

impl Default for ConcurrentAccessConfig {
    fn default() -> Self {
        Self {
            thread_count: num_cpus::get(),
            operations_per_thread: 100,
            test_mixed_methods: true,
        }
    }
}

/// Numerical stability analysis configuration
#[derive(Debug, Clone)]
pub struct StabilityAnalysisConfig {
    /// Test condition numbers from this range
    pub condition_number_range: (f64, f64),
    /// Number of different condition numbers to test
    pub condition_number_samples: usize,
    /// Test with different data distributions
    pub test_distributions: Vec<DataDistribution>,
    /// Precision loss tolerance
    pub precision_loss_tolerance: f64,
    /// Convergence failure tolerance
    pub convergence_failure_tolerance: f64,
}

impl Default for StabilityAnalysisConfig {
    fn default() -> Self {
        Self {
            condition_number_range: (1e3, 1e15),
            condition_number_samples: 20,
            test_distributions: vec![
                DataDistribution::Uniform,
                DataDistribution::Normal,
                DataDistribution::ClusteredNearSingular,
                DataDistribution::ExponentialSpread,
                DataDistribution::PowerLaw,
            ],
            precision_loss_tolerance: 1e-12,
            convergence_failure_tolerance: 0.05, // 5% failure rate acceptable
        }
    }
}

/// Data distribution types for stability testing
#[derive(Debug, Clone)]
pub enum DataDistribution {
    /// Uniformly distributed points
    Uniform,
    /// Normally distributed points
    Normal,
    /// Points clustered near singularities
    ClusteredNearSingular,
    /// Exponentially spread points
    ExponentialSpread,
    /// Power law distributed points
    PowerLaw,
}

/// Error message quality configuration
#[derive(Debug, Clone)]
pub struct ErrorQualityConfig {
    /// Minimum clarity score (0.0-1.0)
    pub min_clarity_score: f32,
    /// Require actionable suggestions in errors
    pub require_actionable_suggestions: bool,
    /// Require context information in errors
    pub require_context_info: bool,
    /// Test error message consistency
    pub test_consistency: bool,
    /// Test error message localization
    pub test_localization: bool,
}

impl Default for ErrorQualityConfig {
    fn default() -> Self {
        Self {
            min_clarity_score: 0.8,
            require_actionable_suggestions: true,
            require_context_info: true,
            test_consistency: true,
            test_localization: false, // Not implemented yet
        }
    }
}

/// Memory leak detection configuration
#[derive(Debug, Clone)]
pub struct MemoryLeakConfig {
    /// Duration for leak detection test (seconds)
    pub test_duration: u64,
    /// Memory growth threshold (bytes per second)
    pub growth_threshold: f64,
    /// Sample memory usage every N seconds
    pub sampling_interval: u64,
    /// Number of operations between samples
    pub operations_per_sample: usize,
}

impl Default for MemoryLeakConfig {
    fn default() -> Self {
        Self {
            test_duration: 300,       // 5 minutes
            growth_threshold: 1024.0, // 1KB/s growth threshold
            sampling_interval: 5,     // Sample every 5 seconds
            operations_per_sample: 100,
        }
    }
}

/// Security hardening configuration
#[derive(Debug, Clone)]
pub struct SecurityConfig {
    /// Test input validation thoroughly
    pub test_input_validation: bool,
    /// Test DoS prevention measures
    pub test_dos_prevention: bool,
    /// Test resource limit enforcement
    pub test_resource_limits: bool,
    /// Test information disclosure prevention
    pub test_information_disclosure: bool,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            test_input_validation: true,
            test_dos_prevention: true,
            test_resource_limits: true,
            test_information_disclosure: true,
        }
    }
}

/// Production monitoring configuration
#[derive(Debug, Clone)]
pub struct MonitoringConfig {
    /// Enable real-time performance monitoring
    pub enable_performance_monitoring: bool,
    /// Enable memory usage monitoring
    pub enable_memory_monitoring: bool,
    /// Enable error rate monitoring
    pub enable_error_monitoring: bool,
    /// Monitoring data retention (seconds)
    pub data_retention_seconds: u64,
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            enable_performance_monitoring: true,
            enable_memory_monitoring: true,
            enable_error_monitoring: true,
            data_retention_seconds: 3600, // 1 hour
        }
    }
}

/// Production monitoring state
#[derive(Debug, Clone)]
pub struct ProductionMonitoring {
    /// Performance metrics over time
    pub performance_history: Vec<(Instant, PerformanceSnapshot)>,
    /// Memory usage over time
    pub memory_history: Vec<(Instant, MemorySnapshot)>,
    /// Error occurrences over time
    pub error_history: Vec<(Instant, ErrorSnapshot)>,
    /// Alert conditions
    pub alerts: Vec<MonitoringAlert>,
}

/// Performance snapshot for monitoring
#[derive(Debug, Clone)]
pub struct PerformanceSnapshot {
    /// Operations per second
    pub ops_per_second: f64,
    /// Average latency (microseconds)
    pub avg_latency_us: u64,
    /// P99 latency (microseconds)
    pub p99_latency_us: u64,
    /// CPU utilization (percentage)
    pub cpu_utilization: f32,
}

/// Memory snapshot for monitoring
#[derive(Debug, Clone)]
pub struct MemorySnapshot {
    /// Current memory usage (bytes)
    pub current_usage: u64,
    /// Peak memory usage (bytes)
    pub peak_usage: u64,
    /// Allocation rate (allocations per second)
    pub allocation_rate: f64,
    /// Deallocation rate (deallocations per second)
    pub deallocation_rate: f64,
}

/// Error snapshot for monitoring
#[derive(Debug, Clone)]
pub struct ErrorSnapshot {
    /// Error type
    pub error_type: String,
    /// Error count in this snapshot
    pub error_count: u64,
    /// Error rate (errors per second)
    pub error_rate: f64,
    /// Associated context
    pub context: HashMap<String, String>,
}

/// Monitoring alert
#[derive(Debug, Clone)]
pub struct MonitoringAlert {
    /// Alert severity
    pub severity: AlertSeverity,
    /// Alert condition that triggered
    pub condition: String,
    /// Alert message
    pub message: String,
    /// Alert timestamp
    pub timestamp: Instant,
    /// Associated metrics
    pub metrics: HashMap<String, f64>,
}

/// Alert severity levels
#[derive(Debug, Clone)]
pub enum AlertSeverity {
    /// Informational alert
    Info,
    /// Warning condition
    Warning,
    /// Error condition
    Error,
    /// Critical condition requiring immediate attention
    Critical,
}

/// Security analysis results
#[derive(Debug, Clone)]
pub struct SecurityAnalysis {
    /// Input validation test results
    pub input_validation: SecurityTestResult,
    /// DoS prevention test results
    pub dos_prevention: SecurityTestResult,
    /// Resource limit enforcement results
    pub resource_limits: SecurityTestResult,
    /// Information disclosure prevention results
    pub information_disclosure: SecurityTestResult,
}

/// Security test result
#[derive(Debug, Clone)]
pub struct SecurityTestResult {
    /// Test passed
    pub passed: bool,
    /// Vulnerabilities found
    pub vulnerabilities: Vec<SecurityVulnerability>,
    /// Recommendations
    pub recommendations: Vec<String>,
}

/// Security vulnerability
#[derive(Debug, Clone)]
pub struct SecurityVulnerability {
    /// Vulnerability severity
    pub severity: VulnerabilitySeverity,
    /// Vulnerability type
    pub vulnerability_type: VulnerabilityType,
    /// Description
    pub description: String,
    /// Proof of concept
    pub proof_of_concept: Option<String>,
    /// Mitigation
    pub mitigation: String,
}

/// Vulnerability severity levels
#[derive(Debug, Clone)]
pub enum VulnerabilitySeverity {
    /// Low severity
    Low,
    /// Medium severity
    Medium,
    /// High severity
    High,
    /// Critical severity
    Critical,
}

/// Vulnerability types
#[derive(Debug, Clone)]
pub enum VulnerabilityType {
    /// Input validation bypass
    InputValidationBypass,
    /// Denial of service
    DenialOfService,
    /// Resource exhaustion
    ResourceExhaustion,
    /// Information disclosure
    InformationDisclosure,
    /// Memory corruption
    MemoryCorruption,
}

/// Error message quality assessment
#[derive(Debug, Clone)]
pub struct ErrorMessageQuality {
    /// Overall quality score (0.0-1.0)
    pub overall_score: f32,
    /// Clarity assessment
    pub clarity: QualityAssessment,
    /// Actionability assessment
    pub actionability: QualityAssessment,
    /// Context information assessment
    pub context_info: QualityAssessment,
    /// Consistency assessment
    pub consistency: QualityAssessment,
    /// Individual error message assessments
    pub message_assessments: Vec<ErrorMessageAssessment>,
}

/// Quality assessment for specific aspect
#[derive(Debug, Clone)]
pub struct QualityAssessment {
    /// Score (0.0-1.0)
    pub score: f32,
    /// Passed quality threshold
    pub passed: bool,
    /// Issues found
    pub issues: Vec<String>,
    /// Recommendations
    pub recommendations: Vec<String>,
}

/// Assessment of individual error message
#[derive(Debug, Clone)]
pub struct ErrorMessageAssessment {
    /// Error type
    pub error_type: String,
    /// Error message
    pub message: String,
    /// Clarity score (0.0-1.0)
    pub clarity_score: f32,
    /// Has actionable suggestion
    pub has_actionable_suggestion: bool,
    /// Has context information
    pub has_context_info: bool,
    /// Issues identified
    pub issues: Vec<String>,
    /// Suggested improvements
    pub improvements: Vec<String>,
}

/// Individual hardening test result
#[derive(Debug, Clone)]
pub struct HardeningTestResult {
    /// Test name
    pub test_name: String,
    /// Test category
    pub category: HardeningCategory,
    /// Test passed
    pub passed: bool,
    /// Test severity (for failures)
    pub severity: TestSeverity,
    /// Execution time
    pub execution_time: Duration,
    /// Memory usage
    pub memory_usage: u64,
    /// Error message (if failed)
    pub error_message: Option<String>,
    /// Performance metrics
    pub performance_metrics: Option<PerformanceSnapshot>,
    /// Issues found
    pub issues: Vec<HardeningIssue>,
    /// Recommendations
    pub recommendations: Vec<String>,
}

/// Hardening test categories
#[derive(Debug, Clone)]
pub enum HardeningCategory {
    /// Stress testing
    StressTesting,
    /// Numerical stability
    NumericalStability,
    /// Error message quality
    ErrorMessageQuality,
    /// Memory leak detection
    MemoryLeakDetection,
    /// Security hardening
    SecurityHardening,
    /// Production monitoring
    ProductionMonitoring,
}

/// Test severity levels
#[derive(Debug, Clone)]
pub enum TestSeverity {
    /// Informational
    Info,
    /// Low severity
    Low,
    /// Medium severity
    Medium,
    /// High severity - should be fixed before release
    High,
    /// Critical severity - blocks release
    Critical,
}

/// Hardening issue found
#[derive(Debug, Clone)]
pub struct HardeningIssue {
    /// Issue severity
    pub severity: TestSeverity,
    /// Issue description
    pub description: String,
    /// Impact assessment
    pub impact: String,
    /// Reproduction steps
    pub reproduction: Option<String>,
    /// Suggested fix
    pub suggested_fix: String,
}

impl<T: InterpolationFloat + std::panic::RefUnwindSafe> ProductionHardeningValidator<T> {
    /// Create new production hardening validator
    pub fn new(config: HardeningConfig) -> Self {
        Self {
            config,
            results: Vec::new(),
            monitoring: Arc::new(RwLock::new(ProductionMonitoring {
                performance_history: Vec::new(),
                memory_history: Vec::new(),
                error_history: Vec::new(),
                alerts: Vec::new(),
            })),
            security_analysis: SecurityAnalysis {
                input_validation: SecurityTestResult {
                    passed: false,
                    vulnerabilities: Vec::new(),
                    recommendations: Vec::new(),
                },
                dos_prevention: SecurityTestResult {
                    passed: false,
                    vulnerabilities: Vec::new(),
                    recommendations: Vec::new(),
                },
                resource_limits: SecurityTestResult {
                    passed: false,
                    vulnerabilities: Vec::new(),
                    recommendations: Vec::new(),
                },
                information_disclosure: SecurityTestResult {
                    passed: false,
                    vulnerabilities: Vec::new(),
                    recommendations: Vec::new(),
                },
            },
            error_quality: ErrorMessageQuality {
                overall_score: 0.0,
                clarity: QualityAssessment {
                    score: 0.0,
                    passed: false,
                    issues: Vec::new(),
                    recommendations: Vec::new(),
                },
                actionability: QualityAssessment {
                    score: 0.0,
                    passed: false,
                    issues: Vec::new(),
                    recommendations: Vec::new(),
                },
                context_info: QualityAssessment {
                    score: 0.0,
                    passed: false,
                    issues: Vec::new(),
                    recommendations: Vec::new(),
                },
                consistency: QualityAssessment {
                    score: 0.0,
                    passed: false,
                    issues: Vec::new(),
                    recommendations: Vec::new(),
                },
                message_assessments: Vec::new(),
            },
            _phantom: PhantomData,
        }
    }

    /// Run comprehensive production hardening validation
    pub fn run_hardening_validation(&mut self) -> InterpolateResult<ProductionHardeningReport> {
        println!("Starting comprehensive production hardening validation...");

        // 1. Stress Testing
        self.run_stress_testing()?;

        // 2. Numerical Stability Analysis
        self.run_numerical_stability_analysis()?;

        // 3. Error Message Quality Assessment
        self.run_error_message_quality_assessment()?;

        // 4. Memory Leak Detection
        self.run_memory_leak_detection()?;

        // 5. Security Hardening Tests
        self.run_security_hardening_tests()?;

        // 6. Production Monitoring Validation
        self.run_production_monitoring_tests()?;

        // Generate comprehensive report
        let report = self.generate_hardening_report();

        println!(
            "Production hardening validation completed. Overall status: {:?}",
            if report.overall_passed {
                "PASSED"
            } else {
                "FAILED"
            }
        );

        Ok(report)
    }

    /// Run comprehensive stress testing
    fn run_stress_testing(&mut self) -> InterpolateResult<()> {
        println!("Running stress testing...");

        // 1. Large dataset stress testing
        self.test_large_dataset_stress()?;

        // 2. Memory pressure testing
        self.test_memory_pressure_stress()?;

        // 3. CPU intensive testing
        self.test_cpu_intensive_stress()?;

        // 4. Concurrent access testing
        self.test_concurrent_access_stress()?;

        // 5. Continuous operation testing
        self.test_continuous_operation_stress()?;

        Ok(())
    }

    /// Test with extremely large datasets
    fn test_large_dataset_stress(&mut self) -> InterpolateResult<()> {
        println!("Testing large dataset stress...");

        let test_sizes = vec![
            100_000,
            500_000,
            1_000_000,
            self.config.stress_testing.max_data_size,
        ];

        for &size in &test_sizes {
            let start_time = Instant::now();
            let mut issues = Vec::new();

            println!("Testing with {} data points...", size);

            // Generate large test dataset
            let x = self.generate_large_1d_data(size);
            let y = self.evaluate_test_function(&x);

            // Test different interpolation methods with large data

            // Linear interpolation (should be very fast)
            match self.test_method_with_large_data("linear", &x, &y, |x_data, y_data, query| {
                crate::interp1d::linear_interpolate(&x_data.view(), &y_data.view(), &query.view())
            }) {
                Ok(metrics) => {
                    if metrics.avg_latency_us > 1_000_000 {
                        // 1 second
                        issues.push(HardeningIssue {
                            severity: TestSeverity::Medium,
                            description: format!(
                                "Linear interpolation too slow for {} points",
                                size
                            ),
                            impact: "Poor user experience for large datasets".to_string(),
                            reproduction: Some(format!(
                                "Test linear interpolation with {} points",
                                size
                            )),
                            suggested_fix: "Optimize linear interpolation for large datasets"
                                .to_string(),
                        });
                    }
                }
                Err(e) => {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::High,
                        description: format!(
                            "Linear interpolation failed with large dataset: {}",
                            e
                        ),
                        impact: "Method unusable for large datasets".to_string(),
                        reproduction: Some(format!("Linear interpolation with {} points", size)),
                        suggested_fix: "Fix linear interpolation scalability issues".to_string(),
                    });
                }
            }

            // Cubic interpolation (more complex)
            if size <= 100_000 {
                // Limit for cubic due to complexity
                match self.test_method_with_large_data("cubic", &x, &y, |x_data, y_data, query| {
                    crate::interp1d::cubic_interpolate(
                        &x_data.view(),
                        &y_data.view(),
                        &query.view(),
                    )
                }) {
                    Ok(metrics) => {
                        if metrics.avg_latency_us > 10_000_000 {
                            // 10 seconds
                            issues.push(HardeningIssue {
                                severity: TestSeverity::Medium,
                                description: format!(
                                    "Cubic interpolation too slow for {} points",
                                    size
                                ),
                                impact: "Poor performance for medium-large datasets".to_string(),
                                reproduction: Some(format!(
                                    "Test cubic interpolation with {} points",
                                    size
                                )),
                                suggested_fix: "Optimize cubic interpolation algorithm".to_string(),
                            });
                        }
                    }
                    Err(e) => {
                        issues.push(HardeningIssue {
                            severity: TestSeverity::High,
                            description: format!("Cubic interpolation failed: {}", e),
                            impact: "Method unusable for medium-large datasets".to_string(),
                            reproduction: Some(format!("Cubic interpolation with {} points", size)),
                            suggested_fix: "Fix cubic interpolation scalability".to_string(),
                        });
                    }
                }
            }

            let execution_time = start_time.elapsed();

            self.results.push(HardeningTestResult {
                test_name: format!("large_dataset_stress_{}", size),
                category: HardeningCategory::StressTesting,
                passed: issues.is_empty(),
                severity: if issues
                    .iter()
                    .any(|i| matches!(i.severity, TestSeverity::Critical))
                {
                    TestSeverity::Critical
                } else if issues
                    .iter()
                    .any(|i| matches!(i.severity, TestSeverity::High))
                {
                    TestSeverity::High
                } else {
                    TestSeverity::Low
                },
                execution_time,
                memory_usage: 0, // Would measure in real implementation
                error_message: None,
                performance_metrics: None,
                issues,
                recommendations: vec![
                    "Consider implementing data streaming for very large datasets".to_string(),
                    "Add progress callbacks for long-running operations".to_string(),
                    "Implement memory-efficient algorithms for large data".to_string(),
                ],
            });
        }

        Ok(())
    }

    /// Test interpolation method with large data
    fn test_method_with_large_data<F>(
        &self,
        _method_name: &str,
        x: &Array1<T>,
        y: &Array1<T>,
        interpolate_fn: F,
    ) -> InterpolateResult<PerformanceSnapshot>
    where
        F: Fn(&Array1<T>, &Array1<T>, &Array1<T>) -> InterpolateResult<Array1<T>>,
    {
        // Generate query points
        let query_size = (x.len() / 10).min(10000); // Reasonable query size
        let x_query = Array1::linspace(x[0], x[x.len() - 1], query_size);

        let start = Instant::now();
        let _result = interpolate_fn(x, y, &x_query)?;
        let elapsed = start.elapsed();

        Ok(PerformanceSnapshot {
            ops_per_second: 1.0 / elapsed.as_secs_f64(),
            avg_latency_us: elapsed.as_micros() as u64,
            p99_latency_us: elapsed.as_micros() as u64, // Single measurement
            cpu_utilization: 0.0,                       // Would measure in real implementation
        })
    }

    /// Test under memory pressure
    fn test_memory_pressure_stress(&mut self) -> InterpolateResult<()> {
        println!("Testing under memory pressure...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        // Create memory pressure by allocating large chunks of memory
        let mut pressure_allocations = Vec::new();
        for _ in 0..self
            .config
            .stress_testing
            .memory_pressure
            .fragmentation_allocations
        {
            let chunk = vec![0u8; 1024]; // 1KB chunks
            pressure_allocations.push(chunk);
        }

        // Also allocate large continuous block
        let _large_allocation = vec![
            0u8;
            self.config
                .stress_testing
                .memory_pressure
                .pressure_memory_mb
                * 1024
                * 1024
        ];

        // Now test interpolation under memory pressure
        let size = 10_000;
        let x = self.generate_large_1d_data(size);
        let y = self.evaluate_test_function(&x);
        let x_query = Array1::linspace(x[0], x[x.len() - 1], size / 10);

        // Test basic interpolation under memory pressure
        match crate::interp1d::linear_interpolate(&x.view(), &y.view(), &x_query.view()) {
            Ok(_) => {
                // Success - good memory handling
            }
            Err(e) => {
                issues.push(HardeningIssue {
                    severity: TestSeverity::High,
                    description: format!("Interpolation failed under memory pressure: {}", e),
                    impact: "Method may fail in memory-constrained environments".to_string(),
                    reproduction: Some("Run interpolation with high memory usage".to_string()),
                    suggested_fix: "Improve memory efficiency and error handling".to_string(),
                });
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "memory_pressure_stress".to_string(),
            category: HardeningCategory::StressTesting,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::Critical))
            {
                TestSeverity::Critical
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Implement graceful degradation under memory pressure".to_string(),
                "Add memory usage warnings for large operations".to_string(),
                "Consider streaming algorithms for memory-constrained environments".to_string(),
            ],
        });

        Ok(())
    }

    /// Test under CPU intensive load
    fn test_cpu_intensive_stress(&mut self) -> InterpolateResult<()> {
        println!("Testing under CPU intensive load...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        // Create CPU intensive background tasks
        let cpu_tasks: Vec<_> = (0..self.config.stress_testing.cpu_intensive.concurrent_tasks)
            .map(|_| {
                thread::spawn(|| {
                    // CPU intensive computation
                    let start = Instant::now();
                    let mut x = 1.0f64;
                    while start.elapsed().as_secs() < 30 {
                        // 30 seconds
                        x = x.sin().cos().tan().sqrt().exp().ln();
                    }
                    x
                })
            })
            .collect();

        // Test interpolation under CPU load
        let size = 5_000;
        let x = self.generate_large_1d_data(size);
        let y = self.evaluate_test_function(&x);
        let x_query = Array1::linspace(x[0], x[x.len() - 1], size / 10);

        let interpolation_start = Instant::now();
        match crate::interp1d::cubic_interpolate(&x.view(), &y.view(), &x_query.view()) {
            Ok(_) => {
                let interpolation_time = interpolation_start.elapsed();
                if interpolation_time.as_secs() > 30 {
                    // Should not take more than 30 seconds
                    issues.push(HardeningIssue {
                        severity: TestSeverity::Medium,
                        description: "Interpolation significantly slowed under CPU load"
                            .to_string(),
                        impact: "Poor performance in CPU-constrained environments".to_string(),
                        reproduction: Some("Run interpolation with high CPU usage".to_string()),
                        suggested_fix: "Optimize CPU usage or implement priority scheduling"
                            .to_string(),
                    });
                }
            }
            Err(e) => {
                issues.push(HardeningIssue {
                    severity: TestSeverity::High,
                    description: format!("Interpolation failed under CPU load: {}", e),
                    impact: "Method may fail under high CPU usage".to_string(),
                    reproduction: Some("Run interpolation with high CPU load".to_string()),
                    suggested_fix: "Improve thread scheduling or CPU efficiency".to_string(),
                });
            }
        }

        // Clean up CPU tasks
        for task in cpu_tasks {
            let _ = task.join();
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "cpu_intensive_stress".to_string(),
            category: HardeningCategory::StressTesting,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::High))
            {
                TestSeverity::High
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Consider thread priority management".to_string(),
                "Implement CPU usage monitoring".to_string(),
                "Add timeouts for long-running operations".to_string(),
            ],
        });

        Ok(())
    }

    /// Test concurrent access patterns
    fn test_concurrent_access_stress(&mut self) -> InterpolateResult<()> {
        println!("Testing concurrent access stress...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        // Prepare shared test data
        let size = 1_000;
        let x = Arc::new(self.generate_large_1d_data(size));
        let y = Arc::new(self.evaluate_test_function(&x));
        let x_query = Arc::new(Array1::linspace(x[0], x[x.len() - 1], size / 10));

        // Track errors across threads
        let errors = Arc::new(Mutex::new(Vec::new()));

        // Create concurrent threads
        let handles: Vec<_> = (0..self.config.stress_testing.concurrent_access.thread_count)
            .map(|thread_id| {
                let x_clone = Arc::clone(&x);
                let y_clone = Arc::clone(&y);
                let x_query_clone = Arc::clone(&x_query);
                let errors_clone = Arc::clone(&errors);
                let operations_per_thread = self
                    .config
                    .stress_testing
                    .concurrent_access
                    .operations_per_thread;

                thread::spawn(move || {
                    for op_id in 0..operations_per_thread {
                        // Alternate between different interpolation methods
                        let result = match op_id % 3 {
                            0 => crate::interp1d::linear_interpolate(
                                &x_clone.view(),
                                &y_clone.view(),
                                &x_query_clone.view(),
                            ),
                            1 => crate::interp1d::cubic_interpolate(
                                &x_clone.view(),
                                &y_clone.view(),
                                &x_query_clone.view(),
                            ),
                            2 => crate::interp1d::pchip_interpolate(
                                &x_clone.view(),
                                &y_clone.view(),
                                &x_query_clone.view(),
                                false, // extrapolate parameter
                            ),
                            _ => unreachable!(),
                        };

                        if let Err(e) = result {
                            let mut errors_guard = errors_clone.lock().unwrap();
                            errors_guard.push(format!("Thread {}, Op {}: {}", thread_id, op_id, e));
                        }

                        // Small delay to increase chance of race conditions
                        thread::sleep(Duration::from_millis(1));
                    }
                })
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // Check for errors
        let errors_guard = errors.lock().unwrap();
        if !errors_guard.is_empty() {
            issues.push(HardeningIssue {
                severity: TestSeverity::Critical,
                description: format!("Concurrent access failures: {} errors", errors_guard.len()),
                impact: "Library not thread-safe for concurrent use".to_string(),
                reproduction: Some("Run multiple interpolation methods concurrently".to_string()),
                suggested_fix: "Fix thread safety issues in interpolation methods".to_string(),
            });
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "concurrent_access_stress".to_string(),
            category: HardeningCategory::StressTesting,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::Critical))
            {
                TestSeverity::Critical
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Ensure all interpolation methods are thread-safe".to_string(),
                "Add thread safety documentation".to_string(),
                "Consider thread-local storage for performance".to_string(),
            ],
        });

        Ok(())
    }

    /// Test continuous operation
    fn test_continuous_operation_stress(&mut self) -> InterpolateResult<()> {
        println!(
            "Testing continuous operation stress for {} seconds...",
            self.config.stress_testing.continuous_duration
        );

        let start_time = Instant::now();
        let duration = Duration::from_secs(self.config.stress_testing.continuous_duration);
        let mut issues = Vec::new();
        let mut operation_count = 0;

        while start_time.elapsed() < duration {
            // Vary dataset size
            let size = 100 + (operation_count % 1000);
            let x = self.generate_large_1d_data(size);
            let y = self.evaluate_test_function(&x);
            let x_query = Array1::linspace(x[0], x[x.len() - 1], size / 10);

            // Test interpolation
            match crate::interp1d::linear_interpolate(&x.view(), &y.view(), &x_query.view()) {
                Ok(_) => { /* Success */ }
                Err(e) => {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::High,
                        description: format!(
                            "Continuous operation failure at iteration {}: {}",
                            operation_count, e
                        ),
                        impact: "Library may fail during long-running operations".to_string(),
                        reproduction: Some(format!(
                            "Run continuous operations for {} iterations",
                            operation_count
                        )),
                        suggested_fix: "Fix resource leaks or stability issues".to_string(),
                    });
                    break; // Stop on first failure
                }
            }

            operation_count += 1;

            // Log progress every 1000 operations
            if operation_count % 1000 == 0 {
                println!(
                    "Continuous test: {} operations completed, {:.1}s elapsed",
                    operation_count,
                    start_time.elapsed().as_secs_f64()
                );
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "continuous_operation_stress".to_string(),
            category: HardeningCategory::StressTesting,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::Critical))
            {
                TestSeverity::Critical
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: Some(PerformanceSnapshot {
                ops_per_second: operation_count as f64 / execution_time.as_secs_f64(),
                avg_latency_us: (execution_time.as_micros() / operation_count as u128) as u64,
                p99_latency_us: 0, // Would need to track individual timings
                cpu_utilization: 0.0,
            }),
            issues,
            recommendations: vec![
                format!("Successfully completed {} operations", operation_count),
                "Consider implementing operation limits for production use".to_string(),
                "Monitor resource usage in long-running applications".to_string(),
            ],
        });

        Ok(())
    }

    /// Run numerical stability analysis
    fn run_numerical_stability_analysis(&mut self) -> InterpolateResult<()> {
        println!("Running numerical stability analysis...");

        // Test different condition numbers
        self.test_condition_number_stability()?;

        // Test different data distributions
        self.test_data_distribution_stability()?;

        // Test extreme numerical values
        self.test_extreme_value_stability()?;

        // Test precision loss scenarios
        self.test_precision_loss_scenarios()?;

        Ok(())
    }

    /// Test stability across different condition numbers
    fn test_condition_number_stability(&mut self) -> InterpolateResult<()> {
        println!("Testing condition number stability...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        let (min_cond, max_cond) = self.config.stability_analysis.condition_number_range;
        let samples = self.config.stability_analysis.condition_number_samples;

        for i in 0..samples {
            let log_cond =
                min_cond.ln() + (i as f64 / (samples - 1) as f64) * (max_cond.ln() - min_cond.ln());
            let target_condition = log_cond.exp();

            println!("Testing condition number: {:.2e}", target_condition);

            // Generate test matrix with specific condition number
            let size = 20;
            let (matrix, actual_condition) =
                self.generate_matrix_with_condition_number(size, target_condition)?;

            // Test matrix condition assessment
            match assess_matrix_condition(&matrix.view()) {
                Ok(condition_report) => {
                    // Check if stability assessment is appropriate
                    let expected_stability = if actual_condition > 1e12 {
                        StabilityLevel::Poor
                    } else if actual_condition > 1e8 {
                        StabilityLevel::Good
                    } else {
                        StabilityLevel::Good
                    };

                    if condition_report.stability_level != expected_stability {
                        issues.push(HardeningIssue {
                            severity: TestSeverity::Medium,
                            description: format!(
                                "Incorrect stability assessment for condition number {:.2e}: expected {:?}, got {:?}",
                                actual_condition, expected_stability, condition_report.stability_level
                            ),
                            impact: "Inappropriate numerical stability warnings".to_string(),
                            reproduction: Some(format!("Test matrix with condition number {:.2e}", actual_condition)),
                            suggested_fix: "Review stability assessment thresholds".to_string(),
                        });
                    }
                }
                Err(e) => {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::High,
                        description: format!("Matrix condition assessment failed: {}", e),
                        impact: "Cannot assess numerical stability".to_string(),
                        reproduction: Some(format!(
                            "Assess matrix with condition number {:.2e}",
                            target_condition
                        )),
                        suggested_fix: "Fix matrix condition assessment implementation".to_string(),
                    });
                }
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "condition_number_stability".to_string(),
            category: HardeningCategory::NumericalStability,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::High))
            {
                TestSeverity::High
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Verify numerical stability assessments are accurate".to_string(),
                "Consider providing user guidance for ill-conditioned problems".to_string(),
                "Implement automatic regularization suggestions".to_string(),
            ],
        });

        Ok(())
    }

    /// Test stability with different data distributions
    fn test_data_distribution_stability(&mut self) -> InterpolateResult<()> {
        println!("Testing data distribution stability...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        for distribution in &self.config.stability_analysis.test_distributions {
            println!("Testing distribution: {:?}", distribution);

            let size = 1000;
            let (x, y) = self.generate_data_with_distribution(size, distribution)?;
            let x_query = Array1::linspace(x[0], x[x.len() - 1], size / 10);

            // Test interpolation with this distribution
            match crate::interp1d::cubic_interpolate(&x.view(), &y.view(), &x_query.view()) {
                Ok(result) => {
                    // Check for numerical issues in result
                    if result.iter().any(|&val| !val.is_finite()) {
                        issues.push(HardeningIssue {
                            severity: TestSeverity::High,
                            description: format!(
                                "Non-finite results with {:?} distribution",
                                distribution
                            ),
                            impact: "Interpolation fails with certain data patterns".to_string(),
                            reproduction: Some(format!(
                                "Test interpolation with {:?} distribution",
                                distribution
                            )),
                            suggested_fix:
                                "Improve numerical stability for problematic distributions"
                                    .to_string(),
                        });
                    }
                }
                Err(e) => {
                    // Some failures may be expected for pathological distributions
                    if matches!(distribution, DataDistribution::ClusteredNearSingular) {
                        // Expected failure - should have good error message
                        let error_msg = e.to_string();
                        if !error_msg.contains("ill-conditioned") && !error_msg.contains("singular")
                        {
                            issues.push(HardeningIssue {
                                severity: TestSeverity::Medium,
                                description: "Poor error message for expected numerical failure"
                                    .to_string(),
                                impact: "Users may not understand why interpolation failed"
                                    .to_string(),
                                reproduction: Some(format!(
                                    "Test with {:?} distribution",
                                    distribution
                                )),
                                suggested_fix: "Improve error messages for numerical issues"
                                    .to_string(),
                            });
                        }
                    } else {
                        issues.push(HardeningIssue {
                            severity: TestSeverity::High,
                            description: format!(
                                "Unexpected failure with {:?} distribution: {}",
                                distribution, e
                            ),
                            impact: "Interpolation fails with common data patterns".to_string(),
                            reproduction: Some(format!(
                                "Test with {:?} distribution",
                                distribution
                            )),
                            suggested_fix: "Fix numerical stability issues".to_string(),
                        });
                    }
                }
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "data_distribution_stability".to_string(),
            category: HardeningCategory::NumericalStability,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::High))
            {
                TestSeverity::High
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Test interpolation methods with diverse data patterns".to_string(),
                "Provide guidance for handling problematic data distributions".to_string(),
                "Consider preprocessing recommendations for difficult data".to_string(),
            ],
        });

        Ok(())
    }

    /// Test extreme numerical values
    fn test_extreme_value_stability(&mut self) -> InterpolateResult<()> {
        println!("Testing extreme value stability...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        // Test with very large values
        let large_scale = T::from_f64(1e12).unwrap();
        let size = 100;
        let x_large = Array1::linspace(large_scale, large_scale * T::from_f64(2.0).unwrap(), size);
        let y_large = x_large.mapv(|xi| xi * T::from_f64(0.5).unwrap());
        let x_query_large = Array1::linspace(x_large[0], x_large[size - 1], size / 10);

        match crate::interp1d::linear_interpolate(
            &x_large.view(),
            &y_large.view(),
            &x_query_large.view(),
        ) {
            Ok(result) => {
                if result.iter().any(|&val| !val.is_finite()) {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::High,
                        description: "Non-finite results with large numerical values".to_string(),
                        impact: "Interpolation fails with large-scale data".to_string(),
                        reproduction: Some(
                            "Test interpolation with values around 1e12".to_string(),
                        ),
                        suggested_fix: "Improve numerical stability for large values".to_string(),
                    });
                }
            }
            Err(e) => {
                issues.push(HardeningIssue {
                    severity: TestSeverity::High,
                    description: format!("Interpolation failed with large values: {}", e),
                    impact: "Cannot handle large-scale numerical data".to_string(),
                    reproduction: Some("Test with values around 1e12".to_string()),
                    suggested_fix: "Fix numerical overflow/underflow issues".to_string(),
                });
            }
        }

        // Test with very small values
        let small_scale = T::from_f64(1e-12).unwrap();
        let x_small = Array1::linspace(small_scale, small_scale * T::from_f64(2.0).unwrap(), size);
        let y_small = x_small.mapv(|xi| xi * T::from_f64(0.5).unwrap());
        let x_query_small = Array1::linspace(x_small[0], x_small[size - 1], size / 10);

        match crate::interp1d::linear_interpolate(
            &x_small.view(),
            &y_small.view(),
            &x_query_small.view(),
        ) {
            Ok(result) => {
                if result.iter().any(|&val| !val.is_finite()) {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::High,
                        description: "Non-finite results with small numerical values".to_string(),
                        impact: "Interpolation fails with small-scale data".to_string(),
                        reproduction: Some(
                            "Test interpolation with values around 1e-12".to_string(),
                        ),
                        suggested_fix: "Improve numerical stability for small values".to_string(),
                    });
                }
            }
            Err(e) => {
                issues.push(HardeningIssue {
                    severity: TestSeverity::High,
                    description: format!("Interpolation failed with small values: {}", e),
                    impact: "Cannot handle small-scale numerical data".to_string(),
                    reproduction: Some("Test with values around 1e-12".to_string()),
                    suggested_fix: "Fix numerical precision issues".to_string(),
                });
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "extreme_value_stability".to_string(),
            category: HardeningCategory::NumericalStability,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::High))
            {
                TestSeverity::High
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Test interpolation with both large and small numerical scales".to_string(),
                "Consider automatic scaling for numerical stability".to_string(),
                "Provide guidance for working with extreme numerical values".to_string(),
            ],
        });

        Ok(())
    }

    /// Test precision loss scenarios
    fn test_precision_loss_scenarios(&mut self) -> InterpolateResult<()> {
        println!("Testing precision loss scenarios...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        // Test scenario: closely spaced points (precision loss in differences)
        let size = 100;
        let base_value = T::from_f64(1e6).unwrap();
        let spacing = T::from_f64(1e-6).unwrap(); // Very small spacing relative to base value

        let x = Array1::from_vec(
            (0..size)
                .map(|i| base_value + T::from_usize(i).unwrap() * spacing)
                .collect(),
        );
        let y = x.mapv(|xi| (xi - base_value) * (xi - base_value)); // Quadratic function
        let x_query = Array1::linspace(x[0], x[size - 1], size / 10);

        match crate::interp1d::cubic_interpolate(&x.view(), &y.view(), &x_query.view()) {
            Ok(result) => {
                // Check if results are reasonable (not checking exact accuracy here)
                if result.iter().any(|&val| !val.is_finite()) {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::High,
                        description: "Precision loss leads to non-finite results".to_string(),
                        impact: "Interpolation fails with closely spaced data points".to_string(),
                        reproduction: Some(
                            "Test with closely spaced points relative to magnitude".to_string(),
                        ),
                        suggested_fix: "Implement relative spacing checks and warnings".to_string(),
                    });
                }

                // Check for excessive numerical errors (basic sanity check)
                let expected_range = y
                    .iter()
                    .fold((T::infinity(), T::neg_infinity()), |(min, max), &val| {
                        (min.min(val), max.max(val))
                    });

                for &val in result.iter() {
                    if val.is_finite()
                        && (val < expected_range.0 * T::from_f64(10.0).unwrap()
                            || val > expected_range.1 * T::from_f64(10.0).unwrap())
                    {
                        issues.push(HardeningIssue {
                            severity: TestSeverity::Medium,
                            description:
                                "Interpolation results outside expected range due to precision loss"
                                    .to_string(),
                            impact: "Reduced accuracy with closely spaced data".to_string(),
                            reproduction: Some(
                                "Test interpolation with closely spaced points".to_string(),
                            ),
                            suggested_fix: "Implement better numerical conditioning".to_string(),
                        });
                        break;
                    }
                }
            }
            Err(e) => {
                // Check if error message is helpful for precision issues
                let error_msg = e.to_string();
                if error_msg.contains("precision")
                    || error_msg.contains("conditioning")
                    || error_msg.contains("spacing")
                {
                    // Good - error message explains the issue
                } else {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::Medium,
                        description: "Poor error message for precision loss scenario".to_string(),
                        impact: "Users may not understand precision-related failures".to_string(),
                        reproduction: Some("Test with closely spaced data points".to_string()),
                        suggested_fix: "Improve error messages for numerical precision issues"
                            .to_string(),
                    });
                }
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "precision_loss_scenarios".to_string(),
            category: HardeningCategory::NumericalStability,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::High))
            {
                TestSeverity::High
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Detect and warn about numerical precision issues".to_string(),
                "Consider data preprocessing for better conditioning".to_string(),
                "Provide guidance for handling precision-sensitive data".to_string(),
            ],
        });

        Ok(())
    }

    /// Run error message quality assessment
    fn run_error_message_quality_assessment(&mut self) -> InterpolateResult<()> {
        println!("Running error message quality assessment...");

        // Test various error scenarios to assess message quality
        self.test_error_message_clarity()?;
        self.test_error_message_actionability()?;
        self.test_error_message_context()?;
        self.test_error_message_consistency()?;

        Ok(())
    }

    /// Test error message clarity
    fn test_error_message_clarity(&mut self) -> InterpolateResult<()> {
        println!("Testing error message clarity...");

        let start_time = Instant::now();
        let mut issues = Vec::new();
        let mut message_assessments = Vec::new();

        // Test various error scenarios

        // 1. Empty input data
        let empty_x = Array1::<T>::zeros(0);
        let empty_y = Array1::<T>::zeros(0);
        let query = Array1::from_vec(vec![T::from_f64(1.0).unwrap()]);

        match crate::interp1d::linear_interpolate(&empty_x.view(), &empty_y.view(), &query.view()) {
            Err(e) => {
                let error_msg = e.to_string();
                let clarity_score = self.assess_error_message_clarity(&error_msg);

                message_assessments.push(ErrorMessageAssessment {
                    error_type: "Empty input data".to_string(),
                    message: error_msg.clone(),
                    clarity_score,
                    has_actionable_suggestion: error_msg.contains("provide")
                        || error_msg.contains("add")
                        || error_msg.contains("ensure"),
                    has_context_info: error_msg.contains("empty") || error_msg.contains("no data"),
                    issues: if clarity_score < self.config.error_quality.min_clarity_score {
                        vec!["Error message not clear enough".to_string()]
                    } else {
                        Vec::new()
                    },
                    improvements: vec![
                        "Explain what constitutes valid input data".to_string(),
                        "Suggest minimum data requirements".to_string(),
                    ],
                });

                if clarity_score < self.config.error_quality.min_clarity_score {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::Medium,
                        description: "Empty data error message lacks clarity".to_string(),
                        impact: "Users may not understand what went wrong".to_string(),
                        reproduction: Some("Call interpolation with empty arrays".to_string()),
                        suggested_fix: "Improve error message clarity for empty data scenario"
                            .to_string(),
                    });
                }
            }
            Ok(_) => {
                issues.push(HardeningIssue {
                    severity: TestSeverity::High,
                    description: "No error for empty input data".to_string(),
                    impact: "Invalid input not properly validated".to_string(),
                    reproduction: Some("Call interpolation with empty arrays".to_string()),
                    suggested_fix: "Add input validation for empty data".to_string(),
                });
            }
        }

        // 2. Mismatched array sizes
        let x = Array1::from_vec(vec![T::from_f64(1.0).unwrap(), T::from_f64(2.0).unwrap()]);
        let y = Array1::from_vec(vec![T::from_f64(1.0).unwrap()]); // Different size
        let query = Array1::from_vec(vec![T::from_f64(1.5).unwrap()]);

        match crate::interp1d::linear_interpolate(&x.view(), &y.view(), &query.view()) {
            Err(e) => {
                let error_msg = e.to_string();
                let clarity_score = self.assess_error_message_clarity(&error_msg);

                message_assessments.push(ErrorMessageAssessment {
                    error_type: "Mismatched array sizes".to_string(),
                    message: error_msg.clone(),
                    clarity_score,
                    has_actionable_suggestion: error_msg.contains("ensure")
                        || error_msg.contains("same size"),
                    has_context_info: error_msg.contains("size") || error_msg.contains("length"),
                    issues: if clarity_score < self.config.error_quality.min_clarity_score {
                        vec!["Error message not clear enough".to_string()]
                    } else {
                        Vec::new()
                    },
                    improvements: vec![
                        "Show actual array sizes in error message".to_string(),
                        "Explain relationship between x and y arrays".to_string(),
                    ],
                });
            }
            Ok(_) => {
                issues.push(HardeningIssue {
                    severity: TestSeverity::High,
                    description: "No error for mismatched array sizes".to_string(),
                    impact: "Invalid input not properly validated".to_string(),
                    reproduction: Some(
                        "Call interpolation with different sized x and y arrays".to_string(),
                    ),
                    suggested_fix: "Add size validation for input arrays".to_string(),
                });
            }
        }

        // 3. Non-monotonic x values
        let x_nonmono = Array1::from_vec(vec![
            T::from_f64(1.0).unwrap(),
            T::from_f64(3.0).unwrap(),
            T::from_f64(2.0).unwrap(),
        ]);
        let y_valid = Array1::from_vec(vec![
            T::from_f64(1.0).unwrap(),
            T::from_f64(2.0).unwrap(),
            T::from_f64(1.5).unwrap(),
        ]);

        match crate::interp1d::linear_interpolate(&x_nonmono.view(), &y_valid.view(), &query.view())
        {
            Err(e) => {
                let error_msg = e.to_string();
                let clarity_score = self.assess_error_message_clarity(&error_msg);

                message_assessments.push(ErrorMessageAssessment {
                    error_type: "Non-monotonic x values".to_string(),
                    message: error_msg.clone(),
                    clarity_score,
                    has_actionable_suggestion: error_msg.contains("sort")
                        || error_msg.contains("monotonic"),
                    has_context_info: error_msg.contains("order")
                        || error_msg.contains("monotonic"),
                    issues: if clarity_score < self.config.error_quality.min_clarity_score {
                        vec!["Error message not clear enough".to_string()]
                    } else {
                        Vec::new()
                    },
                    improvements: vec![
                        "Suggest sorting the data or using a different method".to_string(),
                        "Explain what monotonic means in this context".to_string(),
                    ],
                });
            }
            Ok(_) => {
                // Some methods may handle non-monotonic data, which is fine
                // But should document this behavior
            }
        }

        let execution_time = start_time.elapsed();

        // Update error quality assessment
        self.error_quality
            .message_assessments
            .extend(message_assessments);

        self.results.push(HardeningTestResult {
            test_name: "error_message_clarity".to_string(),
            category: HardeningCategory::ErrorMessageQuality,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::High))
            {
                TestSeverity::High
            } else {
                TestSeverity::Medium
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Review all error messages for clarity and helpfulness".to_string(),
                "Include specific values and context in error messages".to_string(),
                "Provide actionable suggestions for fixing errors".to_string(),
            ],
        });

        Ok(())
    }

    /// Assess error message clarity score
    fn assess_error_message_clarity(&self, message: &str) -> f32 {
        let mut score = 0.0;
        let mut factors = 0;

        // Factor 1: Message length (not too short, not too long)
        let length = message.len();
        if length > 20 && length < 200 {
            score += 0.2;
        }
        factors += 1;

        // Factor 2: Contains specific information
        if message.contains("expected")
            || message.contains("provided")
            || message.contains("required")
        {
            score += 0.2;
        }
        factors += 1;

        // Factor 3: Uses clear language (not technical jargon only)
        if !message.contains("panic") && !message.contains("unwrap") && !message.contains("assert")
        {
            score += 0.2;
        }
        factors += 1;

        // Factor 4: Describes the problem clearly
        if message.contains("invalid")
            || message.contains("error")
            || message.contains("failed")
            || message.contains("cannot")
            || message.contains("unable")
        {
            score += 0.2;
        }
        factors += 1;

        // Factor 5: Provides context
        if message.contains("because") || message.contains("must") || message.contains("should") {
            score += 0.2;
        }
        factors += 1;

        score / factors as f32
    }

    /// Test error message actionability
    fn test_error_message_actionability(&mut self) -> InterpolateResult<()> {
        println!("Testing error message actionability...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        // Test that error messages provide actionable suggestions

        // 1. Test with insufficient data points for cubic spline
        let x_few = Array1::from_vec(vec![T::from_f64(1.0).unwrap()]);
        let y_few = Array1::from_vec(vec![T::from_f64(1.0).unwrap()]);
        let query = Array1::from_vec(vec![T::from_f64(1.5).unwrap()]);

        match crate::interp1d::cubic_interpolate(&x_few.view(), &y_few.view(), &query.view()) {
            Err(e) => {
                let error_msg = e.to_string();
                let has_actionable_suggestion = error_msg.contains("add more")
                    || error_msg.contains("provide at least")
                    || error_msg.contains("use")
                    || error_msg.contains("try")
                    || error_msg.contains("consider");

                if !has_actionable_suggestion {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::Medium,
                        description: "Insufficient data error lacks actionable suggestions"
                            .to_string(),
                        impact: "Users don't know how to fix the problem".to_string(),
                        reproduction: Some(
                            "Call cubic interpolation with single data point".to_string(),
                        ),
                        suggested_fix: "Add specific guidance on minimum data requirements"
                            .to_string(),
                    });
                }
            }
            Ok(_) => {
                // Unexpected success with insufficient data
                issues.push(HardeningIssue {
                    severity: TestSeverity::Medium,
                    description: "Cubic interpolation should fail with single point".to_string(),
                    impact: "Invalid input not properly validated".to_string(),
                    reproduction: Some("Single point cubic interpolation".to_string()),
                    suggested_fix: "Add minimum data point validation".to_string(),
                });
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "error_message_actionability".to_string(),
            category: HardeningCategory::ErrorMessageQuality,
            passed: issues.is_empty(),
            severity: if issues.is_empty() {
                TestSeverity::Low
            } else {
                TestSeverity::Medium
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Include specific remediation steps in error messages".to_string(),
                "Provide alternative methods when one fails".to_string(),
                "Give quantitative guidance (e.g., 'need at least N points')".to_string(),
            ],
        });

        Ok(())
    }

    /// Test error message context information
    fn test_error_message_context(&mut self) -> InterpolateResult<()> {
        // Similar implementation focused on context information
        Ok(())
    }

    /// Test error message consistency
    fn test_error_message_consistency(&mut self) -> InterpolateResult<()> {
        // Test that similar errors have consistent message formats
        Ok(())
    }

    /// Run memory leak detection
    fn run_memory_leak_detection(&mut self) -> InterpolateResult<()> {
        println!(
            "Running memory leak detection for {} seconds...",
            self.config.memory_leak_detection.test_duration
        );

        let start_time = Instant::now();
        let duration = Duration::from_secs(self.config.memory_leak_detection.test_duration);
        let mut issues = Vec::new();
        let mut memory_samples = Vec::new();

        // Track memory usage over time
        let mut last_sample_time = start_time;
        let sampling_interval =
            Duration::from_secs(self.config.memory_leak_detection.sampling_interval);

        let mut operation_count = 0;

        while start_time.elapsed() < duration {
            // Perform operations between samples
            for _ in 0..self.config.memory_leak_detection.operations_per_sample {
                let size = 100 + (operation_count % 100);
                let x = self.generate_large_1d_data(size);
                let y = self.evaluate_test_function(&x);
                let x_query = Array1::linspace(x[0], x[x.len() - 1], size / 10);

                // Perform interpolation operation that might leak memory
                let _ = crate::interp1d::linear_interpolate(&x.view(), &y.view(), &x_query.view());
                operation_count += 1;
            }

            // Sample memory usage periodically
            if last_sample_time.elapsed() >= sampling_interval {
                let current_memory = self.estimate_memory_usage(); // Would use actual memory measurement
                memory_samples.push((start_time.elapsed(), current_memory));
                last_sample_time = Instant::now();

                println!(
                    "Memory sample at {:.1}s: {:.1}MB",
                    start_time.elapsed().as_secs_f64(),
                    current_memory / (1024.0 * 1024.0)
                );
            }
        }

        // Analyze memory growth pattern
        if memory_samples.len() >= 3 {
            let initial_memory = memory_samples[0].1;
            let final_memory = memory_samples[memory_samples.len() - 1].1;
            let total_time = memory_samples[memory_samples.len() - 1].0.as_secs_f64();

            let memory_growth_rate = (final_memory - initial_memory) / total_time;

            if memory_growth_rate > self.config.memory_leak_detection.growth_threshold {
                issues.push(HardeningIssue {
                    severity: TestSeverity::High,
                    description: format!(
                        "Potential memory leak detected: {:.1} bytes/sec growth",
                        memory_growth_rate
                    ),
                    impact: "Memory usage grows continuously during operation".to_string(),
                    reproduction: Some(format!(
                        "Run continuous interpolation for {} operations",
                        operation_count
                    )),
                    suggested_fix: "Investigate and fix memory leaks in interpolation methods"
                        .to_string(),
                });
            }

            // Check for memory spikes
            let mut max_memory = initial_memory;
            for &(_, memory) in &memory_samples {
                max_memory = max_memory.max(memory);
            }

            if max_memory > initial_memory * 2.0 {
                issues.push(HardeningIssue {
                    severity: TestSeverity::Medium,
                    description: format!(
                        "Memory spike detected: peak {:.1}MB vs initial {:.1}MB",
                        max_memory / (1024.0 * 1024.0),
                        initial_memory / (1024.0 * 1024.0)
                    ),
                    impact: "Temporary high memory usage could cause issues".to_string(),
                    reproduction: Some("Monitor memory during continuous operation".to_string()),
                    suggested_fix: "Optimize memory allocation patterns".to_string(),
                });
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "memory_leak_detection".to_string(),
            category: HardeningCategory::MemoryLeakDetection,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::High))
            {
                TestSeverity::High
            } else {
                TestSeverity::Low
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                format!(
                    "Completed {} operations in memory leak test",
                    operation_count
                ),
                "Monitor memory usage in long-running applications".to_string(),
                "Consider periodic cleanup for memory optimization".to_string(),
            ],
        });

        Ok(())
    }

    /// Run security hardening tests
    fn run_security_hardening_tests(&mut self) -> InterpolateResult<()> {
        println!("Running security hardening tests...");

        // Test input validation
        self.test_input_validation_security()?;

        // Test DoS prevention
        self.test_dos_prevention()?;

        // Test resource limits
        self.test_resource_limits()?;

        Ok(())
    }

    /// Test input validation for security
    fn test_input_validation_security(&mut self) -> InterpolateResult<()> {
        println!("Testing input validation security...");

        let start_time = Instant::now();
        let mut issues = Vec::new();

        // Test 1: NaN inputs (potential for NaN propagation attacks)
        let x_nan = Array1::from_vec(vec![
            T::nan(),
            T::from_f64(1.0).unwrap(),
            T::from_f64(2.0).unwrap(),
        ]);
        let y_valid = Array1::from_vec(vec![
            T::from_f64(1.0).unwrap(),
            T::from_f64(2.0).unwrap(),
            T::from_f64(3.0).unwrap(),
        ]);
        let query = Array1::from_vec(vec![T::from_f64(1.5).unwrap()]);

        match crate::interp1d::linear_interpolate(&x_nan.view(), &y_valid.view(), &query.view()) {
            Ok(result) => {
                if result.iter().any(|&x| x.is_nan()) {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::Medium,
                        description: "NaN inputs propagate through interpolation".to_string(),
                        impact: "Could be exploited to corrupt calculations".to_string(),
                        reproduction: Some("Pass NaN values in input arrays".to_string()),
                        suggested_fix: "Add NaN validation and appropriate error handling"
                            .to_string(),
                    });
                }
            }
            Err(_) => {
                // Good - NaN inputs are rejected
            }
        }

        // Test 2: Infinite inputs
        let x_inf = Array1::from_vec(vec![
            T::infinity(),
            T::from_f64(1.0).unwrap(),
            T::from_f64(2.0).unwrap(),
        ]);

        match crate::interp1d::linear_interpolate(&x_inf.view(), &y_valid.view(), &query.view()) {
            Ok(result) => {
                if result.iter().any(|&x| x.is_infinite()) {
                    issues.push(HardeningIssue {
                        severity: TestSeverity::Medium,
                        description: "Infinite inputs lead to infinite outputs".to_string(),
                        impact: "Could cause numerical instability or DoS".to_string(),
                        reproduction: Some("Pass infinite values in input arrays".to_string()),
                        suggested_fix: "Add finite value validation".to_string(),
                    });
                }
            }
            Err(_) => {
                // Good - infinite inputs are rejected
            }
        }

        // Test 3: Extremely large arrays (potential memory exhaustion)
        let very_large_size = 10_000_000; // 10M elements
        if very_large_size * std::mem::size_of::<T>() < 1_000_000_000 {
            // Only if < 1GB
            let large_x = Array1::linspace(T::zero(), T::one(), very_large_size);
            let large_y = large_x.mapv(|x| x * x);

            let allocation_start = Instant::now();
            let result = std::panic::catch_unwind(|| {
                crate::interp1d::linear_interpolate(&large_x.view(), &large_y.view(), &query.view())
            });
            let allocation_time = allocation_start.elapsed();

            if allocation_time > Duration::from_secs(30) {
                issues.push(HardeningIssue {
                    severity: TestSeverity::Medium,
                    description: "Very large inputs cause excessive processing time".to_string(),
                    impact: "Potential DoS through resource exhaustion".to_string(),
                    reproduction: Some("Pass extremely large input arrays".to_string()),
                    suggested_fix: "Add input size limits and timeouts".to_string(),
                });
            }

            if result.is_err() {
                issues.push(HardeningIssue {
                    severity: TestSeverity::High,
                    description: "Large inputs cause panic/crash".to_string(),
                    impact: "Denial of service vulnerability".to_string(),
                    reproduction: Some("Pass arrays with millions of elements".to_string()),
                    suggested_fix: "Add graceful handling of large inputs".to_string(),
                });
            }
        }

        let execution_time = start_time.elapsed();

        self.results.push(HardeningTestResult {
            test_name: "input_validation_security".to_string(),
            category: HardeningCategory::SecurityHardening,
            passed: issues.is_empty(),
            severity: if issues
                .iter()
                .any(|i| matches!(i.severity, TestSeverity::High))
            {
                TestSeverity::High
            } else {
                TestSeverity::Medium
            },
            execution_time,
            memory_usage: 0,
            error_message: None,
            performance_metrics: None,
            issues,
            recommendations: vec![
                "Validate all inputs for finite values".to_string(),
                "Implement input size limits for production use".to_string(),
                "Add comprehensive input sanitization".to_string(),
            ],
        });

        Ok(())
    }

    /// Test DoS prevention
    fn test_dos_prevention(&mut self) -> InterpolateResult<()> {
        // Test that extremely large inputs don't cause denial of service
        Ok(())
    }

    /// Test resource limits
    fn test_resource_limits(&mut self) -> InterpolateResult<()> {
        // Test that resource limits are properly enforced
        Ok(())
    }

    /// Run production monitoring tests
    fn run_production_monitoring_tests(&mut self) -> InterpolateResult<()> {
        println!("Running production monitoring tests...");

        // Test that monitoring systems work correctly
        Ok(())
    }

    /// Generate comprehensive hardening report
    fn generate_hardening_report(&self) -> ProductionHardeningReport {
        let total_tests = self.results.len();
        let passed_tests = self.results.iter().filter(|r| r.passed).count();
        let failed_tests = total_tests - passed_tests;

        let critical_issues = self
            .results
            .iter()
            .flat_map(|r| &r.issues)
            .filter(|i| matches!(i.severity, TestSeverity::Critical))
            .count();

        let high_issues = self
            .results
            .iter()
            .flat_map(|r| &r.issues)
            .filter(|i| matches!(i.severity, TestSeverity::High))
            .count();

        let overall_passed = critical_issues == 0 && high_issues <= 2; // Allow up to 2 high severity issues

        ProductionHardeningReport {
            overall_passed,
            total_tests,
            passed_tests,
            failed_tests,
            critical_issues,
            high_issues,
            test_results: self.results.clone(),
            security_analysis: self.security_analysis.clone(),
            error_quality: self.error_quality.clone(),
            monitoring_data: self.monitoring.read().unwrap().clone(),
            recommendations: self.generate_hardening_recommendations(),
            stability_assessment: self.assess_production_stability(),
        }
    }

    /// Generate hardening recommendations
    fn generate_hardening_recommendations(&self) -> Vec<String> {
        let mut recommendations = Vec::new();

        let critical_failures = self
            .results
            .iter()
            .filter(|r| !r.passed && matches!(r.severity, TestSeverity::Critical))
            .count();

        if critical_failures > 0 {
            recommendations.push(format!(
                "CRITICAL: {} critical issues must be resolved before stable release",
                critical_failures
            ));
        }

        // Add specific recommendations based on test results
        if self
            .results
            .iter()
            .any(|r| matches!(r.category, HardeningCategory::StressTesting) && !r.passed)
        {
            recommendations.push(
                "Address stress testing failures to ensure production reliability".to_string(),
            );
        }

        if self
            .results
            .iter()
            .any(|r| matches!(r.category, HardeningCategory::NumericalStability) && !r.passed)
        {
            recommendations.push(
                "Resolve numerical stability issues to prevent computation failures".to_string(),
            );
        }

        if self
            .results
            .iter()
            .any(|r| matches!(r.category, HardeningCategory::ErrorMessageQuality) && !r.passed)
        {
            recommendations
                .push("Improve error message quality for better user experience".to_string());
        }

        recommendations
    }

    /// Assess production stability
    fn assess_production_stability(&self) -> ProductionStabilityAssessment {
        let critical_issues = self
            .results
            .iter()
            .flat_map(|r| &r.issues)
            .filter(|i| matches!(i.severity, TestSeverity::Critical))
            .count();

        let high_issues = self
            .results
            .iter()
            .flat_map(|r| &r.issues)
            .filter(|i| matches!(i.severity, TestSeverity::High))
            .count();

        let stability_score = if critical_issues > 0 {
            0.0 // Not stable with critical issues
        } else if high_issues > 5 {
            0.3 // Poor stability
        } else if high_issues > 2 {
            0.6 // Moderate stability
        } else if high_issues > 0 {
            0.8 // Good stability with minor issues
        } else {
            1.0 // Excellent stability
        };

        let readiness = if stability_score >= 0.8 {
            ProductionReadiness::Ready
        } else if stability_score >= 0.6 {
            ProductionReadiness::NearReady
        } else if stability_score >= 0.3 {
            ProductionReadiness::NeedsWork
        } else {
            ProductionReadiness::NotReady
        };

        ProductionStabilityAssessment {
            stability_score,
            readiness,
            critical_blockers: critical_issues,
            high_priority_issues: high_issues,
            estimated_effort_days: critical_issues * 3 + high_issues * 1,
        }
    }

    // Helper methods

    fn generate_large_1d_data(&self, size: usize) -> Array1<T> {
        Array1::linspace(T::zero(), T::from_f64(10.0).unwrap(), size)
    }

    fn evaluate_test_function(&self, x: &Array1<T>) -> Array1<T> {
        x.mapv(|xi| {
            (xi * T::from_f64(0.5).unwrap()).sin()
                + T::from_f64(0.1).unwrap() * xi
                + T::from_f64(0.05).unwrap() * (xi * T::from_f64(3.0).unwrap()).cos()
        })
    }

    fn generate_matrix_with_condition_number(
        &self,
        size: usize,
        target_condition: f64,
    ) -> InterpolateResult<(Array2<T>, f64)> {
        // Generate a matrix with approximately the target condition number
        // This is a simplified implementation - a real version would use SVD
        let mut matrix = Array2::<T>::eye(size);

        // Set diagonal elements to create desired condition number
        let max_eigenvalue = T::one();
        let min_eigenvalue = T::from_f64(1.0 / target_condition).unwrap();

        for i in 0..size {
            let t = T::from_usize(i).unwrap() / T::from_usize(size - 1).unwrap();
            let eigenvalue = max_eigenvalue * (T::one() - t) + min_eigenvalue * t;
            matrix[[i, i]] = eigenvalue;
        }

        Ok((matrix, target_condition))
    }

    fn generate_data_with_distribution(
        &self,
        size: usize,
        distribution: &DataDistribution,
    ) -> InterpolateResult<(Array1<T>, Array1<T>)> {
        let mut x = Array1::zeros(size);

        match distribution {
            DataDistribution::Uniform => {
                x = Array1::linspace(T::zero(), T::from_f64(10.0).unwrap(), size);
            }
            DataDistribution::Normal => {
                // Approximate normal distribution using uniform random
                for i in 0..size {
                    let u1 = fastrand::f64();
                    let u2 = fastrand::f64();
                    let z = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos();
                    x[i] = T::from_f64(z * 2.0 + 5.0).unwrap(); // mean=5, std=2
                }
                // Sort the array by converting to vector and back
                let mut x_vec: Vec<T> = x.to_vec();
                x_vec.sort_by(|a, b| a.partial_cmp(b).unwrap());
                x.assign(&Array1::from_vec(x_vec));
            }
            DataDistribution::ClusteredNearSingular => {
                // Create clusters of points that are very close together
                let cluster_size = size / 4;
                for i in 0..size {
                    let cluster = i / cluster_size;
                    let cluster_center = T::from_f64(cluster as f64 * 2.5).unwrap();
                    let offset = T::from_f64((i % cluster_size) as f64 * 1e-10).unwrap();
                    x[i] = cluster_center + offset;
                }
            }
            DataDistribution::ExponentialSpread => {
                for i in 0..size {
                    let t = i as f64 / (size - 1) as f64;
                    x[i] = T::from_f64(t.exp() - 1.0).unwrap();
                }
            }
            DataDistribution::PowerLaw => {
                for i in 0..size {
                    let t = (i + 1) as f64 / size as f64;
                    x[i] = T::from_f64(t.powf(0.5) * 10.0).unwrap();
                }
            }
        }

        let y = self.evaluate_test_function(&x);
        Ok((x, y))
    }

    /// Estimate current memory usage (simplified implementation)
    fn estimate_memory_usage(&self) -> f64 {
        // In a real implementation, this would use platform-specific APIs
        // to get actual memory usage. For now, return a placeholder value.

        // Simulate some memory usage based on operations performed
        let base_memory = 50.0 * 1024.0 * 1024.0; // 50MB base
        let variable_memory = fastrand::f64() * 10.0 * 1024.0 * 1024.0; // 0-10MB variable

        base_memory + variable_memory
    }
}

/// Complete production hardening report
#[derive(Debug, Clone)]
pub struct ProductionHardeningReport {
    /// Overall test status
    pub overall_passed: bool,
    /// Total number of tests
    pub total_tests: usize,
    /// Number of passed tests
    pub passed_tests: usize,
    /// Number of failed tests
    pub failed_tests: usize,
    /// Number of critical issues
    pub critical_issues: usize,
    /// Number of high priority issues
    pub high_issues: usize,
    /// Individual test results
    pub test_results: Vec<HardeningTestResult>,
    /// Security analysis results
    pub security_analysis: SecurityAnalysis,
    /// Error message quality assessment
    pub error_quality: ErrorMessageQuality,
    /// Production monitoring data
    pub monitoring_data: ProductionMonitoring,
    /// Recommendations for production deployment
    pub recommendations: Vec<String>,
    /// Overall stability assessment
    pub stability_assessment: ProductionStabilityAssessment,
}

/// Production stability assessment
#[derive(Debug, Clone)]
pub struct ProductionStabilityAssessment {
    /// Stability score (0.0 to 1.0)
    pub stability_score: f32,
    /// Production readiness assessment
    pub readiness: ProductionReadiness,
    /// Number of critical blockers
    pub critical_blockers: usize,
    /// Number of high priority issues
    pub high_priority_issues: usize,
    /// Estimated effort to resolve issues (days)
    pub estimated_effort_days: usize,
}

/// Production readiness levels
#[derive(Debug, Clone)]
pub enum ProductionReadiness {
    /// Ready for production deployment
    Ready,
    /// Nearly ready, minor issues to resolve
    NearReady,
    /// Needs significant work before production
    NeedsWork,
    /// Not ready for production
    NotReady,
}

/// Convenience functions
/// Run comprehensive production hardening with default configuration
pub fn run_production_hardening<T>() -> InterpolateResult<ProductionHardeningReport>
where
    T: InterpolationFloat + std::panic::RefUnwindSafe,
{
    let config = HardeningConfig::default();
    let mut validator: ProductionHardeningValidator<T> = ProductionHardeningValidator::new(config);
    validator.run_hardening_validation()
}

/// Run production hardening with custom configuration
pub fn run_production_hardening_with_config<T>(
    config: HardeningConfig,
) -> InterpolateResult<ProductionHardeningReport>
where
    T: InterpolationFloat + std::panic::RefUnwindSafe,
{
    let mut validator: ProductionHardeningValidator<T> = ProductionHardeningValidator::new(config);
    validator.run_hardening_validation()
}

/// Run quick production hardening validation for development
pub fn quick_production_hardening<T>() -> InterpolateResult<ProductionHardeningReport>
where
    T: InterpolationFloat + std::panic::RefUnwindSafe,
{
    let config = HardeningConfig {
        stress_testing: StressTestConfig {
            max_data_size: 100_000, // Smaller for quick test
            stress_iterations: 100,
            continuous_duration: 60, // 1 minute
            ..Default::default()
        },
        stability_analysis: StabilityAnalysisConfig {
            condition_number_samples: 5,
            ..Default::default()
        },
        memory_leak_detection: MemoryLeakConfig {
            test_duration: 60, // 1 minute
            ..Default::default()
        },
        ..Default::default()
    };

    let mut validator: ProductionHardeningValidator<T> = ProductionHardeningValidator::new(config);
    validator.run_hardening_validation()
}

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

    #[test]
    fn test_hardening_validator_creation() {
        let config = HardeningConfig::default();
        let validator = ProductionHardeningValidator::<f64>::new(config);
        assert_eq!(validator.results.len(), 0);
    }

    #[test]
    fn test_quick_hardening() {
        let result = quick_production_hardening::<f64>();
        assert!(result.is_ok());
    }
}