ruchy 4.2.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
//! Unified quality scoring system for Ruchy code (RUCHY-0810)
//! Incremental scoring architecture (RUCHY-0813)
use crate::frontend::ast::ExprKind;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
/// Analysis depth for quality scoring
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum AnalysisDepth {
    /// <100ms - AST metrics only
    Shallow,
    /// <1s - AST + type checking + basic flow
    Standard,
    /// <30s - Full property/mutation testing
    Deep,
}
/// Unified quality score with components
#[derive(Debug, Clone)]
pub struct QualityScore {
    pub value: f64, // 0.0-1.0 normalized score
    pub components: ScoreComponents,
    pub grade: Grade,        // Human-readable grade
    pub confidence: f64,     // Confidence in score accuracy
    pub cache_hit_rate: f64, // Percentage from cached analysis
}
/// Individual score components
#[derive(Debug, Clone)]
pub struct ScoreComponents {
    pub correctness: f64,     // 35% - Semantic correctness
    pub performance: f64,     // 25% - Runtime efficiency
    pub maintainability: f64, // 20% - Change resilience
    pub safety: f64,          // 15% - Memory/type safety
    pub idiomaticity: f64,    // 5%  - Language conventions
}
/// Human-readable grade boundaries
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Grade {
    APlus,  // [0.97, 1.00] - Ship to production
    A,      // [0.93, 0.97) - Ship with confidence
    AMinus, // [0.90, 0.93) - Ship with review
    BPlus,  // [0.87, 0.90) - Acceptable
    B,      // [0.83, 0.87) - Needs work
    BMinus, // [0.80, 0.83) - Minimum viable
    CPlus,  // [0.77, 0.80) - Technical debt
    C,      // [0.73, 0.77) - Refactor advised
    CMinus, // [0.70, 0.73) - Refactor required
    D,      // [0.60, 0.70) - Major issues
    F,      // [0.00, 0.60) - Fundamental problems
}
impl Grade {
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::scoring::Grade;
    ///
    /// let mut instance = Grade::new();
    /// let result = instance.from_score();
    /// // Verify behavior
    /// ```
    pub fn from_score(value: f64) -> Self {
        match value {
            v if v >= 0.97 => Grade::APlus,
            v if v >= 0.93 => Grade::A,
            v if v >= 0.90 => Grade::AMinus,
            v if v >= 0.87 => Grade::BPlus,
            v if v >= 0.83 => Grade::B,
            v if v >= 0.80 => Grade::BMinus,
            v if v >= 0.77 => Grade::CPlus,
            v if v >= 0.73 => Grade::C,
            v if v >= 0.70 => Grade::CMinus,
            v if v >= 0.60 => Grade::D,
            _ => Grade::F,
        }
    }

    /// Extract method: Convert grade to numeric rank for ordering - complexity: 6
    /// Reduces complexity of cmp function from 25 to 2
    pub fn to_rank(&self) -> u8 {
        use Grade::{AMinus, APlus, BMinus, BPlus, CMinus, CPlus, A, B, C, D, F};
        match self {
            F => 0,
            D => 1,
            CMinus => 2,
            C => 3,
            CPlus => 4,
            BMinus => 5,
            B => 6,
            BPlus => 7,
            AMinus => 8,
            A => 9,
            APlus => 10,
        }
    }
}
impl std::fmt::Display for Grade {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Grade::APlus => write!(f, "A+"),
            Grade::A => write!(f, "A"),
            Grade::AMinus => write!(f, "A-"),
            Grade::BPlus => write!(f, "B+"),
            Grade::B => write!(f, "B"),
            Grade::BMinus => write!(f, "B-"),
            Grade::CPlus => write!(f, "C+"),
            Grade::C => write!(f, "C"),
            Grade::CMinus => write!(f, "C-"),
            Grade::D => write!(f, "D"),
            Grade::F => write!(f, "F"),
        }
    }
}
/// Configuration for score weights
#[derive(Debug, Clone)]
pub struct ScoreConfig {
    pub correctness_weight: f64,
    pub performance_weight: f64,
    pub maintainability_weight: f64,
    pub safety_weight: f64,
    pub idiomaticity_weight: f64,
}
impl Default for ScoreConfig {
    fn default() -> Self {
        Self {
            correctness_weight: 0.35,
            performance_weight: 0.25,
            maintainability_weight: 0.20,
            safety_weight: 0.15,
            idiomaticity_weight: 0.05,
        }
    }
}
/// Cache key for scoring results
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CacheKey {
    pub file_path: PathBuf,
    pub content_hash: u64,
    pub depth: AnalysisDepth,
}
/// Cached scoring result with metadata
#[derive(Debug, Clone)]
pub struct CacheEntry {
    pub score: QualityScore,
    pub timestamp: SystemTime,
    pub dependencies: Vec<PathBuf>,
}
/// File dependency tracker
#[derive(Debug)]
pub struct DependencyTracker {
    /// Map of file -> files it depends on
    dependencies: HashMap<PathBuf, Vec<PathBuf>>,
    /// Map of file -> last modified time
    file_times: HashMap<PathBuf, SystemTime>,
}
impl Default for DependencyTracker {
    fn default() -> Self {
        Self::new()
    }
}
impl DependencyTracker {
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::scoring::DependencyTracker;
    ///
    /// let instance = DependencyTracker::new();
    /// // Verify behavior
    /// ```
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::scoring::DependencyTracker;
    ///
    /// let instance = DependencyTracker::new();
    /// // Verify behavior
    /// ```
    pub fn new() -> Self {
        Self {
            dependencies: HashMap::new(),
            file_times: HashMap::new(),
        }
    }
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::track_dependency;
    ///
    /// let result = track_dependency(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn track_dependency(&mut self, file: PathBuf, dependency: PathBuf) {
        self.dependencies.entry(file).or_default().push(dependency);
    }
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::scoring::DependencyTracker;
    ///
    /// let mut instance = DependencyTracker::new();
    /// let result = instance.is_stale();
    /// // Verify behavior
    /// ```
    pub fn is_stale(&self, file: &PathBuf) -> bool {
        if let Some(dependencies) = self.dependencies.get(file) {
            for dep in dependencies {
                if self.is_file_modified(dep) {
                    return true;
                }
            }
        }
        false
    }
    fn is_file_modified(&self, file: &PathBuf) -> bool {
        let Ok(metadata) = fs::metadata(file) else {
            return true;
        };
        let Ok(modified) = metadata.modified() else {
            return true;
        };
        if let Some(&cached_time) = self.file_times.get(file) {
            modified > cached_time
        } else {
            true
        }
    }
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::update_file_time;
    ///
    /// let result = update_file_time(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn update_file_time(&mut self, file: PathBuf) {
        if let Ok(metadata) = fs::metadata(&file) {
            if let Ok(modified) = metadata.modified() {
                self.file_times.insert(file, modified);
            }
        }
    }
}
/// Incremental scoring engine with caching
pub struct ScoreEngine {
    config: ScoreConfig,
    cache: HashMap<CacheKey, CacheEntry>,
    dependency_tracker: DependencyTracker,
}
impl ScoreEngine {
    pub fn new(config: ScoreConfig) -> Self {
        Self {
            config,
            cache: HashMap::new(),
            dependency_tracker: DependencyTracker::new(),
        }
    }
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::score;
    ///
    /// let result = score(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn score(&self, ast: &crate::frontend::ast::Expr, depth: AnalysisDepth) -> QualityScore {
        let components = match depth {
            AnalysisDepth::Shallow => Self::score_shallow(ast),
            AnalysisDepth::Standard => Self::score_standard(ast),
            AnalysisDepth::Deep => Self::score_deep(ast),
        };
        let value = self.calculate_weighted_score(&components);
        let grade = Grade::from_score(value);
        let confidence = Self::calculate_confidence(depth);
        QualityScore {
            value,
            components,
            grade,
            confidence,
            cache_hit_rate: 0.0, // No file path in legacy API
        }
    }
    /// Incremental scoring with file-based caching (RUCHY-0813)
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::score_incremental;
    ///
    /// let result = score_incremental("example");
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn score_incremental(
        &mut self,
        ast: &crate::frontend::ast::Expr,
        file_path: PathBuf,
        content: &str,
        depth: AnalysisDepth,
    ) -> QualityScore {
        let content_hash = Self::hash_content(content);
        let cache_key = CacheKey {
            file_path: file_path.clone(),
            content_hash,
            depth,
        };
        // Check cache first
        if let Some(entry) = self.cache.get(&cache_key) {
            if !self.dependency_tracker.is_stale(&file_path) {
                let mut score = entry.score.clone();
                score.cache_hit_rate = 1.0;
                return score;
            }
        }
        // Fast path for small files - skip complex analysis
        let start = std::time::Instant::now();
        let is_small_file = content.len() < 1024;
        let effective_depth = if is_small_file && depth != AnalysisDepth::Deep {
            AnalysisDepth::Shallow
        } else {
            depth
        };
        let components = match effective_depth {
            AnalysisDepth::Shallow => Self::score_shallow(ast),
            AnalysisDepth::Standard => Self::score_standard(ast),
            AnalysisDepth::Deep => Self::score_deep(ast),
        };
        let value = self.calculate_weighted_score(&components);
        let grade = Grade::from_score(value);
        let confidence = if is_small_file && depth != effective_depth {
            Self::calculate_confidence(effective_depth) * 0.9 // Slightly reduced confidence for fast path
        } else {
            Self::calculate_confidence(depth)
        };
        let elapsed = start.elapsed();
        let score = QualityScore {
            value,
            components,
            grade,
            confidence,
            cache_hit_rate: 0.0,
        };
        // Cache the result only if worth caching
        let is_worth_caching = elapsed > Duration::from_millis(10) || !is_small_file;
        if is_worth_caching {
            let entry = CacheEntry {
                score: score.clone(),
                timestamp: SystemTime::now(),
                dependencies: Self::extract_dependencies(ast),
            };
            self.cache.insert(cache_key, entry);
        }
        self.dependency_tracker.update_file_time(file_path);
        // Maintain cache if scoring took too long or cache is getting large
        if elapsed > Duration::from_millis(100) || self.cache.len() > 1000 {
            self.optimize_cache();
        }
        score
    }
    /// Progressive scoring that refines analysis depth based on time budget
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::score_progressive;
    ///
    /// let result = score_progressive("example");
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn score_progressive(
        &mut self,
        ast: &crate::frontend::ast::Expr,
        file_path: PathBuf,
        content: &str,
        time_budget: Duration,
    ) -> QualityScore {
        let start = std::time::Instant::now();
        // Start with shallow analysis
        let mut score =
            self.score_incremental(ast, file_path.clone(), content, AnalysisDepth::Shallow);
        if start.elapsed() < time_budget / 3 {
            // Upgrade to standard analysis
            score =
                self.score_incremental(ast, file_path.clone(), content, AnalysisDepth::Standard);
            if start.elapsed() < time_budget * 2 / 3 {
                // Upgrade to deep analysis
                score = self.score_incremental(ast, file_path, content, AnalysisDepth::Deep);
            }
        }
        score
    }
    fn hash_content(content: &str) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        content.hash(&mut hasher);
        hasher.finish()
    }
    fn extract_dependencies(_ast: &crate::frontend::ast::Expr) -> Vec<PathBuf> {
        // Extract import/use dependencies from AST
        // Implementation in RUCHY-0814 with type checker integration
        Vec::new()
    }
    fn optimize_cache(&mut self) {
        // Remove old cache entries to maintain <100ms performance
        let now = SystemTime::now();
        let cutoff = Duration::from_secs(300); // 5 minutes
        let max_entries = 500; // Maximum cache entries for performance
                               // First pass: Remove old entries
        self.cache.retain(|_, entry| {
            if let Ok(age) = now.duration_since(entry.timestamp) {
                age < cutoff
            } else {
                false
            }
        });
        // Second pass: If still too many entries, remove least recently used
        if self.cache.len() > max_entries {
            let mut entries: Vec<_> = self
                .cache
                .iter()
                .map(|(k, v)| (k.clone(), v.timestamp))
                .collect();
            entries.sort_by_key(|(_, timestamp)| *timestamp);
            let to_remove = self.cache.len() - max_entries;
            let keys_to_remove: Vec<_> = entries
                .iter()
                .take(to_remove)
                .map(|(k, _)| k.clone())
                .collect();
            for key in keys_to_remove {
                self.cache.remove(&key);
            }
        }
    }
    /// Clear all caches - useful for memory management
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::clear_cache;
    ///
    /// let result = clear_cache(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn clear_cache(&mut self) {
        self.cache.clear();
        self.dependency_tracker = DependencyTracker::new();
    }
    /// Get cache statistics
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::cache_stats;
    ///
    /// let result = cache_stats(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn cache_stats(&self) -> CacheStats {
        CacheStats {
            entries: self.cache.len(),
            memory_usage_estimate: self.cache.len() * 1024, // Rough estimate
        }
    }
    fn score_shallow(ast: &crate::frontend::ast::Expr) -> ScoreComponents {
        // Fast AST-only analysis (<100ms)
        let metrics = analyze_ast_metrics(ast);
        let correctness = 1.0;
        let mut performance = 1.0;
        let mut maintainability = 1.0;
        let safety = 1.0;
        let idiomaticity = 1.0;
        // Penalize high complexity
        if metrics.max_depth > 10 {
            maintainability *= 0.9;
        }
        if metrics.function_count > 50 {
            maintainability *= 0.95;
        }
        // Penalize deep nesting
        if metrics.max_nesting > 5 {
            performance *= 0.9;
            maintainability *= 0.9;
        }
        // Penalize excessive lines
        if metrics.line_count > 1000 {
            maintainability *= 0.95;
        }
        ScoreComponents {
            correctness,
            performance,
            maintainability,
            safety,
            idiomaticity,
        }
    }
    fn score_standard(ast: &crate::frontend::ast::Expr) -> ScoreComponents {
        // Standard analysis with type checking (<1s)
        let mut components = Self::score_shallow(ast);
        // Additional type-based analysis
        // Type checker integration in RUCHY-0814
        components.correctness *= 0.95;
        components.safety *= 0.95;
        components
    }
    fn score_deep(ast: &crate::frontend::ast::Expr) -> ScoreComponents {
        // Deep analysis with property testing (<30s)
        let mut components = Self::score_standard(ast);
        // Additional deep analysis
        // Property testing and mutation testing in RUCHY-0816
        components.correctness *= 0.98;
        components
    }
    fn calculate_weighted_score(&self, components: &ScoreComponents) -> f64 {
        components.correctness * self.config.correctness_weight
            + components.performance * self.config.performance_weight
            + components.maintainability * self.config.maintainability_weight
            + components.safety * self.config.safety_weight
            + components.idiomaticity * self.config.idiomaticity_weight
    }
    fn calculate_confidence(depth: AnalysisDepth) -> f64 {
        match depth {
            AnalysisDepth::Shallow => 0.6,
            AnalysisDepth::Standard => 0.8,
            AnalysisDepth::Deep => 0.95,
        }
    }
}
/// AST metrics for analysis
#[derive(Debug)]
struct AstMetrics {
    function_count: usize,
    max_depth: usize,
    max_nesting: usize,
    line_count: usize,
    cyclomatic_complexity: usize,
}
fn analyze_ast_metrics(ast: &crate::frontend::ast::Expr) -> AstMetrics {
    let mut metrics = AstMetrics {
        function_count: 0,
        max_depth: 0,
        max_nesting: 0,
        line_count: 0,
        cyclomatic_complexity: 1, // Base complexity
    };
    analyze_expr(ast, &mut metrics, 0, 0);
    metrics
}
fn analyze_expr(
    expr: &crate::frontend::ast::Expr,
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    metrics.max_depth = metrics.max_depth.max(depth);
    metrics.max_nesting = metrics.max_nesting.max(nesting);
    match &expr.kind {
        ExprKind::Function { body, .. } => analyze_function(body, metrics, depth),
        ExprKind::Block(exprs) => analyze_block(exprs, metrics, depth, nesting),
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => analyze_if(
            condition,
            then_branch,
            else_branch.as_deref(),
            metrics,
            depth,
            nesting,
        ),
        ExprKind::While {
            condition, body, ..
        } => analyze_while(condition, body, metrics, depth, nesting),
        ExprKind::For { iter, body, .. } => analyze_for(iter, body, metrics, depth, nesting),
        ExprKind::Match {
            expr: match_expr,
            arms,
        } => analyze_match(match_expr, arms, metrics, depth, nesting),
        _ => {}
    }
}

