cachelito-core 0.16.0

Core functionality for cachelito - global cache with LRU/FIFO/LFU/ARC/Random/TLRU/W-TinyLFU eviction policies
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
use crate::{CacheEntry, EvictionPolicy};
use once_cell::sync::Lazy;
use parking_lot::lock_api::MutexGuard;
use parking_lot::{Mutex, RawMutex, RwLock};
use std::collections::{HashMap, VecDeque};
use std::fmt::Debug;

use crate::utils::{
    find_arc_eviction_key, find_min_frequency_key, find_tlru_eviction_key, move_key_to_end,
    remove_key_from_global_cache,
};
#[cfg(feature = "stats")]
use crate::CacheStats;

/// A thread-safe global cache that can be shared across multiple threads.
///
/// Unlike `ThreadLocalCache` which uses thread-local storage, `GlobalCache` stores
/// cached values in global static variables protected by locks, allowing cache
/// sharing across all threads in the application.
///
/// # Type Parameters
///
/// * `R` - The return type to be cached. Must be `'static` to be stored in global state.
///
/// # Features
///
/// - **Thread-safe sharing**: Multiple threads access the same cache through RwLock/Mutex
/// - **Eviction policies**: FIFO, LRU, LFU, ARC, Random, and TLRU
///   - **FIFO**: First In, First Out - simple and predictable
///   - **LRU**: Least Recently Used - evicts least recently accessed entries
///   - **LFU**: Least Frequently Used - evicts least frequently accessed entries
///   - **ARC**: Adaptive Replacement Cache - hybrid policy combining recency and frequency
///   - **Random**: Random replacement - O(1) eviction with minimal overhead
///   - **TLRU**: Time-aware LRU - combines recency, frequency, and age factors
///     - Customizable with `frequency_weight` parameter
///     - Formula: `score = frequency^weight × position × age_factor`
///     - `frequency_weight < 1.0`: Emphasize recency (time-sensitive data)
///     - `frequency_weight > 1.0`: Emphasize frequency (popular content)
/// - **Cache limits**: Entry count limits (`limit`) and memory-based limits (`max_memory`)
/// - **TTL support**: Automatic expiration of entries based on age
/// - **Statistics**: Optional cache hit/miss tracking (with `stats` feature)
/// - **Frequency tracking**: For LFU, ARC, and TLRU policies
/// - **Memory estimation**: Support for memory-based eviction (requires `MemoryEstimator`)
///
/// # Cache Entry Structure
///
/// Cache entries are stored as `CacheEntry<R>` which contains:
/// - `value`: The cached value of type R
/// - `timestamp`: Unix timestamp when the entry was created (for TTL and TLRU age factor)
/// - `frequency`: Access counter for LFU, ARC, and TLRU policies
///
/// # Eviction Behavior
///
/// When the cache reaches its limit (entry count or memory), entries are evicted according
/// to the configured policy:
///
/// - **FIFO**: Oldest entry (first in order queue) is evicted
/// - **LRU**: Least recently accessed entry (first in order queue) is evicted
/// - **LFU**: Entry with lowest frequency counter is evicted
/// - **ARC**: Entry with lowest score (frequency × position_weight) is evicted
/// - **Random**: Randomly selected entry is evicted
/// - **TLRU**: Entry with lowest score (frequency^weight × position × age_factor) is evicted
///
/// # Thread Safety
///
/// This cache uses `parking_lot::RwLock` for the cache map and `parking_lot::Mutex` for the order queue.
/// The `parking_lot` implementation provides:
/// - **RwLock for reads**: Multiple threads can read concurrently without blocking
/// - **No lock poisoning** (simpler API, no `Result` wrapping)
/// - **Better performance** under contention (30-50% faster than std::sync)
/// - **Smaller memory footprint** (~40x smaller than std::sync)
/// - **Fair locking algorithm** prevents thread starvation
///
/// **Read-heavy workloads** (typical for caches) see 4-5x performance improvement with RwLock
/// compared to Mutex, as multiple threads can read the cache simultaneously.
///
/// # Performance Characteristics
///
/// - **Get**: O(1) for cache lookup, O(n) for LRU/ARC/TLRU reordering
/// - **Insert**: O(1) for FIFO/Random, O(n) for LRU/LFU/ARC/TLRU eviction
/// - **Memory**: O(n) where n is the number of cached entries
/// - **Synchronization**: Lock acquisition overhead on every operation
///
/// # Performance Considerations
///
/// - **Synchronization overhead**: Each cache operation requires acquiring locks
/// - **Lock contention**: High concurrent access may cause threads to wait
/// - **Read optimization**: RwLock allows concurrent reads (no blocking for cache hits)
/// - **Write bottleneck**: Only one thread can modify cache at a time
/// - **Shared benefits**: All threads benefit from cached results
/// - **Best for**: Expensive computations where sharing outweighs synchronization cost
///
/// # Examples
///
/// ## Basic Usage
///
/// ```ignore
/// use cachelito_core::{GlobalCache, EvictionPolicy, CacheEntry};
/// use once_cell::sync::Lazy;
/// use parking_lot::{Mutex, RwLock};
/// use std::collections::{HashMap, VecDeque};
///
/// static CACHE_MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
///     Lazy::new(|| RwLock::new(HashMap::new()));
/// static CACHE_ORDER: Lazy<Mutex<VecDeque<String>>> =
///     Lazy::new(|| Mutex::new(VecDeque::new()));
///
/// let cache = GlobalCache::new(
///     &CACHE_MAP,
///     &CACHE_ORDER,
///     Some(100),         // Max 100 entries
///     None,              // No memory limit
///     EvictionPolicy::LRU,
///     Some(60),          // 60 second TTL
///     None,              // Default frequency_weight
/// );
///
/// // All threads can access the same cache
/// cache.insert("key1", 42);
/// assert_eq!(cache.get("key1"), Some(42));
/// ```
///
/// ## TLRU with Custom Frequency Weight
///
/// ```ignore
/// use cachelito_core::{GlobalCache, EvictionPolicy};
///
/// // Emphasize frequency over recency (good for popular content)
/// let cache = GlobalCache::new(
///     &CACHE_MAP,
///     &CACHE_ORDER,
///     Some(100),
///     None,
///     EvictionPolicy::TLRU,
///     Some(300),
///     Some(1.5),         // frequency_weight > 1.0
/// );
///
/// // Emphasize recency over frequency (good for time-sensitive data)
/// let cache = GlobalCache::new(
///     &CACHE_MAP,
///     &CACHE_ORDER,
///     Some(100),
///     None,
///     EvictionPolicy::TLRU,
///     Some(300),
///     Some(0.3),         // frequency_weight < 1.0
/// );
/// ```
///
/// ## With Memory Limits
///
/// ```ignore
/// use cachelito_core::{GlobalCache, EvictionPolicy, MemoryEstimator};
///
/// let cache = GlobalCache::new(
///     &CACHE_MAP,
///     &CACHE_ORDER,
///     Some(1000),
///     Some(100 * 1024 * 1024), // 100MB max
///     EvictionPolicy::LRU,
///     Some(300),
///     None,
/// );
///
/// // Insert with memory tracking (requires MemoryEstimator implementation)
/// cache.insert_with_memory("key", value);
/// ```
pub struct GlobalCache<R: 'static> {
    pub map: &'static Lazy<RwLock<HashMap<String, CacheEntry<R>>>>,
    pub order: &'static Lazy<Mutex<VecDeque<String>>>,
    pub limit: Option<usize>,
    pub max_memory: Option<usize>,
    pub policy: EvictionPolicy,
    pub ttl: Option<u64>,
    pub frequency_weight: Option<f64>,
    pub window_ratio: Option<f64>,
    pub sketch_width: Option<usize>,
    pub sketch_depth: Option<usize>,
    pub decay_interval: Option<u64>,
    #[cfg(feature = "stats")]
    pub stats: &'static Lazy<CacheStats>,
}