fn analyze_function(body: &crate::frontend::ast::Expr, metrics: &mut AstMetrics, depth: usize) {
    metrics.function_count += 1;
    analyze_expr(body, metrics, depth + 1, 0);
}

fn analyze_block(
    exprs: &[crate::frontend::ast::Expr],
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    for e in exprs {
        analyze_expr(e, metrics, depth + 1, nesting);
    }
}

fn analyze_if(
    condition: &crate::frontend::ast::Expr,
    then_branch: &crate::frontend::ast::Expr,
    else_branch: Option<&crate::frontend::ast::Expr>,
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    metrics.cyclomatic_complexity += 1;
    analyze_expr(condition, metrics, depth + 1, nesting + 1);
    analyze_expr(then_branch, metrics, depth + 1, nesting + 1);
    if let Some(else_expr) = else_branch {
        analyze_expr(else_expr, metrics, depth + 1, nesting + 1);
    }
}

fn analyze_while(
    condition: &crate::frontend::ast::Expr,
    body: &crate::frontend::ast::Expr,
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    metrics.cyclomatic_complexity += 1;
    analyze_expr(condition, metrics, depth + 1, nesting + 1);
    analyze_expr(body, metrics, depth + 1, nesting + 1);
}

fn analyze_for(
    iter: &crate::frontend::ast::Expr,
    body: &crate::frontend::ast::Expr,
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    metrics.cyclomatic_complexity += 1;
    analyze_expr(iter, metrics, depth + 1, nesting + 1);
    analyze_expr(body, metrics, depth + 1, nesting + 1);
}

fn analyze_match(
    match_expr: &crate::frontend::ast::Expr,
    arms: &[crate::frontend::ast::MatchArm],
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    analyze_expr(match_expr, metrics, depth + 1, nesting);
    for arm in arms {
        metrics.cyclomatic_complexity += 1;
        analyze_expr(&arm.body, metrics, depth + 1, nesting + 1);
    }
}
impl QualityScore {
    /// Explain changes from a baseline score
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::explain_delta;
    ///
    /// let result = explain_delta(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn explain_delta(&self, baseline: &QualityScore) -> ScoreExplanation {
        let delta = self.value - baseline.value;
        let mut changes = Vec::new();
        let mut tradeoffs = Vec::new();
        // Track component changes
        let components = [
            (
                "Correctness",
                self.components.correctness,
                baseline.components.correctness,
            ),
            (
                "Performance",
                self.components.performance,
                baseline.components.performance,
            ),
            (
                "Maintainability",
                self.components.maintainability,
                baseline.components.maintainability,
            ),
            ("Safety", self.components.safety, baseline.components.safety),
            (
                "Idiomaticity",
                self.components.idiomaticity,
                baseline.components.idiomaticity,
            ),
        ];
        for (name, current, baseline) in components {
            let diff = current - baseline;
            if diff.abs() > 0.01 {
                changes.push(format!(
                    "{}: {}{:.1}%",
                    name,
                    if diff > 0.0 { "+" } else { "" },
                    diff * 100.0
                ));
            }
        }
        // Detect tradeoffs
        if self.components.performance > baseline.components.performance
            && self.components.maintainability < baseline.components.maintainability
        {
            tradeoffs.push("Performance improved at the cost of maintainability".to_string());
        }
        if self.components.safety > baseline.components.safety
            && self.components.performance < baseline.components.performance
        {
            tradeoffs.push("Safety improved at the cost of performance".to_string());
        }
        ScoreExplanation {
            delta,
            changes,
            tradeoffs,
            grade_change: format!("{} → {}", baseline.grade, self.grade),
        }
    }
}
/// Explanation of score changes
pub struct ScoreExplanation {
    pub delta: f64,
    pub changes: Vec<String>,
    pub tradeoffs: Vec<String>,
    pub grade_change: String,
}
/// Cache performance statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub entries: usize,
    pub memory_usage_estimate: usize,
}
/// Score correctness component (35% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_correctness;
///
/// let result = score_correctness(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_correctness(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut score = 1.0;
    // Pattern match exhaustiveness check
    let pattern_completeness = analyze_pattern_completeness(ast);
    score *= pattern_completeness;
    // Error handling coverage
    let error_handling_quality = analyze_error_handling(ast);
    score *= error_handling_quality;
    // Type consistency analysis
    let type_consistency = analyze_type_consistency(ast);
    score *= type_consistency;
    // Logical soundness (basic checks)
    let logical_soundness = analyze_logical_soundness(ast);
    score *= logical_soundness;
    score.clamp(0.0, 1.0)
}
/// Analyze pattern match completeness
fn analyze_pattern_completeness(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut total_matches = 0;
    let mut complete_matches = 0;
    analyze_pattern_completeness_recursive(ast, &mut total_matches, &mut complete_matches);
    if total_matches == 0 {
        1.0 // No matches, assume complete
    } else {
        #[allow(clippy::cast_precision_loss)]
        let score = (complete_matches as f64) / (total_matches as f64);
        score
    }
}
fn analyze_pattern_completeness_recursive(
    expr: &crate::frontend::ast::Expr,
    total_matches: &mut usize,
    complete_matches: &mut usize,
) {
    match &expr.kind {
        ExprKind::Match {
            expr: match_expr,
            arms,
        } => {
            *total_matches += 1;
            // Check if match has wildcard pattern or covers all cases
            let has_wildcard = arms
                .iter()
                .any(|arm| matches!(arm.pattern, crate::frontend::ast::Pattern::Wildcard));
            if has_wildcard || arms.len() >= 2 {
                // Basic heuristic
                *complete_matches += 1;
            }
            analyze_pattern_completeness_recursive(match_expr, total_matches, complete_matches);
            for arm in arms {
                analyze_pattern_completeness_recursive(&arm.body, total_matches, complete_matches);
            }
        }
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => {
            analyze_pattern_completeness_recursive(condition, total_matches, complete_matches);
            analyze_pattern_completeness_recursive(then_branch, total_matches, complete_matches);
            if let Some(else_expr) = else_branch {
                analyze_pattern_completeness_recursive(else_expr, total_matches, complete_matches);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_pattern_completeness_recursive(e, total_matches, complete_matches);
            }
        }
        ExprKind::Function { body, .. } => {
            analyze_pattern_completeness_recursive(body, total_matches, complete_matches);
        }
        _ => {}
    }
}
/// Analyze error handling quality
fn analyze_error_handling(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut total_fallible_ops = 0;
    let mut handled_ops = 0;
    analyze_error_handling_recursive(ast, &mut total_fallible_ops, &mut handled_ops);
    if total_fallible_ops == 0 {
        1.0 // No fallible operations
    } else {
        #[allow(clippy::cast_precision_loss)]
        let base_score = (handled_ops as f64) / (total_fallible_ops as f64);
        // Boost score if some error handling is present
        if handled_ops > 0 {
            (base_score + 0.3).min(1.0)
        } else {
            0.7 // Penalty for no error handling
        }
    }
}
fn analyze_error_handling_recursive(
    expr: &crate::frontend::ast::Expr,
    total_fallible_ops: &mut usize,
    handled_ops: &mut usize,
) {
    match &expr.kind {
        ExprKind::Match {
            expr: match_expr,
            arms,
        } => {
            // Check if matching on Result type (heuristic)
            if arms.len() >= 2 {
                *total_fallible_ops += 1;
                *handled_ops += 1;
            }
            analyze_error_handling_recursive(match_expr, total_fallible_ops, handled_ops);
            for arm in arms {
                analyze_error_handling_recursive(&arm.body, total_fallible_ops, handled_ops);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_error_handling_recursive(e, total_fallible_ops, handled_ops);
            }
        }
        ExprKind::Function { body, .. } => {
            analyze_error_handling_recursive(body, total_fallible_ops, handled_ops);
        }
        _ => {}
    }
}
/// Analyze type consistency
fn analyze_type_consistency(_ast: &crate::frontend::ast::Expr) -> f64 {
    // For now, assume good consistency since we have type checking
    // Future: integrate with type checker for real analysis
    0.95
}
/// Analyze logical soundness
fn analyze_logical_soundness(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut score = 1.0;
    // Check for obvious logical issues
    let has_unreachable = has_unreachable_code(ast);
    if has_unreachable {
        score *= 0.8; // Penalty for unreachable code
    }
    let has_infinite_loops = has_potential_infinite_loops(ast);
    if has_infinite_loops {
        score *= 0.9; // Penalty for potential infinite loops
    }
    score
}
fn has_unreachable_code(ast: &crate::frontend::ast::Expr) -> bool {
    match &ast.kind {
        ExprKind::Block(exprs) => check_block_unreachable(exprs),
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => check_if_unreachable(condition, then_branch, else_branch.as_deref()),
        _ => false,
    }
}

fn check_block_unreachable(exprs: &[crate::frontend::ast::Expr]) -> bool {
    for (i, expr) in exprs.iter().enumerate() {
        if i < exprs.len() - 1 && is_diverging_expr(expr) {
            return true; // Code after diverging expression
        }
        if has_unreachable_code(expr) {
            return true;
        }
    }
    false
}

fn check_if_unreachable(
    condition: &crate::frontend::ast::Expr,
    then_branch: &crate::frontend::ast::Expr,
    else_branch: Option<&crate::frontend::ast::Expr>,
) -> bool {
    has_unreachable_code(condition)
        || has_unreachable_code(then_branch)
        || else_branch
            .as_ref()
            .is_some_and(|e| has_unreachable_code(e))
}
fn is_diverging_expr(expr: &crate::frontend::ast::Expr) -> bool {
    match &expr.kind {
        ExprKind::Call { func, .. } => {
            // Check for known diverging functions (heuristic)
            if let ExprKind::Identifier(name) = &func.kind {
                matches!(name.as_str(), "panic" | "unreachable" | "exit")
            } else {
                false
            }
        }
        _ => false,
    }
}
fn has_potential_infinite_loops(ast: &crate::frontend::ast::Expr) -> bool {
    match &ast.kind {
        ExprKind::While {
            condition, body, ..
        } => {
            // Check for trivial infinite loops: while true { ... }
            if let ExprKind::Literal(crate::frontend::ast::Literal::Bool(true)) = &condition.kind {
                // Check if body has break statement
                !has_break_statement(body)
            } else {
                has_potential_infinite_loops(condition) || has_potential_infinite_loops(body)
            }
        }
        ExprKind::Block(exprs) => exprs.iter().any(has_potential_infinite_loops),
        ExprKind::Function { body, .. } => has_potential_infinite_loops(body),
        _ => false,
    }
}
fn has_break_statement(ast: &crate::frontend::ast::Expr) -> bool {
    match &ast.kind {
        ExprKind::Break { .. } => true,
        ExprKind::Block(exprs) => exprs.iter().any(has_break_statement),
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => {
            has_break_statement(condition)
                || has_break_statement(then_branch)
                || else_branch.as_ref().is_some_and(|e| has_break_statement(e))
        }
        _ => false,
    }
}
/// Score performance component (25% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_performance;
///
/// let result = score_performance(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_performance(ast: &crate::frontend::ast::Expr) -> f64 {
    let metrics = analyze_ast_metrics(ast);
    let mut score = 1.0;
    // Complexity analysis (BigO implications)
    let complexity_score = analyze_algorithmic_complexity(ast);
    score *= complexity_score;
    // Penalize high cyclomatic complexity (affects branch prediction)
    if metrics.cyclomatic_complexity > 10 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = ((metrics.cyclomatic_complexity - 10) as f64 * 0.02).min(0.3);
        score *= 1.0 - penalty;
    }
    // Penalize deep nesting (affects cache performance)
    if metrics.max_nesting > 3 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = ((metrics.max_nesting - 3) as f64 * 0.05).min(0.2);
        score *= 1.0 - penalty;
    }
    // Allocation analysis
    let allocation_score = analyze_allocation_patterns(ast);
    score *= allocation_score;
    // Memory access patterns (simplified for current AST)
    // Future enhancement when Index/Dict variants are added
    score.clamp(0.0, 1.0)
}
/// Analyze algorithmic complexity patterns
fn analyze_algorithmic_complexity(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut nested_loops = 0;
    let mut recursive_calls = 0;
    analyze_complexity_recursive(ast, &mut nested_loops, &mut recursive_calls, 0);
    let mut score = 1.0;
    // Penalize nested loops (O(n^k) complexity)
    if nested_loops > 0 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = (f64::from(nested_loops) * 0.15).min(0.5);
        score *= 1.0 - penalty;
    }
    // Penalize recursive calls without obvious base case
    if recursive_calls > 2 {
        score *= 0.8; // May indicate exponential complexity
    }
    score
}
fn analyze_complexity_recursive(
    expr: &crate::frontend::ast::Expr,
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    match &expr.kind {
        ExprKind::For { iter, body, .. }
        | ExprKind::While {
            condition: iter,
            body,
            ..
        } => analyze_loop_complexity(iter, body, nested_loops, recursive_calls, current_nesting),
        ExprKind::Call { func, args } => {
            analyze_call_complexity(func, args, nested_loops, recursive_calls, current_nesting);
        }
        ExprKind::Block(exprs) => {
            analyze_block_complexity(exprs, nested_loops, recursive_calls, current_nesting);
        }
        ExprKind::Function { body, .. } => {
            analyze_complexity_recursive(body, nested_loops, recursive_calls, 0);
        }
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => analyze_if_complexity(
            condition,
            then_branch,
            else_branch.as_deref(),
            nested_loops,
            recursive_calls,
            current_nesting,
        ),
        _ => {}
    }
}

fn analyze_loop_complexity(
    iter: &crate::frontend::ast::Expr,
    body: &crate::frontend::ast::Expr,
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    if current_nesting > 0 {
        *nested_loops += 1;
    }
    analyze_complexity_recursive(iter, nested_loops, recursive_calls, current_nesting);
    analyze_complexity_recursive(body, nested_loops, recursive_calls, current_nesting + 1);
}

fn analyze_call_complexity(
    func: &crate::frontend::ast::Expr,
    args: &[crate::frontend::ast::Expr],
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    if let ExprKind::Identifier(_) = &func.kind {
        *recursive_calls += 1;
    }
    analyze_complexity_recursive(func, nested_loops, recursive_calls, current_nesting);
    for arg in args {
        analyze_complexity_recursive(arg, nested_loops, recursive_calls, current_nesting);
    }
}

fn analyze_block_complexity(
    exprs: &[crate::frontend::ast::Expr],
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    for e in exprs {
        analyze_complexity_recursive(e, nested_loops, recursive_calls, current_nesting);
    }
}