impl<R: Clone + 'static> GlobalCache<R> {
    /// Creates a new global cache instance.
    ///
    /// # Parameters
    ///
    /// * `map` - Static reference to a RwLock-protected HashMap for storing cache entries
    /// * `order` - Static reference to a Mutex-protected VecDeque for tracking entry order
    /// * `limit` - Optional maximum number of entries (None for unlimited)
    /// * `max_memory` - Optional maximum memory size in bytes (None for unlimited)
    /// * `policy` - Eviction policy (FIFO, LRU, LFU, ARC, Random, or TLRU)
    /// * `ttl` - Optional time-to-live in seconds for cache entries (None for no expiration)
    /// * `frequency_weight` - Optional weight factor for frequency in TLRU policy
    ///   - Values < 1.0: Emphasize recency and age
    ///   - Values > 1.0: Emphasize frequency
    ///   - None or 1.0: Balanced approach (default)
    ///   - Only used when policy is TLRU, ignored otherwise
    /// * `window_ratio` - Optional window ratio for W-TinyLFU policy (between 0.0 and 1.0)
    /// * `sketch_width` - Optional sketch width for W-TinyLFU policy
    /// * `sketch_depth` - Optional sketch depth for W-TinyLFU policy
    /// * `decay_interval` - Optional decay interval for W-TinyLFU policy
    /// * `stats` - Static reference to CacheStats for tracking hit/miss statistics (stats feature only)
    ///
    /// # Returns
    ///
    /// A new `GlobalCache` instance configured with the provided parameters.
    ///
    /// # Examples
    ///
    /// ## Basic LRU cache with TTL
    ///
    /// ```ignore
    /// let cache = GlobalCache::new(
    ///     &CACHE_MAP,
    ///     &CACHE_ORDER,
    ///     Some(1000),              // Max 1000 entries
    ///     None,                    // No memory limit
    ///     EvictionPolicy::LRU,     // LRU eviction
    ///     Some(300),               // 5 minute TTL
    ///     None,                    // No frequency_weight (not needed for LRU)
    ///     None,                    // No window_ratio
    ///     None,                    // No sketch_width
    ///     None,                    // No sketch_depth
    ///     None,                    // No decay_interval
    ///     #[cfg(feature = "stats")]
    ///     &CACHE_STATS,
    /// );
    /// ```
    ///
    /// ## TLRU with memory limit and custom frequency weight
    ///
    /// ```ignore
    /// let cache = GlobalCache::new(
    ///     &CACHE_MAP,
    ///     &CACHE_ORDER,
    ///     Some(1000),
    ///     Some(100 * 1024 * 1024), // 100MB max
    ///     EvictionPolicy::TLRU,    // TLRU eviction
    ///     Some(300),               // 5 minute TTL
    ///     Some(1.5),               // Emphasize frequency (popular content)
    ///     None,                    // No window_ratio
    ///     None,                    // No sketch_width
    ///     None,                    // No sketch_depth
    ///     None,                    // No decay_interval
    ///     #[cfg(feature = "stats")]
    ///     &CACHE_STATS,
    /// );
    /// ```
    #[cfg(feature = "stats")]
    pub fn new(
        map: &'static Lazy<RwLock<HashMap<String, CacheEntry<R>>>>,
        order: &'static Lazy<Mutex<VecDeque<String>>>,
        limit: Option<usize>,
        max_memory: Option<usize>,
        policy: EvictionPolicy,
        ttl: Option<u64>,
        frequency_weight: Option<f64>,
        window_ratio: Option<f64>,
        sketch_width: Option<usize>,
        sketch_depth: Option<usize>,
        decay_interval: Option<u64>,
        stats: &'static Lazy<CacheStats>,
    ) -> Self {
        Self {
            map,
            order,
            limit,
            max_memory,
            policy,
            ttl,
            frequency_weight,
            window_ratio,
            sketch_width,
            sketch_depth,
            decay_interval,
            stats,
        }
    }

    #[cfg(not(feature = "stats"))]
    pub fn new(
        map: &'static Lazy<RwLock<HashMap<String, CacheEntry<R>>>>,
        order: &'static Lazy<Mutex<VecDeque<String>>>,
        limit: Option<usize>,
        max_memory: Option<usize>,
        policy: EvictionPolicy,
        ttl: Option<u64>,
        frequency_weight: Option<f64>,
        window_ratio: Option<f64>,
        sketch_width: Option<usize>,
        sketch_depth: Option<usize>,
        decay_interval: Option<u64>,
    ) -> Self {
        Self {
            map,
            order,
            limit,
            max_memory,
            policy,
            ttl,
            frequency_weight,
            window_ratio,
            sketch_width,
            sketch_depth,
            decay_interval,
        }
    }

    /// Retrieves a cached value by key.
    ///
    /// This method attempts to retrieve a cached value, checking for expiration
    /// and updating access patterns based on the eviction policy.
    ///
    /// # Parameters
    ///
    /// * `key` - The cache key to retrieve
    ///
    /// # Returns
    ///
    /// * `Some(R)` - The cached value if found and not expired
    /// * `None` - If the key is not in cache or the entry has expired
    ///
    /// # Behavior by Policy
    ///
    /// - **FIFO**: No updates on cache hit (order remains unchanged)
    /// - **LRU**: Moves the key to the end of the order queue (most recently used)
    /// - **LFU**: Increments the frequency counter for the entry
    /// - **ARC**: Increments frequency counter and updates position in order queue
    /// - **Random**: No updates on cache hit
    /// - **TLRU**: Increments frequency counter and updates position in order queue
    ///
    /// # TTL Expiration
    ///
    /// If a TTL is configured and the entry has expired:
    /// - The entry is removed from both the cache map and order queue
    /// - A cache miss is recorded (if stats feature is enabled)
    /// - `None` is returned
    ///
    /// # Statistics
    ///
    /// When the `stats` feature is enabled:
    /// - Cache hits are recorded when a valid entry is found
    /// - Cache misses are recorded when the key doesn't exist or has expired
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and uses a multi-phase locking strategy:
    /// 1. **Read lock** for initial lookup (allows concurrent reads)
    /// 2. **Mutex + Write lock** for expired entry removal (if needed)
    /// 3. **Mutex lock** for order queue updates (for LRU/ARC/TLRU)
    ///
    /// Multiple threads can safely call this method concurrently. Read-heavy
    /// workloads benefit from RwLock's concurrent read capability.
    ///
    /// # Performance
    ///
    /// - **FIFO, Random**: O(1) - no reordering needed
    /// - **LRU, ARC, TLRU**: O(n) - requires finding and moving key in order queue
    /// - **LFU**: O(1) - only increments counter
    /// - **Lock overhead**: Read lock for lookup + potential write lock for updates
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Insert and retrieve
    /// cache.insert("user:123", user_data);
    /// assert_eq!(cache.get("user:123"), Some(user_data));
    ///
    /// // Non-existent key
    /// assert_eq!(cache.get("user:999"), None);
    ///
    /// // Expired entry (with TTL)
    /// cache.insert("temp", data);
    /// std::thread::sleep(Duration::from_secs(61)); // Wait for TTL expiration
    /// assert_eq!(cache.get("temp"), None);
    /// ```
    pub fn get(&self, key: &str) -> Option<R> {
        let mut result = None;
        let mut expired = false;

        // Acquire read lock - allows concurrent reads
        {
            let m = self.map.read();
            if let Some(entry) = m.get(key) {
                if entry.is_expired(self.ttl) {
                    expired = true;
                } else {
                    result = Some(entry.value.clone());
                }
            }
        } // Read lock released here

        if expired {
            // Acquiring order lock to modify order queue
            let mut o = self.order.lock();
            // Acquire write lock to modify the map
            let mut map_write = self.map.write();
            remove_key_from_global_cache(&mut map_write, &mut o, key);
            #[cfg(feature = "stats")]
            self.stats.record_miss();
            return None;
        }

        // Record stats
        #[cfg(feature = "stats")]
        {
            if result.is_some() {
                self.stats.record_hit();
            } else {
                self.stats.record_miss();
            }
        }

        // Update access patterns based on policy
        if result.is_some() {
            match self.policy {
                EvictionPolicy::LRU => {
                    // Move key to end of order queue (most recently used)
                    move_key_to_end(&mut self.order.lock(), key);
                }
                EvictionPolicy::LFU => {
                    // Increment frequency counter
                    self.increment_frequency(key);
                }
                EvictionPolicy::ARC => {
                    // Adaptive Replacement: Update both recency (LRU) and frequency (LFU)
                    // Move key to end (recency) - lock is automatically released after this call
                    move_key_to_end(&mut self.order.lock(), key);
                    // Increment frequency counter
                    self.increment_frequency(key);
                }
                EvictionPolicy::TLRU => {
                    // Time-aware LRU: Update both recency and frequency
                    // Similar to ARC but considers age in eviction
                    move_key_to_end(&mut self.order.lock(), key);
                    self.increment_frequency(key);
                }
                EvictionPolicy::WTinyLFU => {
                    // Simplified W-TinyLFU: Behaves like a hybrid of LRU and LFU
                    // Full implementation with Count-Min Sketch would require additional state
                    // For now, update both position (LRU) and frequency (LFU)
                    move_key_to_end(&mut self.order.lock(), key);
                    self.increment_frequency(key);
                }
                EvictionPolicy::FIFO | EvictionPolicy::Random => {
                    // No update needed for FIFO or Random
                }
            }
        }

        result
    }

    /// Increments the frequency counter for the specified key.
    fn increment_frequency(&self, key: &str) {
        let mut m = self.map.write();
        if let Some(entry) = m.get_mut(key) {
            entry.increment_frequency();
        }
    }

    /// Inserts or updates a value in the cache.
    ///
    /// This method stores a new value in the cache or updates an existing one.
    /// It handles cache limit enforcement and eviction according to the configured policy.
    ///
    /// # Parameters
    ///
    /// * `key` - The cache key
    /// * `value` - The value to cache
    ///
    /// # Behavior
    ///
    /// 1. Creates a new `CacheEntry` with the current timestamp
    /// 2. Inserts/updates the entry in the map
    /// 3. Updates the order queue:
    ///    - If key already exists in queue, removes old position
    ///    - Adds key to the end of the queue
    /// 4. Enforces cache limit:
    ///    - If limit is set and exceeded, evicts the oldest entry (front of queue)
    ///    - Removes evicted entry from both map and order queue
    ///
    /// # Eviction Policies
    ///
    /// When the cache limit is reached, entries are evicted according to the policy:
    /// - **FIFO**: Evicts oldest inserted entry (front of queue)
    /// - **LRU**: Evicts least recently used entry (front of queue, updated by `get()`)
    /// - **LFU**: Evicts entry with lowest frequency counter
    /// - **ARC**: Evicts based on hybrid score (frequency × position_weight)
    /// - **Random**: Evicts randomly selected entry
    /// - **TLRU**: Evicts based on TLRU score (frequency^weight × position × age_factor)
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and uses mutex locks to ensure consistency
    /// between the map and order queue.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Insert a value
    /// cache.insert("user:123", user_data);
    ///
    /// // Update existing value
    /// cache.insert("user:123", updated_user_data);
    ///
    /// // With limit=2, this will evict the oldest entry
    /// cache.insert("user:456", another_user);
    /// cache.insert("user:789", yet_another_user); // Evicts first entry
    /// ```
    ///
    /// # Note
    ///
    /// This method does NOT require `MemoryEstimator` trait. It only handles entry-count limits.
    /// If `max_memory` is configured, use `insert_with_memory()` instead, which requires
    /// the type to implement `MemoryEstimator`.
    pub fn insert(&self, key: &str, value: R) {
        let key_s = key.to_string();
        let entry = CacheEntry::new(value);

        // Acquire write lock for modification
        self.map.write().insert(key_s.clone(), entry);

        let mut o = self.order.lock();
        if let Some(pos) = o.iter().position(|k| *k == key_s) {
            o.remove(pos);
        }
        o.push_back(key_s.clone());

        // Always handle entry-count limits, regardless of memory limits
        self.handle_entry_limit_eviction(&mut o);
    }

    /// Handles the eviction of entries from a global cache when the number of entries exceeds the limit.
    ///
    /// The eviction behavior depends on the specified eviction policy. The function ensures that the cache
    /// adheres to the defined entry limit by evicting entries based on the configured policy:
    ///
    /// - **LFU (Least Frequently Used):** Finds and evicts the entry with the minimum frequency of usage.
    /// - **ARC (Adaptive Replacement Cache):** Leverages the ARC eviction strategy to find and evict a specific entry.
    /// - **FIFO (First In First Out):** Evicts the oldest entry in the queue to ensure the limit is maintained.
    /// - **LRU (Least Recently Used):** Evicts the least recently accessed entry from the queue.
    ///
    /// # Parameters
    ///
    /// - `o`: A mutable reference to a `MutexGuard` that holds a `VecDeque<String>`.
    ///   This represents the global cache where entries are stored.
    ///
    /// # Behavior
    ///
    /// 1. **Check Limit:** The function first checks if the `limit` is defined and if the length of the
    ///    cache (`o`) exceeds the defined `limit`.
    ///
    /// 2. **Eviction By Policy:** Based on the configured `EvictionPolicy`, different eviction strategies
    ///    are employed:
    ///
    ///   - **LFU:** The method identifies the key with the minimum frequency count by inspecting the
    ///     associated frequency map and removes it from the cache.
    ///   - **ARC:** Uses an ARC strategy to determine which key should be evicted and removes it from the cache.
    ///   - **FIFO or LRU:** Dequeues entries in sequence (from the front of the queue) and checks if the
    ///     entry still exists in the global cache. If found, the entry is removed from both the queue and cache.
    ///
    /// 3. **Thread-Safe Access:** The function ensures thread-safe read/write access to the cache and
    ///    associated data structures using mutexes.
    fn handle_entry_limit_eviction(&self, mut o: &mut MutexGuard<RawMutex, VecDeque<String>>) {
        if let Some(limit) = self.limit {
            if o.len() > limit {
                match self.policy {
                    EvictionPolicy::LFU => {
                        // Find and evict the entry with the minimum frequency
                        let mut map_write = self.map.write();
                        let min_freq_key = find_min_frequency_key(&map_write, &o);

                        if let Some(evict_key) = min_freq_key {
                            remove_key_from_global_cache(&mut map_write, &mut o, &evict_key);
                        }
                    }
                    EvictionPolicy::ARC => {
                        let mut map_write = self.map.write();
                        if let Some(evict_key) =
                            find_arc_eviction_key(&map_write, o.iter().enumerate())
                        {
                            remove_key_from_global_cache(&mut map_write, &mut o, &evict_key);
                        }
                    }
                    EvictionPolicy::TLRU => {
                        let mut map_write = self.map.write();
                        if let Some(evict_key) = find_tlru_eviction_key(
                            &map_write,
                            o.iter().enumerate(),
                            self.ttl,
                            self.frequency_weight,
                        ) {
                            remove_key_from_global_cache(&mut map_write, &mut o, &evict_key);
                        }
                    }
                    EvictionPolicy::WTinyLFU => {
                        // W-TinyLFU: Window segment (first entries) + Protected segment (rest)
                        let window_ratio = self.window_ratio.unwrap_or(0.20); // Default 20%
                        let window_size = crate::utils::calculate_window_size(limit, window_ratio);

                        let mut map_write = self.map.write();

                        if o.len() <= window_size {
                            // Everything is in window segment - evict FIFO
                            while let Some(evict_key) = o.pop_front() {
                                if map_write.contains_key(&evict_key) {
                                    map_write.remove(&evict_key);
                                    break;
                                }
                            }
                        } else {
                            // We have both window and protected segments
                            let mut evicted = false;

                            // Try to evict from window first (first window_size entries)
                            for i in 0..window_size.min(o.len()) {
                                if let Some(evict_key) = o.get(i) {
                                    if map_write.contains_key(evict_key) {
                                        let key_to_remove = evict_key.clone();
                                        map_write.remove(&key_to_remove);
                                        o.remove(i);
                                        evicted = true;
                                        break;
                                    }
                                }
                            }

                            // If window eviction failed, evict from protected (LFU)
                            if !evicted {
                                // Protected segment is from window_size to end
                                let protected_keys: VecDeque<String> =
                                    o.iter().skip(window_size).cloned().collect();

                                if let Some(evict_key) =
                                    find_min_frequency_key(&map_write, &protected_keys)
                                {
                                    remove_key_from_global_cache(
                                        &mut map_write,
                                        &mut o,
                                        &evict_key,
                                    );
                                }
                            }
                        }
                    }
                    EvictionPolicy::Random => {
                        // O(1) random eviction: select random position and remove directly
                        if !o.is_empty() {
                            let pos = fastrand::usize(..o.len());
                            if let Some(evict_key) = o.remove(pos) {
                                let mut map_write = self.map.write();
                                map_write.remove(&evict_key);
                            }
                        }
                    }
                    EvictionPolicy::FIFO | EvictionPolicy::LRU => {
                        // Keep trying to evict until we find a valid entry or queue is empty
                        let mut map_write = self.map.write();
                        while let Some(evict_key) = o.pop_front() {
                            // Check if the key still exists in the cache before removing
                            if map_write.contains_key(&evict_key) {
                                map_write.remove(&evict_key);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
}

// Separate implementation for types that implement MemoryEstimator
// This allows memory-based eviction
impl<R: Clone + 'static + crate::MemoryEstimator> GlobalCache<R> {
    /// Insert with memory limit support.
    ///
    /// This method requires `R` to implement `MemoryEstimator` and handles both
    /// memory-based and entry-count-based eviction.
    ///
    /// Use this method when `max_memory` is configured in the cache.
    ///
    /// # Arguments
    ///
    /// * `key` - The cache key
    /// * `value` - The value to cache (must implement `MemoryEstimator`)
    ///
    /// # Memory Management
    ///
    /// The method calculates the memory footprint of all cached entries and evicts
    /// entries as needed to stay within the `max_memory` limit. Eviction follows
    /// the configured policy.
    ///
    /// # Safety Check
    ///
    /// If the value to be inserted is larger than `max_memory`, the insertion is
    /// skipped entirely to avoid infinite eviction loops. This ensures the cache
    /// respects the memory limit even if individual values are very large.
    ///
    /// # Eviction Behavior by Policy
    ///
    /// When memory limit is exceeded:
    /// - **FIFO/LRU**: Evicts from front of order queue
    /// - **LFU**: Evicts entry with lowest frequency
    /// - **ARC**: Evicts based on hybrid score (frequency × position_weight)
    /// - **TLRU**: Evicts based on TLRU score (frequency^weight × position × age_factor)
    /// - **Random**: Evicts randomly selected entry
    ///
    /// The eviction loop continues until there's enough memory for the new value.
    ///
    /// # Entry Count Limit
    ///
    /// After satisfying memory constraints, this method also checks the entry count
    /// limit (if configured) and evicts additional entries if needed.
    ///
    /// # Thread Safety
    ///
    /// This method uses write locks to ensure consistency between the map and
    /// order queue during eviction and insertion.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cachelito_core::MemoryEstimator;
    ///
    /// // Type must implement MemoryEstimator
    /// impl MemoryEstimator for MyLargeStruct {
    ///     fn estimate_memory(&self) -> usize {
    ///         std::mem::size_of::<Self>() + self.data.capacity()
    ///     }
    /// }
    ///
    /// // Insert with automatic memory-based eviction
    /// cache.insert_with_memory("large_data", expensive_value);
    /// ```
    ///
    /// # Performance
    ///
    /// - **Memory calculation**: O(n) - iterates all entries to sum memory
    /// - **Eviction**: Varies by policy (see individual policy documentation)
    /// - May evict multiple entries in one call if memory limit is tight
    pub fn insert_with_memory(&self, key: &str, value: R) {
        let key_s = key.to_string();
        let entry = CacheEntry::new(value);

        // Acquire write lock for modification
        self.map.write().insert(key_s.clone(), entry);

        let mut o = self.order.lock();
        if let Some(pos) = o.iter().position(|k| *k == key_s) {
            o.remove(pos);
        }
        o.push_back(key_s.clone());

        // Check memory limit first (if specified)
        if let Some(max_mem) = self.max_memory {
            // First, check if the new value by itself exceeds max_mem
            // This is a safety check to prevent infinite eviction loop
            let new_value_size = {
                let map_read = self.map.read();
                map_read
                    .get(&key_s)
                    .map(|e| e.value.estimate_memory())
                    .unwrap_or(0)
            };

            if new_value_size > max_mem {
                // The value itself is too large for the cache
                // Remove it and return early to respect memory limit
                self.map.write().remove(&key_s);
                o.pop_back(); // Remove from order queue as well
                return;
            }

            loop {
                let current_mem = {
                    let map_read = self.map.read();
                    map_read
                        .values()
                        .map(|e| e.value.estimate_memory())
                        .sum::<usize>()
                };

                if current_mem <= max_mem {
                    break;
                }

                // Need to evict based on policy
                let evicted = match self.policy {
                    EvictionPolicy::LFU => {
                        let mut map_write = self.map.write();
                        let min_freq_key = find_min_frequency_key(&map_write, &o);
                        if let Some(evict_key) = min_freq_key {
                            remove_key_from_global_cache(&mut map_write, &mut o, &evict_key);
                            true
                        } else {
                            false
                        }
                    }
                    EvictionPolicy::ARC => {
                        let mut map_write = self.map.write();
                        if let Some(evict_key) =
                            find_arc_eviction_key(&map_write, o.iter().enumerate())
                        {
                            remove_key_from_global_cache(&mut map_write, &mut o, &evict_key);
                            true
                        } else {
                            false
                        }
                    }
                    EvictionPolicy::TLRU => {
                        let mut map_write = self.map.write();
                        if let Some(evict_key) = find_tlru_eviction_key(
                            &map_write,
                            o.iter().enumerate(),
                            self.ttl,
                            self.frequency_weight,
                        ) {
                            remove_key_from_global_cache(&mut map_write, &mut o, &evict_key);
                            true
                        } else {
                            false
                        }
                    }
                    EvictionPolicy::WTinyLFU => {
                        // Simplified W-TinyLFU: Use LFU-like eviction
                        // Full implementation would use window segment + Count-Min Sketch
                        let mut map_write = self.map.write();
                        if let Some(evict_key) = find_min_frequency_key(&map_write, &o) {
                            remove_key_from_global_cache(&mut map_write, &mut o, &evict_key);
                            true
                        } else {
                            false
                        }
                    }
                    EvictionPolicy::Random => {
                        // O(1) random eviction: select random position and remove directly
                        if !o.is_empty() {
                            let pos = fastrand::usize(..o.len());
                            if let Some(evict_key) = o.remove(pos) {
                                let mut map_write = self.map.write();
                                map_write.remove(&evict_key);
                                true
                            } else {
                                false
                            }
                        } else {
                            false
                        }
                    }
                    EvictionPolicy::FIFO | EvictionPolicy::LRU => {
                        // Ensure we only count as evicted if we actually remove from the map
                        let mut successfully_evicted = false;
                        let mut map_write = self.map.write();
                        while let Some(evict_key) = o.pop_front() {
                            if map_write.contains_key(&evict_key) {
                                map_write.remove(&evict_key);
                                successfully_evicted = true;
                                break;
                            }
                            // If key wasn't in map (orphan), continue popping until we remove a real one
                        }
                        successfully_evicted
                    }
                };

                if !evicted {
                    break; // Nothing left to evict
                }
            }
        }

        // Handle entry-count limits
        self.handle_entry_limit_eviction(&mut o);
    }

    /// Returns a reference to the cache statistics.
    ///
    /// This method is only available when the `stats` feature is enabled.
    ///
    /// # Available Metrics
    ///
    /// The returned CacheStats provides:
    /// - **hits()**: Number of successful cache lookups
    /// - **misses()**: Number of cache misses (key not found or expired)
    /// - **hit_rate()**: Ratio of hits to total accesses (0.0 to 1.0)
    /// - **total_accesses()**: Total number of get operations
    ///
    /// # Thread Safety
    ///
    /// Statistics use atomic counters (`AtomicU64`) and can be safely accessed
    /// from multiple threads without additional synchronization.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Get basic statistics
    /// let stats = cache.stats();
    /// println!("Hits: {}", stats.hits());
    /// println!("Misses: {}", stats.misses());
    /// println!("Hit rate: {:.2}%", stats.hit_rate() * 100.0);
    /// println!("Total accesses: {}", stats.total_accesses());
    ///
    /// // Monitor cache performance
    /// let total = stats.total_accesses();
    /// if total > 1000 && stats.hit_rate() < 0.5 {
    ///     println!("Warning: Low cache hit rate");
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// - [`CacheStats`] - The statistics structure
    /// - [`crate::stats_registry::get()`] - Access stats by cache name
    #[cfg(feature = "stats")]
    pub fn stats(&self) -> &CacheStats {
        self.stats
    }

    /// Clears all entries from the cache.
    ///
    /// This method removes all entries from both the cache map and the order queue.
    /// It's useful for testing or when you need to completely reset the cache state.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be safely called from multiple threads.
    ///
    /// # Example
    ///
    /// ```ignore
    /// cache.insert("key1", 42);
    /// cache.insert("key2", 84);
    ///
    /// cache.clear();
    ///
    /// assert_eq!(cache.get("key1"), None);
    /// assert_eq!(cache.get("key2"), None);
    /// ```
    pub fn clear(&self) {
        self.map.write().clear();
        self.order.lock().clear();
    }
}

/// Implementation of `GlobalCache` for `Result` types.
///
/// This specialized implementation provides a `insert_result` method that only
/// caches successful (`Ok`) results, preventing error values from being cached.
///
/// # Type Parameters
///
/// * `T` - The success type, must be `Clone` and `Debug`
/// * `E` - The error type, must be `Clone` and `Debug`
///
/// # Rationale
///
/// Errors are typically transient (network failures, temporary resource unavailability)
/// and should not be cached. Only successful results should be memoized to avoid
/// repeatedly returning stale errors.
///
/// # Example
///
/// ```ignore
/// let cache: GlobalCache<Result<String, Error>> = GlobalCache::new(...);
///
/// // Only Ok values are cached
/// let result = fetch_data();
/// cache.insert_result("key1", &result);
///
/// // If result was Err, nothing is cached
/// // If result was Ok, the value is cached
/// ```
impl<T: Clone + Debug + 'static, E: Clone + Debug + 'static> GlobalCache<Result<T, E>> {
    /// Inserts a Result into the cache, but only if it's an `Ok` variant.
    ///
    /// This method intelligently caches only successful results, preventing
    /// error values from polluting the cache.
    ///
    /// This version does NOT require MemoryEstimator. Use `insert_result_with_memory()`
    /// when max_memory is configured.
    ///
    /// # Parameters
    ///
    /// * `key` - The cache key
    /// * `value` - The Result to potentially cache
    ///
    /// # Behavior
    ///
    /// - If `value` is `Ok(v)`: Caches `Ok(v.clone())` under the given key
    /// - If `value` is `Err(_)`: Does nothing, no cache entry is created
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads.
    ///
    /// # Example
    ///
    /// ```ignore
    /// fn fetch_user(id: u64) -> Result<User, DbError> {
    ///     // ... database query ...
    /// }
    ///
    /// let result = fetch_user(123);
    /// cache.insert_result("user:123", &result);
    ///
    /// // Success: cached
    /// // Ok(user) -> cache contains Ok(user)
    ///
    /// // Failure: not cached (will retry next time)
    /// // Err(db_error) -> cache remains empty for this key
    /// ```
    pub fn insert_result(&self, key: &str, value: &Result<T, E>) {
        if let Ok(v) = value {
            self.insert(key, Ok(v.clone()));
        }
    }
}

/// Implementation of `GlobalCache` for `Result` types WITH MemoryEstimator support.
///
/// This specialized implementation provides memory-aware caching for Result types.
///
/// # Type Parameters
///
/// * `T` - The success type, must be `Clone`, `Debug`, and implement `MemoryEstimator`
/// * `E` - The error type, must be `Clone`, `Debug`, and implement `MemoryEstimator`
impl<
        T: Clone + Debug + 'static + crate::MemoryEstimator,
        E: Clone + Debug + 'static + crate::MemoryEstimator,
    > GlobalCache<Result<T, E>>
{
    /// Inserts a Result into the cache with memory limit support.
    ///
    /// This method requires both T and E to implement MemoryEstimator.
    /// Use this when max_memory is configured.
    ///
    /// # Parameters
    ///
    /// * `key` - The cache key
    /// * `value` - The Result to potentially cache
    ///
    /// # Behavior
    ///
    /// - If `value` is `Ok(v)`: Caches `Ok(v.clone())` under the given key
    /// - If `value` is `Err(_)`: Does nothing, no cache entry is created
    pub fn insert_result_with_memory(&self, key: &str, value: &Result<T, E>) {
        if let Ok(v) = value {
            self.insert_with_memory(key, Ok(v.clone()));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time::Duration;

    #[test]
    fn test_global_basic_insert_get() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));
        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("key1", 100);
        assert_eq!(cache.get("key1"), Some(100));
    }

    #[test]
    fn test_global_missing_key() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        assert_eq!(cache.get("nonexistent"), None);
    }

    #[test]
    fn test_global_update_existing() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("key", 1);
        cache.insert("key", 2);
        assert_eq!(cache.get("key"), Some(2));
    }

    #[test]
    fn test_global_fifo_eviction() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(2),
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("k1", 1);
        cache.insert("k2", 2);
        cache.insert("k3", 3);

        assert_eq!(cache.get("k1"), None);
        assert_eq!(cache.get("k2"), Some(2));
        assert_eq!(cache.get("k3"), Some(3));
    }

    #[test]
    fn test_global_lru_eviction() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(2),
            None,
            EvictionPolicy::LRU,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("k1", 1);
        cache.insert("k2", 2);
        let _ = cache.get("k1");
        cache.insert("k3", 3);

        assert_eq!(cache.get("k1"), Some(1));
        assert_eq!(cache.get("k2"), None);
        assert_eq!(cache.get("k3"), Some(3));
    }

    #[test]
    fn test_global_lru_multiple_accesses() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(3),
            None,
            EvictionPolicy::LRU,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("k1", 1);
        cache.insert("k2", 2);
        cache.insert("k3", 3);

        // Access k1 to make it most recent
        let _ = cache.get("k1");
        let _ = cache.get("k1");

        // k2 should be evicted (least recently used)
        cache.insert("k4", 4);

        assert_eq!(cache.get("k1"), Some(1));
        assert_eq!(cache.get("k2"), None);
        assert_eq!(cache.get("k3"), Some(3));
        assert_eq!(cache.get("k4"), Some(4));
    }

    #[test]
    fn test_global_thread_safety() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let handles: Vec<_> = (0..10)
            .map(|i| {
                thread::spawn(move || {
                    let cache = GlobalCache::new(
                        &MAP,
                        &ORDER,
                        None,
                        None,
                        EvictionPolicy::FIFO,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        #[cfg(feature = "stats")]
                        &STATS,
                    );
                    cache.insert(&format!("key{}", i), i);
                    thread::sleep(Duration::from_millis(10));
                    cache.get(&format!("key{}", i))
                })
            })
            .collect();

        for (i, handle) in handles.into_iter().enumerate() {
            let result = handle.join().unwrap();
            assert_eq!(result, Some(i as i32));
        }
    }

    #[test]
    fn test_global_ttl_expiration() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            Some(1),
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("expires", 999);

        // Should be valid immediately
        assert_eq!(cache.get("expires"), Some(999));

        thread::sleep(Duration::from_secs(2));

        // Should be expired now
        assert_eq!(cache.get("expires"), None);
    }

    #[test]
    fn test_global_result_ok() {
        static RES_MAP: Lazy<RwLock<HashMap<String, CacheEntry<Result<i32, String>>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static RES_ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));
        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &RES_MAP,
            &RES_ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        let ok_result = Ok(42);
        cache.insert_result("success", &ok_result);
        assert_eq!(cache.get("success"), Some(Ok(42)));
    }

    #[test]
    fn test_global_result_err() {
        static RES_MAP: Lazy<RwLock<HashMap<String, CacheEntry<Result<i32, String>>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static RES_ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));
        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &RES_MAP,
            &RES_ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        let err_result: Result<i32, String> = Err("error".to_string());
        cache.insert_result("failure", &err_result);
        assert_eq!(cache.get("failure"), None); // Errors not cached
    }

    #[test]
    fn test_global_concurrent_lru_access() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(5),
            None,
            EvictionPolicy::LRU,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        // Pre-populate cache
        for i in 0..5 {
            cache.insert(&format!("k{}", i), i);
        }

        // Concurrent access to k0
        let handles: Vec<_> = (0..5)
            .map(|_| {
                thread::spawn(|| {
                    let cache = GlobalCache::new(
                        &MAP,
                        &ORDER,
                        Some(5),
                        None,
                        EvictionPolicy::LRU,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        #[cfg(feature = "stats")]
                        &STATS,
                    );
                    for _ in 0..10 {
                        let _ = cache.get("k0");
                    }
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }

        // k0 should still be in cache (frequently accessed)
        assert_eq!(cache.get("k0"), Some(0));
    }

    #[test]
    fn test_global_no_limit() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        for i in 0..100 {
            cache.insert(&format!("k{}", i), i);
        }

        // All should still be present
        for i in 0..100 {
            assert_eq!(cache.get(&format!("k{}", i)), Some(i));
        }
    }

    #[test]
    fn test_memory_eviction_skips_orphan_and_removes_real_entry() {
        // Shared structures
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        // max_memory allows only a single i32 (size 4)
        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            Some(std::mem::size_of::<i32>()),
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        // Insert first real entry
        cache.insert_with_memory("k1", 1i32);

        // Introduce an orphan key at the front of the order queue
        {
            let mut o = ORDER.lock();
            o.push_front("orphan".to_string());
        }

        // Insert second entry which forces memory eviction
        cache.insert_with_memory("k2", 2i32);

        // The orphan should be ignored for memory purposes and a real key should be evicted.
        // Expect k1 to be evicted and k2 to remain.
        assert_eq!(cache.get("k1"), None);
        assert_eq!(cache.get("k2"), Some(2));

        // Ensure the orphan key is gone from the order
        let order_contents: Vec<String> = {
            let o = ORDER.lock();
            o.iter().cloned().collect()
        };
        assert!(order_contents.iter().all(|k| k != "orphan"));
    }

    /// Test RwLock allows concurrent reads (no blocking)
    #[test]
    fn test_rwlock_concurrent_reads() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        // Populate cache
        for i in 0..10 {
            cache.insert(&format!("key{}", i), i);
        }

        // Spawn many threads reading concurrently
        let handles: Vec<_> = (0..20)
            .map(|_thread_id| {
                thread::spawn(move || {
                    let cache = GlobalCache::new(
                        &MAP,
                        &ORDER,
                        None,
                        None,
                        EvictionPolicy::FIFO,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        #[cfg(feature = "stats")]
                        &STATS,
                    );
                    let mut results = Vec::new();
                    for i in 0..10 {
                        results.push(cache.get(&format!("key{}", i)));
                    }
                    results
                })
            })
            .collect();

        // All threads should complete without blocking
        for handle in handles {
            let results = handle.join().unwrap();
            for (i, result) in results.iter().enumerate() {
                assert_eq!(*result, Some(i as i32));
            }
        }
    }

    /// Test RwLock write blocks reads temporarily
    #[test]
    fn test_rwlock_write_excludes_reads() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        cache.insert("key1", 100);

        // Write and read interleaved - should not deadlock
        let write_handle = thread::spawn(|| {
            let cache = GlobalCache::new(
                &MAP,
                &ORDER,
                None,
                None,
                EvictionPolicy::FIFO,
                None,
                None,
                None,
                None,
                None,
                None,
                #[cfg(feature = "stats")]
                &STATS,
            );
            for i in 0..50 {
                cache.insert(&format!("key{}", i), i);
                thread::sleep(Duration::from_micros(100));
            }
        });

        let read_handles: Vec<_> = (0..5)
            .map(|_| {
                thread::spawn(|| {
                    let cache = GlobalCache::new(
                        &MAP,
                        &ORDER,
                        None,
                        None,
                        EvictionPolicy::FIFO,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        #[cfg(feature = "stats")]
                        &STATS,
                    );
                    for i in 0..50 {
                        let _ = cache.get(&format!("key{}", i));
                        thread::sleep(Duration::from_micros(100));
                    }
                })
            })
            .collect();

        write_handle.join().unwrap();
        for handle in read_handles {
            handle.join().unwrap();
        }
    }

    #[test]
    #[cfg(feature = "stats")]
    fn test_global_stats_basic() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("k1", 1);
        cache.insert("k2", 2);

        let _ = cache.get("k1"); // Hit
        let _ = cache.get("k2"); // Hit
        let _ = cache.get("k3"); // Miss

        let stats = cache.stats();
        assert_eq!(stats.hits(), 2);
        assert_eq!(stats.misses(), 1);
        assert_eq!(stats.total_accesses(), 3);
        assert!((stats.hit_rate() - 0.6666).abs() < 0.001);
    }

    #[test]
    #[cfg(feature = "stats")]
    fn test_global_stats_expired_counts_as_miss() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            Some(1),
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("expires", 999);

        // Immediate access - should be a hit
        let _ = cache.get("expires");
        assert_eq!(cache.stats().hits(), 1);
        assert_eq!(cache.stats().misses(), 0);

        // Wait for expiration
        thread::sleep(Duration::from_secs(2));

        // Access after expiration - should be a miss
        let _ = cache.get("expires");
        assert_eq!(cache.stats().hits(), 1);
        assert_eq!(cache.stats().misses(), 1);
    }

    #[test]
    #[cfg(feature = "stats")]
    fn test_global_stats_reset() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("k1", 1);
        let _ = cache.get("k1");
        let _ = cache.get("k2");

        let stats = cache.stats();
        assert_eq!(stats.hits(), 1);
        assert_eq!(stats.misses(), 1);

        stats.reset();
        assert_eq!(stats.hits(), 0);
        assert_eq!(stats.misses(), 0);
    }

    #[test]
    #[cfg(feature = "stats")]
    fn test_global_stats_concurrent_access() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("k1", 1);
        cache.insert("k2", 2);

        let handles: Vec<_> = (0..10)
            .map(|_| {
                thread::spawn(|| {
                    let cache = GlobalCache::new(
                        &MAP,
                        &ORDER,
                        None,
                        None,
                        EvictionPolicy::FIFO,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        #[cfg(feature = "stats")]
                        &STATS,
                    );
                    for _ in 0..10 {
                        let _ = cache.get("k1"); // Hit
                        let _ = cache.get("k2"); // Hit
                        let _ = cache.get("k3"); // Miss
                    }
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }

        let stats = cache.stats();
        // 10 threads * 10 iterations * 2 hits = 200 hits
        // 10 threads * 10 iterations * 1 miss = 100 misses
        assert_eq!(stats.hits(), 200);
        assert_eq!(stats.misses(), 100);
        assert_eq!(stats.total_accesses(), 300);
    }

    #[test]
    #[cfg(feature = "stats")]
    fn test_global_stats_all_hits() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );
        cache.insert("k1", 1);
        cache.insert("k2", 2);

        for _ in 0..10 {
            let _ = cache.get("k1");
            let _ = cache.get("k2");
        }

        let stats = cache.stats();
        assert_eq!(stats.hits(), 20);
        assert_eq!(stats.misses(), 0);
        assert_eq!(stats.hit_rate(), 1.0);
        assert_eq!(stats.miss_rate(), 0.0);
    }

    #[test]
    #[cfg(feature = "stats")]
    fn test_global_stats_all_misses() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            None,
            None,
            EvictionPolicy::FIFO,
            None,
            None,
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        for i in 0..10 {
            let _ = cache.get(&format!("k{}", i));
        }

        let stats = cache.stats();
        assert_eq!(stats.hits(), 0);
        assert_eq!(stats.misses(), 10);
        assert_eq!(stats.hit_rate(), 0.0);
        assert_eq!(stats.miss_rate(), 1.0);
    }

    // ========== TLRU with frequency_weight tests ==========

    #[test]
    fn test_tlru_with_low_frequency_weight() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        // Low frequency_weight (0.3) - emphasizes recency over frequency
        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(3),
            None,
            EvictionPolicy::TLRU,
            Some(10),
            Some(0.3), // Low weight
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        // Fill cache
        cache.insert("k1", 1);
        cache.insert("k2", 2);
        cache.insert("k3", 3);

        // Make k1 very frequent
        for _ in 0..10 {
            let _ = cache.get("k1");
        }

        // Wait a bit to age k1
        thread::sleep(Duration::from_millis(100));

        // Add new entry (cache is full)
        cache.insert("k4", 4);

        // With low frequency_weight, even frequent entries can be evicted
        // if they're older (recency and age matter more)
        assert_eq!(cache.get("k4"), Some(4));
    }

    #[test]
    fn test_tlru_with_high_frequency_weight() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        // High frequency_weight (1.5) - emphasizes frequency over recency
        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(3),
            None,
            EvictionPolicy::TLRU,
            Some(10),
            Some(1.5), // High weight
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        // Fill cache
        cache.insert("k1", 1);
        cache.insert("k2", 2);
        cache.insert("k3", 3);

        // Make k1 very frequent
        for _ in 0..10 {
            let _ = cache.get("k1");
        }

        // Wait a bit to age k1
        thread::sleep(Duration::from_millis(100));

        // Add new entry (cache is full)
        cache.insert("k4", 4);

        // With high frequency_weight, frequent entries are protected
        // k1 should remain cached despite being older
        assert_eq!(cache.get("k1"), Some(1));
        assert_eq!(cache.get("k4"), Some(4));
    }

    #[test]
    fn test_tlru_default_frequency_weight() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        // Default frequency_weight (None = 1.0) - balanced approach
        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(2),
            None,
            EvictionPolicy::TLRU,
            Some(5),
            None, // Default weight
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        cache.insert("k1", 1);
        cache.insert("k2", 2);

        // Access k1 a few times
        for _ in 0..3 {
            let _ = cache.get("k1");
        }

        // Add third entry
        cache.insert("k3", 3);

        // With balanced weight, both frequency and recency matter
        // k1 has higher frequency, so it should remain
        assert_eq!(cache.get("k1"), Some(1));
        assert_eq!(cache.get("k3"), Some(3));
    }

    #[test]
    fn test_tlru_frequency_weight_comparison() {
        // Test that different weights produce different behavior
        static MAP_LOW: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER_LOW: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        static MAP_HIGH: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER_HIGH: Lazy<Mutex<VecDeque<String>>> =
            Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS_LOW: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());
        #[cfg(feature = "stats")]
        static STATS_HIGH: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache_low = GlobalCache::new(
            &MAP_LOW,
            &ORDER_LOW,
            Some(2),
            None,
            EvictionPolicy::TLRU,
            Some(10),
            Some(0.3), // Low weight
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS_LOW,
        );

        let cache_high = GlobalCache::new(
            &MAP_HIGH,
            &ORDER_HIGH,
            Some(2),
            None,
            EvictionPolicy::TLRU,
            Some(10),
            Some(2.0), // High weight
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS_HIGH,
        );

        // Same operations on both caches
        cache_low.insert("k1", 1);
        cache_low.insert("k2", 2);
        cache_high.insert("k1", 1);
        cache_high.insert("k2", 2);

        // Make k1 frequent in both
        for _ in 0..5 {
            let _ = cache_low.get("k1");
            let _ = cache_high.get("k1");
        }

        thread::sleep(Duration::from_millis(50));

        // Add new entry to both
        cache_low.insert("k3", 3);
        cache_high.insert("k3", 3);

        // Both should work correctly with their respective weights
        assert_eq!(cache_low.get("k3"), Some(3));
        assert_eq!(cache_high.get("k3"), Some(3));
    }

    #[test]
    fn test_tlru_no_ttl_with_frequency_weight() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        // TLRU without TTL (behaves like ARC but with frequency_weight)
        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(3),
            None,
            EvictionPolicy::TLRU,
            None, // No TTL - age_factor will be 1.0
            Some(1.5),
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        cache.insert("k1", 1);
        cache.insert("k2", 2);
        cache.insert("k3", 3);

        // Make k1 very frequent
        for _ in 0..10 {
            let _ = cache.get("k1");
        }

        // Add new entry
        cache.insert("k4", 4);

        // Without TTL, TLRU focuses on frequency and position
        // k1 should remain due to high frequency
        assert_eq!(cache.get("k1"), Some(1));
    }

    #[test]
    fn test_tlru_concurrent_with_frequency_weight() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(5),
            None,
            EvictionPolicy::TLRU,
            Some(10),
            Some(1.2), // Slightly emphasize frequency
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        // Insert initial entries
        cache.insert("k1", 1);
        cache.insert("k2", 2);

        // Spawn multiple threads accessing the cache
        let handles: Vec<_> = (0..5)
            .map(|i| {
                thread::spawn(move || {
                    let cache = GlobalCache::new(
                        &MAP,
                        &ORDER,
                        Some(5),
                        None,
                        EvictionPolicy::TLRU,
                        Some(10),
                        Some(1.2),
                        None,
                        None,
                        None,
                        None,
                        #[cfg(feature = "stats")]
                        &STATS,
                    );

                    // Access k1 frequently
                    for _ in 0..3 {
                        let _ = cache.get("k1");
                    }

                    // Insert new entry
                    cache.insert(&format!("k{}", i + 3), i + 3);
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }

        // k1 should remain cached due to high frequency and frequency_weight > 1.0
        assert_eq!(cache.get("k1"), Some(1));
    }

    #[test]
    fn test_tlru_frequency_weight_edge_cases() {
        static MAP: Lazy<RwLock<HashMap<String, CacheEntry<i32>>>> =
            Lazy::new(|| RwLock::new(HashMap::new()));
        static ORDER: Lazy<Mutex<VecDeque<String>>> = Lazy::new(|| Mutex::new(VecDeque::new()));

        #[cfg(feature = "stats")]
        static STATS: Lazy<CacheStats> = Lazy::new(|| CacheStats::new());

        // Test with very low weight (close to 0)
        let cache = GlobalCache::new(
            &MAP,
            &ORDER,
            Some(2),
            None,
            EvictionPolicy::TLRU,
            Some(5),
            Some(0.1), // Very low weight
            None,
            None,
            None,
            None,
            #[cfg(feature = "stats")]
            &STATS,
        );

        cache.insert("k1", 1);
        cache.insert("k2", 2);

        // Make k1 extremely frequent
        for _ in 0..100 {
            let _ = cache.get("k1");
        }

        thread::sleep(Duration::from_millis(50));

        // Even with very high frequency, k1 might be evicted with very low weight
        cache.insert("k3", 3);

        // The cache should still work correctly
        assert!(cache.get("k3").is_some());
    }
}