fn analyze_if_complexity(
    condition: &crate::frontend::ast::Expr,
    then_branch: &crate::frontend::ast::Expr,
    else_branch: Option<&crate::frontend::ast::Expr>,
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    analyze_complexity_recursive(condition, nested_loops, recursive_calls, current_nesting);
    analyze_complexity_recursive(then_branch, nested_loops, recursive_calls, current_nesting);
    if let Some(else_expr) = else_branch {
        analyze_complexity_recursive(else_expr, nested_loops, recursive_calls, current_nesting);
    }
}
/// Analyze allocation patterns (GC pressure)
fn analyze_allocation_patterns(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut allocations = 0;
    let mut large_allocations = 0;
    count_allocations_recursive(ast, &mut allocations, &mut large_allocations);
    let mut score = 1.0;
    // Penalize excessive allocations
    if allocations > 10 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = (f64::from(allocations - 10) * 0.01).min(0.3);
        score *= 1.0 - penalty;
    }
    // Penalize large allocations in loops
    if large_allocations > 0 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = (f64::from(large_allocations) * 0.1).min(0.4);
        score *= 1.0 - penalty;
    }
    score
}
fn count_allocations_recursive(
    expr: &crate::frontend::ast::Expr,
    allocations: &mut i32,
    large_allocations: &mut i32,
) {
    match &expr.kind {
        ExprKind::List(items) => {
            *allocations += 1;
            if items.len() > 100 {
                *large_allocations += 1;
            }
            for item in items {
                count_allocations_recursive(item, allocations, large_allocations);
            }
        }
        // Dictionary literals not yet implemented in AST
        // ExprKind::Dict { pairs } => { ... }
        ExprKind::StringInterpolation { parts } => {
            *allocations += 1; // String concatenation
            for part in parts {
                if let crate::frontend::ast::StringPart::Expr(e) = part {
                    count_allocations_recursive(e, allocations, large_allocations);
                }
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_allocations_recursive(e, allocations, large_allocations);
            }
        }
        ExprKind::Function { body, .. } => {
            count_allocations_recursive(body, allocations, large_allocations);
        }
        _ => {}
    }
}
// Memory access pattern analysis will be added when
// AST supports indexing and dictionary operations
/// Score maintainability component (20% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_maintainability;
///
/// let result = score_maintainability(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_maintainability(ast: &crate::frontend::ast::Expr) -> f64 {
    let metrics = analyze_ast_metrics(ast);
    let mut score = 1.0;
    // Coupling analysis
    let coupling_score = analyze_coupling(ast);
    score *= coupling_score;
    // Cohesion analysis
    let cohesion_score = analyze_cohesion(ast, &metrics);
    score *= cohesion_score;
    // Code duplication detection (simplified)
    let duplication_score = analyze_duplication(ast);
    score *= duplication_score;
    // Naming quality (basic heuristics)
    let naming_score = analyze_naming_quality(ast);
    score *= naming_score;
    score.clamp(0.0, 1.0)
}
/// Analyze coupling between functions/modules
fn analyze_coupling(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut external_calls = 0;
    let mut total_functions = 0;
    count_coupling_metrics(ast, &mut external_calls, &mut total_functions);
    if total_functions == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let coupling_ratio = f64::from(external_calls) / f64::from(total_functions);
    // Lower coupling is better
    if coupling_ratio > 5.0 {
        0.7 // High coupling penalty
    } else if coupling_ratio > 2.0 {
        0.85
    } else {
        1.0 // Good coupling
    }
}
fn count_coupling_metrics(
    expr: &crate::frontend::ast::Expr,
    external_calls: &mut i32,
    total_functions: &mut i32,
) {
    match &expr.kind {
        ExprKind::Function { body, .. } => {
            *total_functions += 1;
            count_coupling_metrics(body, external_calls, total_functions);
        }
        ExprKind::Call { func, args } => {
            *external_calls += 1;
            count_coupling_metrics(func, external_calls, total_functions);
            for arg in args {
                count_coupling_metrics(arg, external_calls, total_functions);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_coupling_metrics(e, external_calls, total_functions);
            }
        }
        _ => {}
    }
}
/// Analyze cohesion within functions
fn analyze_cohesion(_ast: &crate::frontend::ast::Expr, metrics: &AstMetrics) -> f64 {
    let mut score = 1.0;
    // Penalize functions that are too large (low cohesion indicator)
    if metrics.line_count > 100 {
        score *= 0.8;
    }
    // Penalize excessive depth (indicates mixed concerns)
    if metrics.max_depth > 15 {
        score *= 0.85;
    }
    // Penalize too many functions (possible low cohesion)
    if metrics.function_count > 30 {
        score *= 0.9;
    }
    score
}
/// Analyze code duplication (simplified heuristic)
fn analyze_duplication(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut expression_patterns = std::collections::HashMap::new();
    collect_expression_patterns(ast, &mut expression_patterns);
    let duplicated_patterns = expression_patterns
        .values()
        .filter(|&&count| count > 1)
        .count();
    if duplicated_patterns > 5 {
        0.8 // Significant duplication penalty
    } else if duplicated_patterns > 2 {
        0.9 // Some duplication
    } else {
        1.0 // Little to no duplication
    }
}
fn collect_expression_patterns(
    expr: &crate::frontend::ast::Expr,
    patterns: &mut std::collections::HashMap<String, i32>,
) {
    // Simplified pattern matching - use expression kind as pattern
    let pattern = format!("{:?}", std::mem::discriminant(&expr.kind));
    *patterns.entry(pattern).or_insert(0) += 1;
    match &expr.kind {
        ExprKind::Block(exprs) => {
            for e in exprs {
                collect_expression_patterns(e, patterns);
            }
        }
        ExprKind::Function { body, .. } => {
            collect_expression_patterns(body, patterns);
        }
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => {
            collect_expression_patterns(condition, patterns);
            collect_expression_patterns(then_branch, patterns);
            if let Some(else_expr) = else_branch {
                collect_expression_patterns(else_expr, patterns);
            }
        }
        _ => {}
    }
}
/// Analyze naming quality (basic heuristics)
fn analyze_naming_quality(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut good_names = 0;
    let mut total_names = 0;
    analyze_names_recursive(ast, &mut good_names, &mut total_names);
    if total_names == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let good_ratio = f64::from(good_names) / f64::from(total_names);
    good_ratio.max(0.5) // Minimum score for naming
}
fn analyze_names_recursive(
    expr: &crate::frontend::ast::Expr,
    good_names: &mut i32,
    total_names: &mut i32,
) {
    match &expr.kind {
        ExprKind::Function { name, .. } => {
            *total_names += 1;
            if is_good_name(name) {
                *good_names += 1;
            }
        }
        ExprKind::Let { name, body, .. } => {
            *total_names += 1;
            if is_good_name(name) {
                *good_names += 1;
            }
            analyze_names_recursive(body, good_names, total_names);
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_names_recursive(e, good_names, total_names);
            }
        }
        _ => {}
    }
}
fn is_good_name(name: &str) -> bool {
    // Basic heuristics for good naming
    if name.len() < 2 || name.starts_with('_') {
        return false;
    }
    // Check for descriptive names (not single letters or abbreviations)
    name.len() >= 3 && !name.chars().all(|c| c.is_ascii_uppercase())
}
/// Score safety component (15% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_safety;
///
/// let result = score_safety(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_safety(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut score = 1.0;
    // Error handling coverage (reuse from correctness)
    let error_handling_quality = analyze_error_handling(ast);
    score *= error_handling_quality;
    // Null safety analysis
    let null_safety_score = analyze_null_safety(ast);
    score *= null_safety_score;
    // Resource management analysis
    let resource_score = analyze_resource_management(ast);
    score *= resource_score;
    // Bounds checking (implicit in type system, give good score)
    score *= 0.95; // Slight penalty for not having explicit bounds checks
    score.clamp(0.0, 1.0)
}
/// Analyze null safety patterns
fn analyze_null_safety(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut option_uses = 0;
    let mut unsafe_accesses = 0;
    analyze_null_safety_recursive(ast, &mut option_uses, &mut unsafe_accesses);
    if option_uses + unsafe_accesses == 0 {
        return 1.0; // No nullable types used
    }
    // Prefer Option types over unsafe accesses
    if unsafe_accesses == 0 {
        1.0 // All nullable accesses are safe
    } else {
        #[allow(clippy::cast_precision_loss)]
        let safety_ratio = f64::from(option_uses) / f64::from(option_uses + unsafe_accesses);
        safety_ratio.max(0.5) // Minimum safety score
    }
}
fn analyze_null_safety_recursive(
    expr: &crate::frontend::ast::Expr,
    option_uses: &mut i32,
    unsafe_accesses: &mut i32,
) {
    match &expr.kind {
        ExprKind::Some { .. } | ExprKind::None => {
            *option_uses += 1;
        }
        ExprKind::Match { arms, .. } => {
            // Check if matching on Option (heuristic)
            if arms.len() >= 2 {
                *option_uses += 1;
            }
            for arm in arms {
                analyze_null_safety_recursive(&arm.body, option_uses, unsafe_accesses);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_null_safety_recursive(e, option_uses, unsafe_accesses);
            }
        }
        ExprKind::Function { body, .. } => {
            analyze_null_safety_recursive(body, option_uses, unsafe_accesses);
        }
        _ => {}
    }
}
/// Analyze resource management patterns
fn analyze_resource_management(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut resource_allocations = 0;
    let mut proper_cleanup = 0;
    analyze_resources_recursive(ast, &mut resource_allocations, &mut proper_cleanup);
    if resource_allocations == 0 {
        return 1.0; // No resources to manage
    }
    #[allow(clippy::cast_precision_loss)]
    let cleanup_ratio = f64::from(proper_cleanup) / f64::from(resource_allocations);
    cleanup_ratio.max(0.7) // Minimum score for resource management
}
fn analyze_resources_recursive(
    expr: &crate::frontend::ast::Expr,
    allocations: &mut i32,
    cleanup: &mut i32,
) {
    match &expr.kind {
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_resources_recursive(e, allocations, cleanup);
            }
        }
        ExprKind::Function { body, .. } => {
            analyze_resources_recursive(body, allocations, cleanup);
        }
        _ => {}
    }
}
/// Score idiomaticity component (5% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_idiomaticity;
///
/// let result = score_idiomaticity(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_idiomaticity(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut score = 1.0;
    // Pattern matching usage (idiomatic in Ruchy)
    let pattern_score = analyze_pattern_usage(ast);
    score *= pattern_score;
    // Iterator usage (functional style)
    let iterator_score = analyze_iterator_usage(ast);
    score *= iterator_score;
    // Lambda usage (functional programming)
    let lambda_score = analyze_lambda_usage(ast);
    score *= lambda_score;
    score.clamp(0.0, 1.0)
}
/// Analyze usage of pattern matching (idiomatic)
fn analyze_pattern_usage(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut matches = 0;
    let mut conditionals = 0;
    count_pattern_vs_conditional(ast, &mut matches, &mut conditionals);
    let total = matches + conditionals;
    if total == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let pattern_ratio = f64::from(matches) / f64::from(total);
    // Higher ratio of matches vs if-else is more idiomatic
    if pattern_ratio > 0.7 {
        1.0
    } else if pattern_ratio > 0.4 {
        0.9
    } else {
        0.8
    }
}
fn count_pattern_vs_conditional(
    expr: &crate::frontend::ast::Expr,
    matches: &mut i32,
    conditionals: &mut i32,
) {
    match &expr.kind {
        ExprKind::Match { arms, .. } => {
            *matches += 1;
            for arm in arms {
                count_pattern_vs_conditional(&arm.body, matches, conditionals);
            }
        }
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => {
            *conditionals += 1;
            count_pattern_vs_conditional(condition, matches, conditionals);
            count_pattern_vs_conditional(then_branch, matches, conditionals);
            if let Some(else_expr) = else_branch {
                count_pattern_vs_conditional(else_expr, matches, conditionals);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_pattern_vs_conditional(e, matches, conditionals);
            }
        }
        ExprKind::Function { body, .. } => {
            count_pattern_vs_conditional(body, matches, conditionals);
        }
        _ => {}
    }
}
/// Analyze iterator usage patterns
fn analyze_iterator_usage(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut iterators = 0;
    let mut loops = 0;
    count_iterator_vs_loops(ast, &mut iterators, &mut loops);
    let total = iterators + loops;
    if total == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let iterator_ratio = f64::from(iterators) / f64::from(total);
    // Higher ratio of iterators vs manual loops is more idiomatic
    if iterator_ratio > 0.6 {
        1.0
    } else if iterator_ratio > 0.3 {
        0.9
    } else {
        0.8
    }
}
fn count_iterator_vs_loops(
    expr: &crate::frontend::ast::Expr,
    iterators: &mut i32,
    loops: &mut i32,
) {
    match &expr.kind {
        ExprKind::For { .. } => {
            *iterators += 1; // For loops in Ruchy are iterator-based
        }
        ExprKind::While { .. } => {
            *loops += 1;
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_iterator_vs_loops(e, iterators, loops);
            }
        }
        ExprKind::Function { body, .. } => {
            count_iterator_vs_loops(body, iterators, loops);
        }
        _ => {}
    }
}
/// Analyze lambda/closure usage
fn analyze_lambda_usage(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut lambdas = 0;
    let mut total_functions = 0;
    count_lambda_usage(ast, &mut lambdas, &mut total_functions);
    if total_functions == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let lambda_ratio = f64::from(lambdas) / f64::from(total_functions);
    // Some lambda usage indicates functional style
    if lambda_ratio > 0.3 {
        1.0
    } else if lambda_ratio > 0.1 {
        0.95
    } else {
        0.9 // Still good if other patterns are used
    }
}
fn count_lambda_usage(
    expr: &crate::frontend::ast::Expr,
    lambdas: &mut i32,
    total_functions: &mut i32,
) {
    match &expr.kind {
        ExprKind::Lambda { .. } => {
            *lambdas += 1;
            *total_functions += 1;
        }
        ExprKind::Function { body, .. } => {
            *total_functions += 1;
            count_lambda_usage(body, lambdas, total_functions);
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_lambda_usage(e, lambdas, total_functions);
            }
        }
        _ => {}
    }
}

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

    #[test]
    fn test_grade_from_score() {
        assert_eq!(Grade::from_score(1.0), Grade::APlus);
        assert_eq!(Grade::from_score(0.97), Grade::APlus);
        assert_eq!(Grade::from_score(0.95), Grade::A);
        assert_eq!(Grade::from_score(0.93), Grade::A);
        assert_eq!(Grade::from_score(0.91), Grade::AMinus);
        assert_eq!(Grade::from_score(0.90), Grade::AMinus);
        assert_eq!(Grade::from_score(0.88), Grade::BPlus);
        assert_eq!(Grade::from_score(0.85), Grade::B);
        assert_eq!(Grade::from_score(0.81), Grade::BMinus);
        assert_eq!(Grade::from_score(0.78), Grade::CPlus);
        assert_eq!(Grade::from_score(0.75), Grade::C);
        assert_eq!(Grade::from_score(0.71), Grade::CMinus);
        assert_eq!(Grade::from_score(0.65), Grade::D);
        assert_eq!(Grade::from_score(0.5), Grade::F);
        assert_eq!(Grade::from_score(0.0), Grade::F);
    }

    #[test]
    fn test_grade_to_rank() {
        assert_eq!(Grade::F.to_rank(), 0);
        assert_eq!(Grade::D.to_rank(), 1);
        assert_eq!(Grade::CMinus.to_rank(), 2);
        assert_eq!(Grade::C.to_rank(), 3);
        assert_eq!(Grade::CPlus.to_rank(), 4);
        assert_eq!(Grade::BMinus.to_rank(), 5);
        assert_eq!(Grade::B.to_rank(), 6);
        assert_eq!(Grade::BPlus.to_rank(), 7);
        assert_eq!(Grade::AMinus.to_rank(), 8);
        assert_eq!(Grade::A.to_rank(), 9);
        assert_eq!(Grade::APlus.to_rank(), 10);
    }

    #[test]
    fn test_grade_display() {
        assert_eq!(format!("{}", Grade::APlus), "A+");
        assert_eq!(format!("{}", Grade::A), "A");
        assert_eq!(format!("{}", Grade::AMinus), "A-");
        assert_eq!(format!("{}", Grade::BPlus), "B+");
        assert_eq!(format!("{}", Grade::B), "B");
        assert_eq!(format!("{}", Grade::BMinus), "B-");
        assert_eq!(format!("{}", Grade::CPlus), "C+");
        assert_eq!(format!("{}", Grade::C), "C");
        assert_eq!(format!("{}", Grade::CMinus), "C-");
        assert_eq!(format!("{}", Grade::D), "D");
        assert_eq!(format!("{}", Grade::F), "F");
    }

    #[test]
    fn test_analysis_depth_equality() {
        assert_eq!(AnalysisDepth::Shallow, AnalysisDepth::Shallow);
        assert_eq!(AnalysisDepth::Standard, AnalysisDepth::Standard);
        assert_eq!(AnalysisDepth::Deep, AnalysisDepth::Deep);
        assert_ne!(AnalysisDepth::Shallow, AnalysisDepth::Deep);
    }

    #[test]
    fn test_score_components_creation() {
        let components = ScoreComponents {
            correctness: 0.9,
            performance: 0.85,
            maintainability: 0.8,
            safety: 0.95,
            idiomaticity: 0.7,
        };

        assert_eq!(components.correctness, 0.9);
        assert_eq!(components.performance, 0.85);
        assert_eq!(components.maintainability, 0.8);
        assert_eq!(components.safety, 0.95);
        assert_eq!(components.idiomaticity, 0.7);
    }

    #[test]
    fn test_quality_score_creation() {
        let components = ScoreComponents {
            correctness: 0.9,
            performance: 0.85,
            maintainability: 0.8,
            safety: 0.95,
            idiomaticity: 0.7,
        };

        let score = QualityScore {
            value: 0.88,
            components,
            grade: Grade::BPlus,
            confidence: 0.95,
            cache_hit_rate: 0.2,
        };

        assert_eq!(score.value, 0.88);
        assert_eq!(score.grade, Grade::BPlus);
        assert_eq!(score.confidence, 0.95);
        assert_eq!(score.cache_hit_rate, 0.2);
        assert_eq!(score.components.correctness, 0.9);
    }

    #[test]
    fn test_quality_score_confidence_levels() {
        let mut score = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::B,
            confidence: 0.0,
            cache_hit_rate: 0.0,
        };

        // Test different confidence levels
        score.confidence = 0.0;
        assert!(score.confidence < 0.5);

        score.confidence = 0.5;
        assert_eq!(score.confidence, 0.5);

        score.confidence = 1.0;
        assert_eq!(score.confidence, 1.0);
    }

    #[test]
    fn test_quality_score_cache_hit_rate() {
        let mut score = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::B,
            confidence: 0.9,
            cache_hit_rate: 0.0,
        };

        // Test different cache hit rates
        score.cache_hit_rate = 0.0;
        assert_eq!(score.cache_hit_rate, 0.0);

        score.cache_hit_rate = 0.5;
        assert_eq!(score.cache_hit_rate, 0.5);

        score.cache_hit_rate = 1.0;
        assert_eq!(score.cache_hit_rate, 1.0);
    }

    #[test]
    fn test_grade_edge_cases() {
        // Test boundary values
        assert_eq!(Grade::from_score(0.969_999), Grade::A);
        assert_eq!(Grade::from_score(0.97), Grade::APlus);
        assert_eq!(Grade::from_score(0.929_999), Grade::AMinus);
        assert_eq!(Grade::from_score(0.93), Grade::A);
        assert_eq!(Grade::from_score(0.599_999), Grade::F);
        assert_eq!(Grade::from_score(0.60), Grade::D);

        // Test negative and > 1.0 values
        assert_eq!(Grade::from_score(-0.1), Grade::F);
        assert_eq!(Grade::from_score(1.1), Grade::APlus);
    }

    #[test]
    fn test_analysis_depth_display() {
        // Test that analysis depths have distinct values
        let depths = vec![
            AnalysisDepth::Shallow,
            AnalysisDepth::Standard,
            AnalysisDepth::Deep,
        ];

        for depth in &depths {
            // Each depth should equal itself
            assert_eq!(*depth, *depth);
        }

        // Different depths should not be equal
        assert_ne!(AnalysisDepth::Shallow, AnalysisDepth::Standard);
        assert_ne!(AnalysisDepth::Standard, AnalysisDepth::Deep);
    }

    #[test]
    fn test_score_components_weights() {
        // Test that component weights sum to approximately 1.0
        let components = ScoreComponents {
            correctness: 0.35,
            performance: 0.25,
            maintainability: 0.20,
            safety: 0.15,
            idiomaticity: 0.05,
        };

        let sum = components.correctness
            + components.performance
            + components.maintainability
            + components.safety
            + components.idiomaticity;
        assert!((sum - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_quality_score_normalization() {
        // Test that scores are normalized to 0.0-1.0 range
        let score = QualityScore {
            value: 0.5,
            components: ScoreComponents {
                correctness: 0.5,
                performance: 0.5,
                maintainability: 0.5,
                safety: 0.5,
                idiomaticity: 0.5,
            },
            grade: Grade::F,
            confidence: 0.5,
            cache_hit_rate: 0.5,
        };

        assert!(score.value >= 0.0 && score.value <= 1.0);
        assert!(score.confidence >= 0.0 && score.confidence <= 1.0);
        assert!(score.cache_hit_rate >= 0.0 && score.cache_hit_rate <= 1.0);
    }

    #[test]
    fn test_grade_ordering() {
        // Test that grades are properly ordered
        assert!(Grade::APlus.to_rank() > Grade::A.to_rank());
        assert!(Grade::A.to_rank() > Grade::AMinus.to_rank());
        assert!(Grade::AMinus.to_rank() > Grade::BPlus.to_rank());
        assert!(Grade::BPlus.to_rank() > Grade::B.to_rank());
        assert!(Grade::B.to_rank() > Grade::BMinus.to_rank());
        assert!(Grade::BMinus.to_rank() > Grade::CPlus.to_rank());
        assert!(Grade::CPlus.to_rank() > Grade::C.to_rank());
        assert!(Grade::C.to_rank() > Grade::CMinus.to_rank());
        assert!(Grade::CMinus.to_rank() > Grade::D.to_rank());
        assert!(Grade::D.to_rank() > Grade::F.to_rank());
    }

    #[test]
    fn test_incremental_cache_behavior() {
        // Test cache hit rate behavior
        let mut score = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::B,
            confidence: 0.9,
            cache_hit_rate: 0.0,
        };

        // Simulate incremental cache improvements
        score.cache_hit_rate = 0.25;
        assert!(score.cache_hit_rate > 0.0);

        score.cache_hit_rate = 0.50;
        assert!(score.cache_hit_rate > 0.25);

        score.cache_hit_rate = 0.75;
        assert!(score.cache_hit_rate > 0.50);
    }

    #[test]
    fn test_analysis_depth_performance_tradeoffs() {
        // Test that different depths represent performance tradeoffs
        let shallow = AnalysisDepth::Shallow;
        let standard = AnalysisDepth::Standard;
        let deep = AnalysisDepth::Deep;

        // Each depth should be distinct
        assert_ne!(shallow, standard);
        assert_ne!(standard, deep);
        assert_ne!(shallow, deep);
    }

    #[test]
    fn test_score_component_independence() {
        // Test that components can vary independently
        let components1 = ScoreComponents {
            correctness: 1.0,
            performance: 0.0,
            maintainability: 0.5,
            safety: 0.7,
            idiomaticity: 0.3,
        };

        let components2 = ScoreComponents {
            correctness: 0.0,
            performance: 1.0,
            maintainability: 0.5,
            safety: 0.7,
            idiomaticity: 0.3,
        };

        assert_ne!(components1.correctness, components2.correctness);
        assert_ne!(components1.performance, components2.performance);
        assert_eq!(components1.maintainability, components2.maintainability);
    }

    #[test]
    fn test_grade_display_format() {
        // Test that grades display correctly
        assert_eq!(format!("{}", Grade::APlus), "A+");
        assert_eq!(format!("{}", Grade::A), "A");
        assert_eq!(format!("{}", Grade::AMinus), "A-");
        assert_eq!(format!("{}", Grade::BPlus), "B+");
        assert_eq!(format!("{}", Grade::B), "B");
        assert_eq!(format!("{}", Grade::BMinus), "B-");
        assert_eq!(format!("{}", Grade::CPlus), "C+");
        assert_eq!(format!("{}", Grade::C), "C");
        assert_eq!(format!("{}", Grade::CMinus), "C-");
        assert_eq!(format!("{}", Grade::D), "D");
        assert_eq!(format!("{}", Grade::F), "F");
    }

    #[test]
    fn test_confidence_levels() {
        // Test different confidence scenarios
        let low_confidence = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::B,
            confidence: 0.2,
            cache_hit_rate: 0.0,
        };

        let high_confidence = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::B,
            confidence: 0.95,
            cache_hit_rate: 0.0,
        };

        assert!(low_confidence.confidence < 0.5);
        assert!(high_confidence.confidence > 0.9);
    }

    #[test]
    fn test_quality_score_with_extreme_components() {
        // Test with extreme component values
        let extreme_score = QualityScore {
            value: 0.0,
            components: ScoreComponents {
                correctness: 0.0,
                performance: 0.0,
                maintainability: 0.0,
                safety: 0.0,
                idiomaticity: 0.0,
            },
            grade: Grade::F,
            confidence: 1.0,
            cache_hit_rate: 0.0,
        };

        assert_eq!(extreme_score.value, 0.0);
        assert_eq!(extreme_score.grade, Grade::F);

        let perfect_score = QualityScore {
            value: 1.0,
            components: ScoreComponents {
                correctness: 1.0,
                performance: 1.0,
                maintainability: 1.0,
                safety: 1.0,
                idiomaticity: 1.0,
            },
            grade: Grade::APlus,
            confidence: 1.0,
            cache_hit_rate: 1.0,
        };

        assert_eq!(perfect_score.value, 1.0);
        assert_eq!(perfect_score.grade, Grade::APlus);
    }

    #[test]
    fn test_grade_transitions() {
        // Test grade transitions at exact boundaries
        let scores = vec![
            (0.97, Grade::APlus),
            (0.93, Grade::A),
            (0.90, Grade::AMinus),
            (0.87, Grade::BPlus),
            (0.83, Grade::B),
            (0.80, Grade::BMinus),
            (0.77, Grade::CPlus),
            (0.73, Grade::C),
            (0.70, Grade::CMinus),
            (0.60, Grade::D),
            (0.59, Grade::F),
        ];

        for (score, expected_grade) in scores {
            assert_eq!(Grade::from_score(score), expected_grade);
        }
    }

    #[test]
    fn test_score_component_balance() {
        // Test balanced vs unbalanced components
        let balanced = ScoreComponents {
            correctness: 0.8,
            performance: 0.8,
            maintainability: 0.8,
            safety: 0.8,
            idiomaticity: 0.8,
        };

        let unbalanced = ScoreComponents {
            correctness: 1.0,
            performance: 0.2,
            maintainability: 0.9,
            safety: 0.3,
            idiomaticity: 1.0,
        };

        // All balanced components should be equal
        assert_eq!(balanced.correctness, balanced.performance);
        assert_eq!(balanced.performance, balanced.maintainability);

        // Unbalanced components should vary
        assert_ne!(unbalanced.correctness, unbalanced.performance);
        assert_ne!(unbalanced.safety, unbalanced.idiomaticity);
    }

    #[test]
    fn test_analysis_depth_hash_equality() {
        use std::collections::HashSet;

        // Test that analysis depths can be used as hash keys
        let mut depth_set = HashSet::new();
        depth_set.insert(AnalysisDepth::Shallow);
        depth_set.insert(AnalysisDepth::Standard);
        depth_set.insert(AnalysisDepth::Deep);

        assert_eq!(depth_set.len(), 3);
        assert!(depth_set.contains(&AnalysisDepth::Shallow));
        assert!(depth_set.contains(&AnalysisDepth::Standard));
        assert!(depth_set.contains(&AnalysisDepth::Deep));
    }

    #[test]
    fn test_grade_rank_consistency() {
        // Test that to_rank() is consistent with from_score()
        let test_scores = vec![
            0.98, 0.95, 0.92, 0.88, 0.85, 0.82, 0.78, 0.75, 0.72, 0.65, 0.50,
        ];

        for score in test_scores {
            let grade1 = Grade::from_score(score);
            let grade2 = Grade::from_score(score + 0.001);

            // Higher scores should have equal or higher ranks
            assert!(grade2.to_rank() >= grade1.to_rank());
        }
    }

    #[test]
    fn test_cache_hit_rate_impact() {
        // Test that cache hit rate doesn't affect grade
        let score1 = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::B,
            confidence: 0.9,
            cache_hit_rate: 0.0,
        };

        let score2 = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::B,
            confidence: 0.9,
            cache_hit_rate: 1.0,
        };

        // Same value should yield same grade regardless of cache
        assert_eq!(score1.grade, score2.grade);
        assert_eq!(score1.value, score2.value);
    }

    #[test]
    fn test_incremental_scoring_architecture() {
        // Test incremental scoring concepts
        let initial_score = QualityScore {
            value: 0.7,
            components: ScoreComponents {
                correctness: 0.6,
                performance: 0.7,
                maintainability: 0.8,
                safety: 0.7,
                idiomaticity: 0.6,
            },
            grade: Grade::CMinus,
            confidence: 0.5,
            cache_hit_rate: 0.0,
        };

        // Simulate incremental improvement
        let improved_score = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::B,
            confidence: 0.8,
            cache_hit_rate: 0.5,
        };

        assert!(improved_score.value > initial_score.value);
        assert!(improved_score.confidence > initial_score.confidence);
        assert!(improved_score.cache_hit_rate > initial_score.cache_hit_rate);
    }

    #[test]
    fn test_component_weight_distribution() {
        // Test expected weight distribution
        let expected_weights = [
            ("correctness", 0.35),
            ("performance", 0.25),
            ("maintainability", 0.20),
            ("safety", 0.15),
            ("idiomaticity", 0.05),
        ];

        let total: f64 = expected_weights.iter().map(|(_, w)| w).sum();
        assert!((total - 1.0).abs() < 0.001);

        // Verify correctness has highest weight
        assert!(expected_weights[0].1 > expected_weights[1].1);
        assert!(expected_weights[1].1 > expected_weights[2].1);
    }

    #[test]
    fn test_edge_case_scores() {
        // Test edge cases and special values
        assert_eq!(Grade::from_score(f64::NAN), Grade::F);
        assert_eq!(Grade::from_score(f64::INFINITY), Grade::APlus);
        assert_eq!(Grade::from_score(f64::NEG_INFINITY), Grade::F);
        assert_eq!(Grade::from_score(f64::MIN), Grade::F);
        assert_eq!(Grade::from_score(f64::MAX), Grade::APlus);
    }

    #[test]
    fn test_score_serialization_compatibility() {
        // Test that Grade enum is serializable
        let grades = vec![
            Grade::APlus,
            Grade::A,
            Grade::AMinus,
            Grade::BPlus,
            Grade::B,
            Grade::BMinus,
            Grade::CPlus,
            Grade::C,
            Grade::CMinus,
            Grade::D,
            Grade::F,
        ];

        for grade in grades {
            // Test serialization round-trip
            let json = serde_json::to_string(&grade).unwrap();
            let deserialized: Grade = serde_json::from_str(&json).unwrap();
            assert_eq!(grade, deserialized);
        }
    }

    // ============== EXTREME TDD Round 121: ScoreEngine & DependencyTracker ==============

    #[test]
    fn test_score_engine_new() {
        let config = ScoreConfig::default();
        let engine = ScoreEngine::new(config);
        // Just verify it creates successfully
        drop(engine);
    }

    #[test]
    fn test_score_engine_score_shallow() {
        let config = ScoreConfig::default();
        let engine = ScoreEngine::new(config);
        let mut parser = crate::frontend::parser::Parser::new("42");
        let ast = parser.parse().expect("parse should succeed");
        let score = engine.score(&ast, AnalysisDepth::Shallow);
        assert!(score.value >= 0.0 && score.value <= 1.0);
    }

    #[test]
    fn test_score_engine_score_standard() {
        let config = ScoreConfig::default();
        let engine = ScoreEngine::new(config);
        let mut parser = crate::frontend::parser::Parser::new("let x = 1");
        let ast = parser.parse().expect("parse should succeed");
        let score = engine.score(&ast, AnalysisDepth::Standard);
        assert!(score.confidence >= 0.0);
    }

    #[test]
    fn test_score_engine_score_deep() {
        let config = ScoreConfig::default();
        let engine = ScoreEngine::new(config);
        let mut parser = crate::frontend::parser::Parser::new("fun foo() { 1 + 2 }");
        let ast = parser.parse().expect("parse should succeed");
        let score = engine.score(&ast, AnalysisDepth::Deep);
        assert!(matches!(
            score.grade,
            Grade::APlus
                | Grade::A
                | Grade::AMinus
                | Grade::BPlus
                | Grade::B
                | Grade::BMinus
                | Grade::CPlus
                | Grade::C
                | Grade::CMinus
                | Grade::D
                | Grade::F
        ));
    }

    #[test]
    fn test_dependency_tracker_new() {
        let tracker = DependencyTracker::new();
        // Just verify creation
        drop(tracker);
    }

    #[test]
    fn test_dependency_tracker_is_stale_nonexistent() {
        let tracker = DependencyTracker::new();
        let path = PathBuf::from("/nonexistent/path/file.rs");
        let is_stale = tracker.is_stale(&path);
        // Non-existent file should not report as stale (no dependencies)
        assert!(!is_stale);
    }

    #[test]
    fn test_score_config_default() {
        let config = ScoreConfig::default();
        // Verify default weights sum to 1.0
        let total = config.correctness_weight
            + config.performance_weight
            + config.maintainability_weight
            + config.safety_weight
            + config.idiomaticity_weight;
        assert!((total - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_cache_key_hash() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let key1 = CacheKey {
            file_path: PathBuf::from("test.rs"),
            content_hash: 12345,
            depth: AnalysisDepth::Shallow,
        };
        let key2 = CacheKey {
            file_path: PathBuf::from("test.rs"),
            content_hash: 12345,
            depth: AnalysisDepth::Shallow,
        };

        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        key1.hash(&mut hasher1);
        key2.hash(&mut hasher2);
        assert_eq!(hasher1.finish(), hasher2.finish());
    }

    #[test]
    fn test_grade_ordering_via_rank() {
        assert!(Grade::APlus.to_rank() > Grade::A.to_rank());
        assert!(Grade::A.to_rank() > Grade::AMinus.to_rank());
        assert!(Grade::AMinus.to_rank() > Grade::BPlus.to_rank());
        assert!(Grade::BPlus.to_rank() > Grade::B.to_rank());
        assert!(Grade::B.to_rank() > Grade::BMinus.to_rank());
        assert!(Grade::BMinus.to_rank() > Grade::CPlus.to_rank());
        assert!(Grade::CPlus.to_rank() > Grade::C.to_rank());
        assert!(Grade::C.to_rank() > Grade::CMinus.to_rank());
        assert!(Grade::CMinus.to_rank() > Grade::D.to_rank());
        assert!(Grade::D.to_rank() > Grade::F.to_rank());
    }

    #[test]
    fn test_analysis_depth_hash() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        AnalysisDepth::Shallow.hash(&mut hasher);
        let hash1 = hasher.finish();

        let mut hasher = DefaultHasher::new();
        AnalysisDepth::Standard.hash(&mut hasher);
        let hash2 = hasher.finish();

        // Different depths should have different hashes
        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_score_components_clone() {
        let original = ScoreComponents {
            correctness: 0.9,
            performance: 0.85,
            maintainability: 0.8,
            safety: 0.95,
            idiomaticity: 0.7,
        };
        let cloned = original.clone();
        assert_eq!(original.correctness, cloned.correctness);
        assert_eq!(original.performance, cloned.performance);
    }

    #[test]
    fn test_quality_score_clone() {
        let components = ScoreComponents {
            correctness: 0.9,
            performance: 0.85,
            maintainability: 0.8,
            safety: 0.95,
            idiomaticity: 0.7,
        };
        let original = QualityScore {
            value: 0.88,
            components,
            grade: Grade::BPlus,
            confidence: 0.95,
            cache_hit_rate: 0.2,
        };
        let cloned = original.clone();
        assert_eq!(original.value, cloned.value);
        assert_eq!(original.grade, cloned.grade);
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod property_tests_scoring {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(50))]

        // Grade::from_score always returns valid grade
        // Note: from_score expects normalized value 0.0-1.0, not 0-100
        // to_rank returns 0-10 (F=0, APlus=10)
        #[test]
        fn prop_grade_from_score_valid(value in 0.0f64..=1.0) {
            let grade = Grade::from_score(value);
            // Grade should be one of the valid variants (ranks 0-10)
            let rank = grade.to_rank();
            prop_assert!((0..=10).contains(&rank));
        }

        // Grade ranks are consistent (same score = same rank)
        #[test]
        fn prop_grade_rank_consistent(value in 0.0f64..=1.0) {
            let grade1 = Grade::from_score(value);
            let grade2 = Grade::from_score(value);
            // Same score should produce same rank
            prop_assert_eq!(grade1.to_rank(), grade2.to_rank());
        }

        // ScoreConfig default is valid
        #[test]
        fn prop_score_config_default_valid(_dummy: u8) {
            let _config = ScoreConfig::default();
            prop_assert!(true);
        }

        // ScoreEngine::new never panics
        #[test]
        fn prop_score_engine_new_never_panics(_dummy: u8) {
            let config = ScoreConfig::default();
            let _engine = ScoreEngine::new(config);
            prop_assert!(true);
        }

        // DependencyTracker::new never panics
        #[test]
        fn prop_dependency_tracker_new_never_panics(_dummy: u8) {
            let tracker = DependencyTracker::new();
            // Verify tracker works with path check
            let _is_stale = tracker.is_stale(&PathBuf::from("test.rs"));
            prop_assert!(true);
        }

        // Scoring parsed integer code works
        #[test]
        fn prop_score_parsed_integer(n in -1000i64..1000) {
            let code = format!("{n}");
            let mut parser = crate::frontend::parser::Parser::new(&code);
            if let Ok(ast) = parser.parse() {
                let score = score_correctness(&ast);
                prop_assert!((0.0..=100.0).contains(&score));
            }
        }

        // Scoring parsed let statement works
        #[test]
        fn prop_score_parsed_let(n in -100i64..100) {
            let code = format!("let x = {n}");
            let mut parser = crate::frontend::parser::Parser::new(&code);
            if let Ok(ast) = parser.parse() {
                let score = score_performance(&ast);
                prop_assert!((0.0..=100.0).contains(&score));
            }
        }

        // Scoring parsed function works
        #[test]
        fn prop_score_parsed_function(_dummy: u8) {
            let code = "fun add(a, b) { a + b }";
            let mut parser = crate::frontend::parser::Parser::new(code);
            if let Ok(ast) = parser.parse() {
                let score = score_maintainability(&ast);
                prop_assert!((0.0..=100.0).contains(&score));
            }
        }

        // Scoring safety is bounded
        #[test]
        fn prop_score_safety_bounded(_dummy: u8) {
            let code = "let x = 42";
            let mut parser = crate::frontend::parser::Parser::new(code);
            if let Ok(ast) = parser.parse() {
                let score = score_safety(&ast);
                prop_assert!((0.0..=100.0).contains(&score));
            }
        }

        // Scoring idiomaticity is bounded
        #[test]
        fn prop_score_idiomaticity_bounded(_dummy: u8) {
            let code = "true && false";
            let mut parser = crate::frontend::parser::Parser::new(code);
            if let Ok(ast) = parser.parse() {
                let score = score_idiomaticity(&ast);
                prop_assert!((0.0..=100.0).contains(&score));
            }
        }
    }
}

// === EXTREME TDD Round 162 - Scoring Unit Tests ===

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

    // Grade boundary tests
    #[test]
    fn test_grade_from_score_boundaries_r162() {
        // Test exact boundaries
        assert_eq!(Grade::from_score(1.0), Grade::APlus);
        assert_eq!(Grade::from_score(0.97), Grade::APlus);
        assert_eq!(Grade::from_score(0.969), Grade::A);
        assert_eq!(Grade::from_score(0.93), Grade::A);
        assert_eq!(Grade::from_score(0.929), Grade::AMinus);
        assert_eq!(Grade::from_score(0.90), Grade::AMinus);
        assert_eq!(Grade::from_score(0.899), Grade::BPlus);
        assert_eq!(Grade::from_score(0.87), Grade::BPlus);
        assert_eq!(Grade::from_score(0.869), Grade::B);
        assert_eq!(Grade::from_score(0.83), Grade::B);
        assert_eq!(Grade::from_score(0.829), Grade::BMinus);
        assert_eq!(Grade::from_score(0.80), Grade::BMinus);
        assert_eq!(Grade::from_score(0.799), Grade::CPlus);
        assert_eq!(Grade::from_score(0.77), Grade::CPlus);
        assert_eq!(Grade::from_score(0.769), Grade::C);
        assert_eq!(Grade::from_score(0.73), Grade::C);
        assert_eq!(Grade::from_score(0.729), Grade::CMinus);
        assert_eq!(Grade::from_score(0.70), Grade::CMinus);
        assert_eq!(Grade::from_score(0.699), Grade::D);
        assert_eq!(Grade::from_score(0.60), Grade::D);
        assert_eq!(Grade::from_score(0.599), Grade::F);
        assert_eq!(Grade::from_score(0.0), Grade::F);
    }

    #[test]
    fn test_grade_to_rank_all_grades_r162() {
        assert_eq!(Grade::F.to_rank(), 0);
        assert_eq!(Grade::D.to_rank(), 1);
        assert_eq!(Grade::CMinus.to_rank(), 2);
        assert_eq!(Grade::C.to_rank(), 3);
        assert_eq!(Grade::CPlus.to_rank(), 4);
        assert_eq!(Grade::BMinus.to_rank(), 5);
        assert_eq!(Grade::B.to_rank(), 6);
        assert_eq!(Grade::BPlus.to_rank(), 7);
        assert_eq!(Grade::AMinus.to_rank(), 8);
        assert_eq!(Grade::A.to_rank(), 9);
        assert_eq!(Grade::APlus.to_rank(), 10);
    }

    #[test]
    fn test_grade_display_all_r162() {
        assert_eq!(format!("{}", Grade::APlus), "A+");
        assert_eq!(format!("{}", Grade::A), "A");
        assert_eq!(format!("{}", Grade::AMinus), "A-");
        assert_eq!(format!("{}", Grade::BPlus), "B+");
        assert_eq!(format!("{}", Grade::B), "B");
        assert_eq!(format!("{}", Grade::BMinus), "B-");
        assert_eq!(format!("{}", Grade::CPlus), "C+");
        assert_eq!(format!("{}", Grade::C), "C");
        assert_eq!(format!("{}", Grade::CMinus), "C-");
        assert_eq!(format!("{}", Grade::D), "D");
        assert_eq!(format!("{}", Grade::F), "F");
    }

    #[test]
    fn test_grade_negative_score_r162() {
        // Negative scores should map to F
        assert_eq!(Grade::from_score(-1.0), Grade::F);
        assert_eq!(Grade::from_score(-0.5), Grade::F);
        assert_eq!(Grade::from_score(-100.0), Grade::F);
    }

    #[test]
    fn test_grade_over_1_score_r162() {
        // Scores over 1.0 should map to APlus
        assert_eq!(Grade::from_score(1.1), Grade::APlus);
        assert_eq!(Grade::from_score(2.0), Grade::APlus);
        assert_eq!(Grade::from_score(100.0), Grade::APlus);
    }

    // AnalysisDepth tests
    #[test]
    fn test_analysis_depth_clone_r162() {
        let depth = AnalysisDepth::Standard;
        let cloned = depth;
        assert_eq!(depth, cloned);
    }

    #[test]
    fn test_analysis_depth_debug_r162() {
        let shallow = AnalysisDepth::Shallow;
        let standard = AnalysisDepth::Standard;
        let deep = AnalysisDepth::Deep;

        assert!(format!("{:?}", shallow).contains("Shallow"));
        assert!(format!("{:?}", standard).contains("Standard"));
        assert!(format!("{:?}", deep).contains("Deep"));
    }

    #[test]
    fn test_analysis_depth_eq_r162() {
        assert_eq!(AnalysisDepth::Shallow, AnalysisDepth::Shallow);
        assert_eq!(AnalysisDepth::Standard, AnalysisDepth::Standard);
        assert_eq!(AnalysisDepth::Deep, AnalysisDepth::Deep);
        assert_ne!(AnalysisDepth::Shallow, AnalysisDepth::Standard);
        assert_ne!(AnalysisDepth::Standard, AnalysisDepth::Deep);
        assert_ne!(AnalysisDepth::Shallow, AnalysisDepth::Deep);
    }

    #[test]
    fn test_analysis_depth_hash_r162() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(AnalysisDepth::Shallow);
        set.insert(AnalysisDepth::Standard);
        set.insert(AnalysisDepth::Deep);
        assert_eq!(set.len(), 3);
        // Inserting duplicate should not increase size
        set.insert(AnalysisDepth::Shallow);
        assert_eq!(set.len(), 3);
    }

    // ScoreComponents tests
    #[test]
    fn test_score_components_clone_r162() {
        let components = ScoreComponents {
            correctness: 0.9,
            performance: 0.8,
            maintainability: 0.7,
            safety: 0.6,
            idiomaticity: 0.5,
        };
        let cloned = components.clone();
        assert_eq!(cloned.correctness, 0.9);
        assert_eq!(cloned.performance, 0.8);
        assert_eq!(cloned.maintainability, 0.7);
        assert_eq!(cloned.safety, 0.6);
        assert_eq!(cloned.idiomaticity, 0.5);
    }

    #[test]
    fn test_score_components_debug_r162() {
        let components = ScoreComponents {
            correctness: 0.95,
            performance: 0.85,
            maintainability: 0.75,
            safety: 0.65,
            idiomaticity: 0.55,
        };
        let debug_str = format!("{:?}", components);
        assert!(debug_str.contains("ScoreComponents"));
        assert!(debug_str.contains("correctness"));
        assert!(debug_str.contains("performance"));
        assert!(debug_str.contains("maintainability"));
        assert!(debug_str.contains("safety"));
        assert!(debug_str.contains("idiomaticity"));
    }

    // QualityScore tests
    #[test]
    fn test_quality_score_clone_r162() {
        let score = QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.7,
                safety: 0.85,
                idiomaticity: 0.75,
            },
            grade: Grade::B,
            confidence: 0.95,
            cache_hit_rate: 0.5,
        };
        let cloned = score.clone();
        assert_eq!(cloned.value, 0.85);
        assert_eq!(cloned.grade, Grade::B);
        assert_eq!(cloned.confidence, 0.95);
        assert_eq!(cloned.cache_hit_rate, 0.5);
    }

    #[test]
    fn test_quality_score_debug_r162() {
        let score = QualityScore {
            value: 0.75,
            components: ScoreComponents {
                correctness: 0.8,
                performance: 0.7,
                maintainability: 0.6,
                safety: 0.75,
                idiomaticity: 0.65,
            },
            grade: Grade::CPlus,
            confidence: 0.8,
            cache_hit_rate: 0.25,
        };
        let debug_str = format!("{:?}", score);
        assert!(debug_str.contains("QualityScore"));
        assert!(debug_str.contains("value"));
        assert!(debug_str.contains("grade"));
        assert!(debug_str.contains("confidence"));
    }

    // ScoreConfig tests
    #[test]
    fn test_score_config_default_r162() {
        let config = ScoreConfig::default();
        // Default should have reasonable values
        assert!(config.correctness_weight >= 0.0 && config.correctness_weight <= 1.0);
        assert!(config.performance_weight >= 0.0 && config.performance_weight <= 1.0);
        assert!(config.maintainability_weight >= 0.0 && config.maintainability_weight <= 1.0);
        assert!(config.safety_weight >= 0.0 && config.safety_weight <= 1.0);
        assert!(config.idiomaticity_weight >= 0.0 && config.idiomaticity_weight <= 1.0);
    }

    // DependencyTracker tests
    #[test]
    fn test_dependency_tracker_new_r162() {
        let tracker = DependencyTracker::new();
        // New tracker should work
        let path = PathBuf::from("nonexistent.rs");
        let _is_stale = tracker.is_stale(&path);
    }

    #[test]
    fn test_dependency_tracker_is_stale_nonexistent_r162() {
        let tracker = DependencyTracker::new();
        let path = PathBuf::from("definitely_does_not_exist_12345.rs");
        // Test that is_stale doesn't panic on nonexistent files
        let is_stale = tracker.is_stale(&path);
        // Note: Implementation returns false for files not tracked
        assert!(!is_stale);
    }

    // Grade comparison tests
    #[test]
    fn test_grade_rank_ordering_r162() {
        // Higher grades should have higher ranks
        assert!(Grade::APlus.to_rank() > Grade::A.to_rank());
        assert!(Grade::A.to_rank() > Grade::AMinus.to_rank());
        assert!(Grade::AMinus.to_rank() > Grade::BPlus.to_rank());
        assert!(Grade::BPlus.to_rank() > Grade::B.to_rank());
        assert!(Grade::B.to_rank() > Grade::BMinus.to_rank());
        assert!(Grade::BMinus.to_rank() > Grade::CPlus.to_rank());
        assert!(Grade::CPlus.to_rank() > Grade::C.to_rank());
        assert!(Grade::C.to_rank() > Grade::CMinus.to_rank());
        assert!(Grade::CMinus.to_rank() > Grade::D.to_rank());
        assert!(Grade::D.to_rank() > Grade::F.to_rank());
    }

    #[test]
    fn test_grade_serialize_deserialize_r162() {
        // Grade should be serializable
        let grade = Grade::AMinus;
        let serialized = serde_json::to_string(&grade).unwrap();
        let deserialized: Grade = serde_json::from_str(&serialized).unwrap();
        assert_eq!(grade, deserialized);
    }

    #[test]
    fn test_grade_all_serialize_r162() {
        for grade in [
            Grade::APlus,
            Grade::A,
            Grade::AMinus,
            Grade::BPlus,
            Grade::B,
            Grade::BMinus,
            Grade::CPlus,
            Grade::C,
            Grade::CMinus,
            Grade::D,
            Grade::F,
        ] {
            let serialized = serde_json::to_string(&grade).unwrap();
            let deserialized: Grade = serde_json::from_str(&serialized).unwrap();
            assert_eq!(grade, deserialized);
        }
    }

    // Edge case scoring tests
    #[test]
    fn test_score_empty_program_r162() {
        let code = "";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            // Empty program should still produce valid scores
            let correctness = score_correctness(&ast);
            let performance = score_performance(&ast);
            let maintainability = score_maintainability(&ast);
            let safety = score_safety(&ast);
            let idiomaticity = score_idiomaticity(&ast);

            assert!((0.0..=100.0).contains(&correctness));
            assert!((0.0..=100.0).contains(&performance));
            assert!((0.0..=100.0).contains(&maintainability));
            assert!((0.0..=100.0).contains(&safety));
            assert!((0.0..=100.0).contains(&idiomaticity));
        }
    }

    #[test]
    fn test_score_simple_literal_r162() {
        let code = "42";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let correctness = score_correctness(&ast);
            assert!((0.0..=100.0).contains(&correctness));
        }
    }

    #[test]
    fn test_score_string_literal_r162() {
        let code = r#""hello world""#;
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let idiomaticity = score_idiomaticity(&ast);
            assert!((0.0..=100.0).contains(&idiomaticity));
        }
    }

    #[test]
    fn test_score_boolean_literal_r162() {
        let code = "true";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let safety = score_safety(&ast);
            assert!((0.0..=100.0).contains(&safety));
        }
    }

    #[test]
    fn test_score_binary_expression_r162() {
        let code = "1 + 2 * 3";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let performance = score_performance(&ast);
            assert!((0.0..=100.0).contains(&performance));
        }
    }

    #[test]
    fn test_score_nested_functions_r162() {
        let code = "fun outer() { fun inner() { 42 } }";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let maintainability = score_maintainability(&ast);
            assert!((0.0..=100.0).contains(&maintainability));
        }
    }

    #[test]
    fn test_score_if_expression_r162() {
        let code = "if true { 1 } else { 2 }";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let correctness = score_correctness(&ast);
            assert!((0.0..=100.0).contains(&correctness));
        }
    }

    #[test]
    fn test_score_while_loop_r162() {
        let code = "while false { 1 }";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let safety = score_safety(&ast);
            assert!((0.0..=100.0).contains(&safety));
        }
    }

    #[test]
    fn test_score_array_literal_r162() {
        let code = "[1, 2, 3, 4, 5]";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let performance = score_performance(&ast);
            assert!((0.0..=100.0).contains(&performance));
        }
    }

    #[test]
    fn test_score_lambda_expression_r162() {
        let code = "|x| x * 2";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let maintainability = score_maintainability(&ast);
            assert!((0.0..=100.0).contains(&maintainability));
        }
    }

    #[test]
    fn test_score_idiomaticity_compound_expression_r162() {
        let code = "fun map_values(arr) { arr.map(|x| x * 2) }";
        let mut parser = crate::frontend::parser::Parser::new(code);
        if let Ok(ast) = parser.parse() {
            let idiomaticity = score_idiomaticity(&ast);
            assert!((0.0..=100.0).contains(&idiomaticity));
        }
    }
}