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
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
#![warn(missing_docs)]
#![warn(clippy::missing_docs_in_private_items)]

use std::{
    collections::HashSet,
    fmt::Display,
    fs,
    io::{
        BufRead,
        BufReader,
        Write,
    },
    ops::RangeInclusive,
    process::Command,
};

use anyhow::{
    anyhow,
    ensure,
    Context,
    Result,
};
use async_openai::{
    config::OpenAIConfig,
    types::{
        ChatCompletionRequestMessage,
        CreateChatCompletionRequest,
        CreateChatCompletionResponse,
        Role,
    },
};
use colored::Colorize;
use futures::{
    future::try_join_all,
    stream::FuturesUnordered,
};
use itertools::Itertools;
use rhai::FnPtr;
#[allow(deprecated)]
use rhai::{
    Array,
    CustomType,
    Dynamic,
    EvalAltResult,
};
use serde::{
    Deserialize,
    Serialize,
};
use similar::{
    utils::diff_unicode_words,
    Algorithm,
    ChangeTag,
};
use snailquote::unescape;
use tabled::{
    display::ExpandedDisplay,
    object::Rows,
    Alignment,
    Modify,
    Panel,
    TableIteratorExt,
    Tabled,
    Width,
};
use typed_builder::TypedBuilder;
use umm_derive::generate_rhai_variant;

use crate::{
    constants::{
        ALGORITHMIC_SOLUTIONS_SLO,
        CODE_READABILITY_SLO,
        COMMENTS_WRITTEN_SLO,
        ERROR_HANDLING_SLO,
        JAVA_TS_LANG,
        LOGIC_SLO,
        METHOD_CALL_QUERY,
        NAMING_CONVENTIONS_SLO,
        OBJECT_ORIENTED_PROGRAMMING_SLO,
        POSTGREST_CLIENT,
        PROMPT_TRUNCATE,
        RETRIEVAL_MESSAGE_INTRO,
        ROOT_DIR,
        RUNTIME,
        SCRIPT_AST,
        SOURCE_DIR,
        SYNTAX_SLO,
        SYSTEM_MESSAGE,
        TESTING_SLO,
        USE_ACTIVE_RETRIEVAL,
    },
    create_engine,
    java::{
        File,
        FileType,
        JavaFileError,
        Parser,
        Project,
    },
    parsers::parser,
    util::{
        classpath,
        java_path,
    },
    Dict,
};
#[derive(Debug, Hash, PartialEq, Eq)]
/// A struct representing a line in a stack trace
pub struct LineRef {
    /// The line number
    pub line_number: usize,
    /// The file name
    pub file_name:   String,
}

impl LineRef {
    /// Returns the file name
    pub fn file_name(&self) -> &str {
        self.file_name.as_ref()
    }
}

#[derive(Clone, Default)]
/// A struct representing a grade
pub struct Grade {
    /// The actual grade received
    pub grade:  f64,
    /// The maximum grade possible
    pub out_of: f64,
}

impl Grade {
    /// Creates a new grade -
    /// * `grade` - The actual grade received
    /// * `out_of` - The maximum grade possible
    pub fn new(grade: f64, out_of: f64) -> Self {
        Self {
            grade,
            out_of,
        }
    }

    #[generate_rhai_variant(Impl, Fallible)]
    /// Creates a new grade from a string -
    /// * `grade_string` - A string in the format `grade/out_of`, eg. `10/20`
    pub fn grade_from_string(grade_string: String) -> Result<Grade> {
        let (grade, out_of) = grade_string.split_once('/').unwrap_or(("0", "0"));
        Ok(Grade::new(
            grade.parse::<f64>().context("Failed to parse grade")?,
            out_of.parse::<f64>().context("Failed to parse out of")?,
        ))
    }

    /// a getter for the grade
    pub fn grade(&mut self) -> f64 {
        self.grade
    }

    /// a getter for the out_of
    pub fn out_of(&mut self) -> f64 {
        self.out_of
    }

    /// a setter for the grade
    pub fn set_grade(mut self, grade: f64) -> Self {
        self.grade = grade;
        self
    }

    /// a setter for the out_of
    pub fn set_out_of(mut self, out_of: f64) -> Self {
        self.grade = out_of;
        self
    }
}

impl Display for Grade {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:.2}/{:.2}", self.grade, self.out_of)
    }
}

#[derive(Tabled, Clone, Default)]
/// A struct to store grading results and display them
pub struct GradeResult {
    #[tabled(rename = "Requirement")]
    /// * `requirement`: refers to Requirement ID
    requirement: String,
    #[tabled(rename = "Grade")]
    /// * `grade`: grade received for above Requirement
    grade:       Grade,
    #[tabled(rename = "Reason")]
    /// * `reason`: the reason for penalties applied, if any
    reason:      String,
    #[tabled(skip)]
    /// * `prompt`: the prompt for the AI TA
    prompt:      Option<Vec<ChatCompletionRequestMessage>>,
}

impl GradeResult {
    /// a getter for Requirement
    pub fn requirement(&mut self) -> String {
        self.requirement.clone()
    }

    /// a setter for Requirement
    pub fn set_requirement(mut self, requirement: String) -> Self {
        self.requirement = requirement;
        self
    }

    /// a getter for Reason
    pub fn reason(&mut self) -> String {
        self.reason.clone()
    }

    /// a setter for Reason
    pub fn set_reason(mut self, reason: String) -> Self {
        self.reason = reason;
        self
    }

    /// a getter for the self.grade.grade
    pub fn grade(&mut self) -> f64 {
        self.grade.grade()
    }

    /// a getter for the self.grade.out_of
    pub fn out_of(&mut self) -> f64 {
        self.grade.out_of()
    }

    /// a setter for the self.grade.grade
    pub fn set_grade(mut self, grade: f64) -> Self {
        self.grade = self.grade.set_grade(grade);
        self
    }

    /// a setter for the self.grade.out_of
    pub fn set_out_of(mut self, out_of: f64) -> Self {
        self.grade = self.grade.set_out_of(out_of);
        self
    }

    /// a getter for the prompt
    pub fn prompt(&mut self) -> Option<Vec<ChatCompletionRequestMessage>> {
        self.prompt.clone()
    }

    /// a setter for the prompt
    pub fn set_prompt(mut self, prompt: Option<Vec<ChatCompletionRequestMessage>>) -> Self {
        self.prompt = prompt;
        self
    }
}

#[derive(Tabled, Serialize, Deserialize, TypedBuilder, Clone, Debug)]
#[builder(field_defaults(setter(into)))]
#[builder(doc)]
/// A struct representing a javac diagnostic message
pub struct JavacDiagnostic {
    /// * `path`: path to the file diagnostic is referring to
    #[tabled(rename = "File")]
    path:        String,
    /// * `file_name`: name of the file the diagnostic is about
    #[tabled(skip)]
    file_name:   String,
    /// * `line_number`: line number
    #[tabled(rename = "Line")]
    line_number: u32,
    /// * `is_error`: boolean value, is true if error or false if the diagnostic
    ///   is a warning
    #[tabled(skip)]
    is_error:    bool,
    /// * `message`: the diagnostic message
    #[tabled(rename = "Message")]
    message:     String,
}

impl JavacDiagnostic {
    /// Returns the file name
    pub fn file_name(&self) -> &str {
        self.file_name.as_ref()
    }
}

impl From<JavacDiagnostic> for LineRef {
    /// Converts a JavacDiagnostic to a LineRef
    fn from(val: JavacDiagnostic) -> Self {
        LineRef {
            file_name:   val.file_name,
            line_number: val.line_number as usize,
        }
    }
}

#[derive(Tabled, Serialize, Deserialize, TypedBuilder, Clone)]
#[builder(field_defaults(setter(into)))]
#[builder(doc)]
/// A struct representing a PIT diagnostic message
pub struct MutationDiagnostic {
    /// * `mutator`: name of the mutator in question
    #[tabled(rename = "Mutation type")]
    mutator:          String,
    /// * `source_method`: name of the source method being mutated
    #[tabled(rename = "Source method mutated")]
    source_method:    String,
    /// * `line_number`: source line number where mutation occurred
    #[tabled(rename = "Line no. of mutation")]
    line_number:      u32,
    /// * `test_method`: name of the test examined
    #[tabled(rename = "Test examined")]
    test_method:      String,
    /// * `result`: result of mutation testing
    #[tabled(rename = "Result")]
    result:           String,
    /// * `source_file_name`: name of the source file
    #[tabled(skip)]
    source_file_name: String,
    /// * `test_file_name`: name of the test file
    #[tabled(skip)]
    test_file_name:   String,
}

impl From<MutationDiagnostic> for LineRef {
    /// Converts a MutationDiagnostic to a LineRef
    fn from(val: MutationDiagnostic) -> Self {
        LineRef {
            file_name:   val.source_file_name,
            line_number: val.line_number as usize,
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
/// `RetrievalFunctionCallParams` is a struct that holds the parameters for a
/// retrieval function call.
struct RetrievalFunctionCallParams {
    /// A string that holds the name of the class.
    class_name:  String,
    ///  A string that holds the name of the method.
    method_name: String,
}

#[derive(Serialize, Deserialize, Debug)]
/// `RetrievalFunctionCallParamsArray` is a struct that holds an array of
/// `RetrievalFunctionCallParams`.
struct RetrievalFunctionCallParamsArray {
    /// A vector of `RetrievalFunctionCallParams`.
    params: Vec<RetrievalFunctionCallParams>,
}

/// Retrieves the active context for a retrieval operation.
///
/// This function takes a reference to a `Project` and an optional `String` as
/// additional context. It ensures that the additional context is provided when
/// using active retrieval. It then prepares a series of
/// `ChatCompletionRequestMessage` and serializes them into a JSON string.
///
/// # Arguments
///
/// * `proj` - A reference to a `Project`.
/// * `additional_context` - An optional `String` that provides additional
///   context for the retrieval operation.
///
/// # Returns
///
/// * `Result<ChatCompletionRequestMessage>` - A `Result` that contains a
///   `ChatCompletionRequestMessage` if the operation was successful, or an
///   `Err` if it was not.
pub fn get_active_retrieval_context(
    proj: &Project,
    active_retrieval_context: Option<String>,
) -> Result<ChatCompletionRequestMessage> {
    ensure!(
        active_retrieval_context.is_some(),
        "Additional context must be provided when using active retrieval."
    );

    print!("Trying to decide what to share with AI for feedback...");
    let mut messages = Vec::new();

    messages.push(ChatCompletionRequestMessage {
        role:          Role::System,
        content:       Some(RETRIEVAL_MESSAGE_INTRO.to_string()),
        name:          Some(String::from("Instructor")),
        function_call: None,
    });
    messages.push(ChatCompletionRequestMessage {
        role:          Role::User,
        content:       Some(format!(
            "Here is the output (stdout and stderr) from running the auto-grader on my \
             submission:\n```\n{}\n```",
            active_retrieval_context.unwrap()
        )),
        name:          Some(String::from("Student")),
        function_call: None,
    });
    messages.push(ChatCompletionRequestMessage {
        role:          Role::System,
        content:       Some(format!(
            include_str!("prompts/retrieval_system_message_outro.md"),
            JAVA_FILE_NAMES = proj.files().iter().map(File::proper_name).join(", "),
            SYNTHESIZED_OUTLINE = proj.describe(),
        )),
        name:          Some(String::from("Instructor")),
        function_call: None,
    });
    let messages = serde_json::to_string(&messages).expect("Failed to serialize messages array");

    let client = reqwest::blocking::Client::new();
    let response: CreateChatCompletionResponse = client
        .post("https://umm-feedback-openai-func.deno.dev/")
        .body(messages)
        .send()?
        .json()?;
    let response = response.choices[0].message.clone();
    println!(" done!");
    ensure!(
        response.function_call.is_some(),
        "No function call found in response."
    );
    let function_call_args: RetrievalFunctionCallParamsArray =
        serde_json::from_str(response.function_call.unwrap().arguments.as_str())?;

    let mut context = Vec::new();
    for function_call_arg in function_call_args.params {
        let file = proj.identify(&function_call_arg.class_name)?;
        let query = format!(
            include_str!("queries/method_body_with_name.scm"),
            &function_call_arg.method_name
        );

        let res = file
            .query(&query)
            .or_else(|_| Ok::<Vec<Dict>, anyhow::Error>(vec![]))
            .unwrap();

        for r in res {
            let body = r.get("body").unwrap().to_string();
            context.push(format!(
                "Method body from student's submission for `{}#{}`:",
                file.proper_name(),
                function_call_arg.method_name
            ));
            context.push(format!("\n```\n{}\n```\n", body));
        }
    }

    Ok(ChatCompletionRequestMessage {
        role:          Role::System,
        content:       Some(context.join("\n")),
        name:          Some(String::from("Instructor")),
        function_call: None,
    })
}

/// Returns a ChatCompletionRequestMessage with the given line references that
/// include contextual lines of code from the source
///
/// * `line_refs`: a vector of LineRef objects
/// * `proj`: a Project object
/// * `start_offset`: the number of lines of code to include before the line
/// * `num_lines`: the number of lines of code to include after the line
/// * `max_line_refs`: the maximum number of _processed_ line references to
///   include in the final message
/// * `try_use_active_retrieval`: whether to try to use active retrieval
/// * `additional_context`: additional context to use for
pub fn get_source_context<T: Into<LineRef>>(
    line_refs: Vec<T>,
    proj: Project,
    start_offset: usize,
    num_lines: usize,
    max_line_refs: usize,
    try_use_active_retrieval: bool,
    active_retrieval_context: Option<String>,
) -> Result<ChatCompletionRequestMessage> {
    if try_use_active_retrieval {
        if let Ok(message) = get_active_retrieval_context(&proj, active_retrieval_context) {
            return Ok(message);
        }
    }

    let mut line_refs: Vec<(File, LineRef, RangeInclusive<usize>)> = line_refs
        .into_iter()
        .flat_map(|x| {
            let x = x.into();
            let file = proj.identify(&x.file_name)?;
            let start = match file.kind() {
                FileType::Test => x.line_number.saturating_sub(num_lines),
                _ => x.line_number.saturating_sub(start_offset),
            };
            let end = start + num_lines;
            Ok::<(File, LineRef, RangeInclusive<usize>), anyhow::Error>((file, x, start..=end))
        })
        .collect();

    line_refs.sort_by(|lhs, rhs| {
        rhs.1
            .file_name
            .cmp(&lhs.1.file_name)
            .then(lhs.1.line_number.cmp(&rhs.1.line_number))
    });
    line_refs.dedup();

    let mut context = Vec::new();
    context.push(
        "You cannot see all of the student's submission as you are an AI language model, with \
         limited context length. Here are some snippets of code the stacktrace indicates might be \
         relevant:
:\n"
        .to_string(),
    );
    let end_ticks = "\n```\n".to_string();
    let mut methods: HashSet<String> = HashSet::new();

    line_refs
        .into_iter()
        .coalesce(|lhs, rhs| {
            if lhs.0 == rhs.0 {
                let lhs_start = *lhs.2.start();
                let lhs_end = *lhs.2.end();
                let rhs_start = *rhs.2.start();
                let rhs_end = *rhs.2.end();
                let expanded_range = rhs_start.saturating_sub(num_lines)..=(rhs_end + num_lines);

                if expanded_range.contains(&lhs_start) || expanded_range.contains(&lhs_end) {
                    Ok((lhs.0, lhs.1, lhs_start..=rhs_end))
                } else {
                    Err((lhs, rhs))
                }
            } else {
                Err((lhs, rhs))
            }
        })
        .take(max_line_refs)
        .for_each(|(file, f, r)| {
            let num_lines = r.size_hint().0;
            let count = file.parser().code().lines().count();

            let (f, r) = if num_lines as f32 >= 0.6 * (count as f32) {
                (f, 0..=count)
            } else {
                (f, r)
            };

            context.push(format!(
                "- Lines {} to {} from {} -\n```",
                *r.start(),
                *r.end(),
                f.file_name
            ));

            let width = (count as f32).log10().ceil() as usize;

            let source_code_lines: Vec<String> =
                file.parser().code().lines().map(String::from).collect();

            let relevant_source = source_code_lines
                .clone()
                .iter()
                .skip(*r.start())
                .take(num_lines)
                .enumerate()
                .map(|(line_n, x)| {
                    format!("{:width$}|{}", *r.start() + line_n, x)
                        .replace("\\\\", "\\")
                        .replace("\\\"", "\"")
                })
                .collect::<Vec<String>>();

            context.append(&mut (relevant_source.clone()));
            context.push(end_ticks.clone());

            match Parser::new(relevant_source.join("\n"), *JAVA_TS_LANG) {
                Ok(parser) => {
                    let method_names: Vec<Dict> = parser
                        .query(METHOD_CALL_QUERY)
                        .or_else(|_| Ok::<Vec<Dict>, anyhow::Error>(vec![]))
                        .unwrap();

                    for method in method_names {
                        let method_name = method.get("name").unwrap().to_string();
                        methods.insert(method_name.clone());

                        let query = format!(
                            include_str!("queries/method_body_with_name.scm"),
                            &method_name
                        );

                        for f in proj.files() {
                            if *f.kind() == FileType::Class || *f.kind() == FileType::ClassWithMain
                            {
                                let res = f
                                    .query(&query)
                                    .or_else(|_| Ok::<Vec<Dict>, anyhow::Error>(vec![]))
                                    .unwrap();

                                for r in res {
                                    let body = r.get("body").unwrap().to_string();
                                    let body_lines =
                                        body.lines().map(String::from).collect::<Vec<_>>();
                                    if body_lines.first().is_some() {
                                        let start_line_number = source_code_lines
                                            .iter()
                                            .find_position(|x| {
                                                x.contains(body_lines.first().unwrap().trim())
                                            })
                                            .unwrap_or((0, &String::new()))
                                            .0;

                                        let body = body_lines
                                            .iter()
                                            .enumerate()
                                            .map(|(line_n, x)| {
                                                if start_line_number != 0 {
                                                    format!(
                                                        "{:width$}|{}",
                                                        start_line_number + line_n + 1,
                                                        x
                                                    )
                                                } else {
                                                    x.to_string()
                                                }
                                            })
                                            .collect::<Vec<String>>()
                                            .join("\n");

                                        context.push(format!(
                                            "Method body from student's submission `{}#{}`:",
                                            f.proper_name(),
                                            method_name
                                        ));
                                        context.push(format!("\n```\n{}\n```\n", body));
                                    }
                                }
                            }
                        }
                    }
                }
                Err(e) => {
                    eprintln!("Error parsing partial source context: {e}");
                }
            };
        });

    let mut context = context.join("\n");
    if context.len() > PROMPT_TRUNCATE {
        context.truncate(PROMPT_TRUNCATE);
        context.push_str("...[TRUNCATED]");
    }

    Ok(ChatCompletionRequestMessage {
        role:          Role::System,
        content:       Some(context),
        name:          Some(String::from("Instructor")),
        function_call: None,
    })
}

#[derive(Clone, Default)]
/// A struct representing arguments to grade_docs function
pub struct DocsGrader {
    /// * `project`: the project to grade
    pub project:  Project,
    /// * `files`: the files to grade
    pub files:    Array,
    /// * `out_of`: the total points for the requirement
    pub out_of:   f64,
    /// * `req_name`: the name of the requirement
    pub req_name: String,
    /// * `penalty`: the penalty to apply for each instance of a violation.
    ///   Optional, default is 3
    pub penalty:  f64,
}

impl DocsGrader {
    /// Getter for project
    pub fn project(&mut self) -> Project {
        self.project.clone()
    }

    /// Setter for project
    pub fn set_project(mut self, project: Project) -> Self {
        self.project = project;
        self
    }

    /// Getter for files
    pub fn files(&mut self) -> Array {
        self.files.clone()
    }

    /// Setter for files
    pub fn set_files(mut self, files: Array) -> Self {
        self.files = files;
        self
    }

    /// Getter for out_of
    pub fn out_of(&mut self) -> f64 {
        self.out_of
    }

    /// Setter for out_of
    pub fn set_out_of(mut self, out_of: f64) -> Self {
        self.out_of = out_of;
        self
    }

    /// Getter for req_name
    pub fn req_name(&mut self) -> String {
        self.req_name.clone()
    }

    /// Setter for req_name
    pub fn set_req_name(mut self, req_name: String) -> Self {
        self.req_name = req_name;
        self
    }

    /// Getter for penalty
    pub fn penalty(&mut self) -> f64 {
        self.penalty
    }

    /// Setter for penalty
    pub fn set_penalty(mut self, penalty: f64) -> Self {
        self.penalty = penalty;
        self
    }

    /// Grades documentation by using the -Xdoclint javac flag.
    /// Scans javac output for generated warnings and grades accordingly.
    #[generate_rhai_variant(Fallible)]
    pub fn grade_docs(self) -> Result<GradeResult> {
        let mut diags = vec![];
        let mut all_diags = vec![];
        let files: Vec<String> = self
            .files
            .iter()
            .map(|f| match f.clone().into_string() {
                Ok(n) => Ok(n),
                Err(e) => Err(anyhow!(
                    "files array has something that's not a string: {}",
                    e
                )),
            })
            .try_collect()?;
        let out_of = self.out_of;
        let mut outputs = vec![];
        for name in &files {
            let file = self.project.identify(name)?;
            let output = match file.doc_check() {
                Ok(o) => o,
                Err(JavaFileError::DuringCompilation {
                    stacktrace,
                    diags,
                }) => {
                    let messages = vec![
                        ChatCompletionRequestMessage {
                            role:          Role::System,
                            content:       Some(SYSTEM_MESSAGE.to_string()),
                            name:          Some(String::from("Instructor")),
                            function_call: None,
                        },
                        ChatCompletionRequestMessage {
                            role:          Role::User,
                            content:       format!("Compiler error -\n```\n{}\n```", stacktrace)
                                .into(),
                            name:          Some(String::from("Student")),
                            function_call: None,
                        },
                        get_source_context(diags, self.project, 1, 3, 6, false, None)?,
                    ];

                    return Ok(GradeResult {
                        requirement: self.req_name,
                        grade:       Grade::new(0.0, out_of),
                        reason:      String::from("See above."),
                        prompt:      Some(messages),
                    });
                }
                Err(e) => {
                    let messages = vec![
                        ChatCompletionRequestMessage {
                            role:          Role::System,
                            content:       SYSTEM_MESSAGE.to_string().into(),
                            name:          Some(String::from("Instructor")),
                            function_call: None,
                        },
                        ChatCompletionRequestMessage {
                            role:          Role::User,
                            content:       format!("Unknown error -\n```\n{:?}\n```", e).into(),
                            name:          Some(String::from("Student")),
                            function_call: None,
                        },
                    ];

                    return Ok(GradeResult {
                        requirement: self.req_name,
                        grade:       Grade::new(0.0, out_of),
                        reason:      String::from("See above."),
                        prompt:      Some(messages),
                    });
                }
            };
            outputs.push(output.clone());
            for line in output.lines() {
                let result = parser::parse_diag(line);
                match result {
                    Ok(res) => {
                        if file.file_name() == res.file_name {
                            diags.push(res.clone());
                        }
                        all_diags.push(res);
                    }
                    Err(_) => continue,
                }
            }
        }

        let penalty = diags.len() as f64 * self.penalty;
        let grade = if out_of - penalty > 0.0 {
            out_of - penalty
        } else {
            0.0
        };

        let num_diags = diags.len();
        eprintln!(
            "{}",
            diags
                .table()
                .with(Panel::header(format!(
                    "Check javadoc for {}",
                    files.join(", ")
                )))
                .with(Panel::footer(format!("-{penalty} due to {num_diags} nits")))
                .with(Modify::new(Rows::new(1..)).with(Width::wrap(24).keep_words()))
                .with(
                    Modify::new(Rows::first())
                        .with(Alignment::center())
                        .with(Alignment::center_vertical()),
                )
                .with(
                    Modify::new(Rows::last())
                        .with(Alignment::center())
                        .with(Alignment::center_vertical()),
                )
                .with(tabled::Style::modern())
        );

        let prompt = if num_diags > 0 {
            let context = get_source_context(all_diags, self.project, 1, 3, 6, false, None)?;

            let mut outputs = outputs
                .iter()
                .map(|output| format!("```\n{output}\n```"))
                .collect::<Vec<String>>()
                .join("\n\n---\n\n");

            if outputs.len() > PROMPT_TRUNCATE {
                outputs.truncate(PROMPT_TRUNCATE);
                outputs.push_str("...[TRUNCATED]");
            }

            Some(vec![
                ChatCompletionRequestMessage {
                    role:          Role::System,
                    content:       SYSTEM_MESSAGE.to_string().into(),
                    name:          Some("Instructor".into()),
                    function_call: None,
                },
                ChatCompletionRequestMessage {
                    role:          Role::User,
                    content:       outputs.into(),
                    name:          Some("Student".into()),
                    function_call: None,
                },
                context,
                ChatCompletionRequestMessage {
                    role:          Role::System,
                    content:       include_str!("prompts/javadoc.md").to_string().into(),
                    name:          Some("Instructor".into()),
                    function_call: None,
                },
            ])
        } else {
            None
        };
        Ok(GradeResult {
            requirement: self.req_name,
            grade: Grade::new(grade, out_of),
            reason: String::from("See above."),
            prompt,
        })
    }
}

#[derive(Clone, Default)]
/// Grades by running tests, and reports how many tests pass.
/// Final grade is the same percentage of maximum grade as the number of tests
/// passing.
pub struct ByUnitTestGrader {
    /// A list of test files to run.
    test_files:     Array,
    /// A list of test names that should be found. Grade returned is 0 if any
    /// are not found.
    expected_tests: Array,
    /// A reference to the project the test files belong to.
    project:        Project,
    /// Maximum possible grade.
    out_of:         f64,
    /// Display name for requirement to use while displaying grade result
    req_name:       String,
}

impl ByUnitTestGrader {
    /// Getter for test_files
    pub fn test_files(&mut self) -> Array {
        self.test_files.clone()
    }

    /// Setter for test_files
    pub fn set_test_files(mut self, test_files: Array) -> Self {
        self.test_files = test_files;
        self
    }

    /// Getter for expected_tests
    pub fn expected_tests(&mut self) -> Array {
        self.expected_tests.clone()
    }

    /// Setter for expected_tests
    pub fn set_expected_tests(mut self, expected_tests: Array) -> Self {
        self.expected_tests = expected_tests;
        self
    }

    /// Getter for project
    pub fn project(&mut self) -> Project {
        self.project.clone()
    }

    /// Setter for project
    pub fn set_project(mut self, project: Project) -> Self {
        self.project = project;
        self
    }

    /// Getter for out_of
    pub fn out_of(&mut self) -> f64 {
        self.out_of
    }

    /// Setter for out_of
    pub fn set_out_of(mut self, out_of: f64) -> Self {
        self.out_of = out_of;
        self
    }

    /// Getter for req_name
    pub fn req_name(&mut self) -> String {
        self.req_name.clone()
    }

    /// Setter for req_name
    pub fn set_req_name(mut self, req_name: String) -> Self {
        self.req_name = req_name;
        self
    }

    #[generate_rhai_variant(Fallible)]
    /// Grades by running tests, and reports how many tests pass.
    /// Final grade is the same percentage of maximum grade as the number of
    /// tests passing.
    pub fn grade_by_tests(self) -> Result<GradeResult> {
        let convert_to_string = |f: Vec<Dynamic>| -> Result<Vec<String>> {
            f.iter()
                .map(|f| match f.clone().into_string() {
                    Ok(n) => Ok(n),
                    Err(e) => Err(anyhow!(
                        "test_files array has something that's not a string: {}",
                        e
                    )),
                })
                .try_collect()
        };

        let project = self.project.clone();
        let out_of = self.out_of;
        let req_name = self.req_name;
        let test_files: Vec<String> = convert_to_string(self.test_files)?;
        let expected_tests: Vec<String> = convert_to_string(self.expected_tests)?;

        let mut reasons = {
            let mut reasons = vec![];
            let mut actual_tests = vec![];
            let mut expected_tests = expected_tests;
            expected_tests.sort();

            for test_file in &test_files {
                let test_file = project.identify(test_file)?;

                actual_tests.append(&mut test_file.test_methods());
            }
            actual_tests.sort();

            if !expected_tests.is_empty() {
                for expected in &expected_tests {
                    let n = expected.split_once('#').unwrap().1;
                    if !actual_tests.contains(expected) {
                        reasons.push(format!("- {n} not found."));
                    }
                }

                for actual in &actual_tests {
                    let n = actual.split_once('#').unwrap().1;
                    if !expected_tests.contains(actual) {
                        reasons.push(format!("- Unexpected test called {n}"));
                    }
                }
            }

            reasons
        };

        let new_user_message = |content: String| {
            let mut content = content;
            if content.len() > PROMPT_TRUNCATE {
                content.truncate(PROMPT_TRUNCATE);
                content.push_str("...[TRUNCATED]");
            }

            ChatCompletionRequestMessage {
                role:          Role::User,
                content:       Some(content),
                name:          Some("Student".into()),
                function_call: None,
            }
        };
        let new_system_message = |content: String| ChatCompletionRequestMessage {
            role:          Role::System,
            content:       Some(content),
            name:          Some("Instructor".into()),
            function_call: None,
        };
        let process_junit_stacktrace = |stacktrace: String| {
            let mut updated_stacktrace = Vec::new();
            let mut all_diags = Vec::new();

            for line in stacktrace.lines() {
                if line.contains("MethodSource") || line.contains("Native Method") {
                    continue;
                }

                if line.contains("Test run finished after") {
                    break;
                }

                if let Ok(diag) = parser::junit_stacktrace_line_ref(line) {
                    if project.identify(&diag.file_name).is_ok() {
                        updated_stacktrace
                            .push(line.replace("\\\\", "\\").replace("\\\"", "\"").to_string());
                    }
                    all_diags.push(diag);
                } else {
                    updated_stacktrace
                        .push(line.replace("\\\\", "\\").replace("\\\"", "\"").to_string());
                }
            }

            (updated_stacktrace, all_diags)
        };

        let initial_message = new_system_message(SYSTEM_MESSAGE.to_string());

        if !reasons.is_empty() {
            reasons.push("Tests will not be run until above is fixed.".into());
            let reasons = reasons.join("\n");
            let messages = vec![initial_message, new_user_message(reasons.clone())];
            Ok(GradeResult {
                requirement: req_name,
                grade:       Grade::new(0.0, out_of),
                reason:      reasons,
                prompt:      Some(messages),
            })
        } else {
            let mut num_tests_passed = 0.0;
            let mut num_tests_total = 0.0;
            let mut messages = vec![initial_message.clone()];

            for test_file in test_files {
                let res = match project
                    .identify(test_file.as_str())?
                    .test(Vec::new(), Some(&project))
                {
                    Ok(res) => res,
                    Err(JavaFileError::FailedTests {
                        test_results,
                        diags,
                    }) => {
                        let (updated_stacktrace, _) =
                            process_junit_stacktrace(test_results.clone());

                        messages.extend(vec![
                            new_user_message(format!(
                                "Failed tests -\n```\n{}\n```",
                                updated_stacktrace.join("\n")
                            )),
                            get_source_context(
                                diags,
                                project.clone(),
                                3,
                                6,
                                6,
                                *USE_ACTIVE_RETRIEVAL.try_get().unwrap_or(&false),
                                Some(updated_stacktrace.join("\n")),
                            )?,
                        ]);

                        test_results
                    }
                    Err(JavaFileError::Unknown(e)) => {
                        let out = format!("Unknown error -\n```\n{:#?}\n```", e);
                        messages.push(new_user_message(out.clone()));
                        out
                    }
                    Err(JavaFileError::DuringCompilation {
                        stacktrace,
                        diags,
                    }) => {
                        let out = format!("Compiler error -\n```\n{}\n```", stacktrace);
                        messages.extend(vec![
                            new_user_message(out.clone()),
                            get_source_context(diags, project.clone(), 3, 6, 6, false, None)?,
                        ]);
                        out
                    }
                    Err(JavaFileError::AtRuntime {
                        output,
                        diags,
                    }) => {
                        let out = format!("Error at runtime -\n```\n{}\n```", output);
                        messages.extend(vec![
                            new_user_message(out.clone()),
                            get_source_context(diags, project.clone(), 3, 6, 6, false, None)?,
                        ]);
                        out
                    }
                };
                let mut current_tests_passed = 0.0;
                let mut current_tests_total = 0.0;

                for line in res.lines() {
                    let parse_result =
                        parser::num_tests_passed(line).context("While parsing Junit summary table");
                    if let Ok(n) = parse_result {
                        current_tests_passed = n as f64;
                    }
                    let parse_result =
                        parser::num_tests_found(line).context("While parsing Junit summary table");
                    if let Ok(n) = parse_result {
                        current_tests_total = n as f64;
                    }
                }

                num_tests_passed += current_tests_passed;
                num_tests_total += current_tests_total;
            }
            let grade = if num_tests_total != 0.0 {
                (num_tests_passed / num_tests_total) * out_of
            } else {
                0.0
            };

            Ok(GradeResult {
                requirement: req_name,
                grade:       Grade::new(grade, out_of),
                reason:      format!("- {num_tests_passed}/{num_tests_total} tests passing."),
                prompt:      Some(messages),
            })
        }
    }
}

#[derive(Clone, Default)]
/// Runs mutation tests using ![Pitest](http://pitest.org/) to grade unit tests written by students.
pub struct UnitTestGrader {
    /// Name of the requirement.
    pub req_name:         String,
    /// Maximum possible grade.
    pub out_of:           f64,
    /// List of test classes to run.
    pub target_test:      Array,
    /// List of classes to mutate.
    pub target_class:     Array,
    /// List of methods to exclude from mutation.
    pub excluded_methods: Array,
    /// List of classes to avoid mutating.
    pub avoid_calls_to:   Array,
}

impl UnitTestGrader {
    /// A getter for the name of the requirement.
    pub fn get_req_name(&mut self) -> String {
        self.req_name.clone()
    }

    /// A getter for the maximum possible grade.
    pub fn get_out_of(&mut self) -> f64 {
        self.out_of
    }

    /// A getter for the list of test classes to run.
    pub fn get_target_test(&mut self) -> Array {
        self.target_test.clone()
    }

    /// A getter for the list of classes to mutate.
    pub fn get_target_class(&mut self) -> Array {
        self.target_class.clone()
    }

    /// A getter for the list of methods to exclude from mutation.
    pub fn get_excluded_methods(&mut self) -> Array {
        self.excluded_methods.clone()
    }

    /// A getter for the list of classes to avoid mutating.
    pub fn get_avoid_calls_to(&mut self) -> Array {
        self.avoid_calls_to.clone()
    }

    /// A setter for the name of the requirement.
    pub fn set_req_name(mut self, req_name: String) -> Self {
        self.req_name = req_name;
        self
    }

    /// A setter for the maximum possible grade.
    pub fn set_out_of(mut self, out_of: f64) -> Self {
        self.out_of = out_of;
        self
    }

    /// A setter for the list of test classes to run.
    pub fn set_target_test(mut self, target_test: Array) -> Self {
        self.target_test = target_test;
        self
    }

    /// A setter for the list of classes to mutate.
    pub fn set_target_class(mut self, target_class: Array) -> Self {
        self.target_class = target_class;
        self
    }

    /// A setter for the list of methods to exclude from mutation.
    pub fn set_excluded_methods(mut self, excluded_methods: Array) -> Self {
        self.excluded_methods = excluded_methods;
        self
    }

    /// A setter for the list of classes to avoid mutating.
    pub fn set_avoid_calls_to(mut self, avoid_calls_to: Array) -> Self {
        self.avoid_calls_to = avoid_calls_to;
        self
    }

    #[generate_rhai_variant(Fallible)]
    /// Runs mutation tests using ![Pitest](http://pitest.org/) to grade unit tests written by students.
    pub fn grade_unit_tests(&mut self) -> Result<GradeResult> {
        let req_name = self.get_req_name();
        let out_of = self.get_out_of();
        let target_test = self.get_target_test();
        let target_class = self.get_target_class();
        let excluded_methods = self.get_excluded_methods();
        let avoid_calls_to = self.get_avoid_calls_to();
        let project = Project::new()?;

        eprintln!("Running Mutation tests -");
        let target_test: Vec<String> = target_test
            .iter()
            .map(|f| match f.clone().into_string() {
                Ok(n) => Ok(n),
                Err(e) => Err(anyhow!(
                    "target_test array has something that's not a string: {}",
                    e
                )),
            })
            .try_collect()?;
        let target_class: Vec<String> = target_class
            .iter()
            .map(|f| match f.clone().into_string() {
                Ok(n) => Ok(n),
                Err(e) => Err(anyhow!(
                    "target_class array has something that's not a string: {}",
                    e
                )),
            })
            .try_collect()?;
        let excluded_methods: Vec<String> = excluded_methods
            .iter()
            .map(|f| match f.clone().into_string() {
                Ok(n) => Ok(n),
                Err(e) => Err(anyhow!(
                    "excluded_methods array has something that's not a string: {}",
                    e
                )),
            })
            .try_collect()?;
        let avoid_calls_to: Vec<String> = avoid_calls_to
            .iter()
            .map(|f| match f.clone().into_string() {
                Ok(n) => Ok(n),
                Err(e) => Err(anyhow!(
                    "avoid_calls_to array has something that's not a string: {}",
                    e
                )),
            })
            .try_collect()?;

        let child = Command::new(java_path()?)
            .args([
                "--class-path",
                classpath()?.as_str(),
                "org.pitest.mutation test.commandline.MutationCoverageReport",
                "--reportDir",
                "test_reports",
                "--failWhenNoMutations",
                "true",
                "--threads",
                "4",
                "--targetClasses",
                target_class.join(",").as_str(),
                "--targetTests",
                target_test.join(",").as_str(),
                "--sourceDirs",
                [
                    SOURCE_DIR.to_str().unwrap_or("."),
                    ROOT_DIR.to_str().unwrap_or("."),
                ]
                .join(",")
                .as_str(),
                "--timestampedReports",
                "false",
                "--outputFormats",
                "HTML,CSV",
                "--mutators",
                "STRONGER",
                "--excludedMethods",
                excluded_methods.join(",").as_str(),
                "--avoidCallsTo",
                avoid_calls_to.join(",").as_str(),
            ])
            .output()
            .context("Failed to spawn javac process.")?;

        if child.status.success() {
            fs::create_dir_all("test_reports")?;
            let file = fs::File::open(ROOT_DIR.join("test_reports").join("mutations.csv"))
                .context("Could not read ./test_reports/mutations.csv file".to_string())?;
            let reader = BufReader::new(file);
            let mut diags = vec![];

            for line in reader.lines() {
                let line = line?;
                let parse_result = parser::mutation_report_row(&line)
                    .context("While parsing test_reports/mutations.csv");

                match parse_result {
                    Ok(r) => {
                        if r.result == "SURVIVED" {
                            diags.push(r);
                        }
                    }
                    Err(e) => {
                        anyhow::bail!(e);
                    }
                };
            }
            let penalty = diags.len() as u32 * 4;
            eprintln!("Ran mutation tests for {} -", target_test.join(", "));
            let num_diags = diags.len();
            eprintln!("Problematic mutation test failures printed about.");

            let prompt = if num_diags > 0 {
                let context = get_source_context(diags.clone(), project, 3, 6, 6, false, None)?;

                let mut feedback = ExpandedDisplay::new(diags).to_string();
                eprintln!("{feedback}");

                if feedback.len() > PROMPT_TRUNCATE {
                    feedback.truncate(PROMPT_TRUNCATE);
                    feedback.push_str("...[TRUNCATED]");
                }

                Some(vec![
                    ChatCompletionRequestMessage {
                        role:          Role::System,
                        content:       SYSTEM_MESSAGE.to_string().into(),
                        name:          Some("Instructor".into()),
                        function_call: None,
                    },
                    // ChatCompletionRequestMessage {
                    //     role:    Role::System,
                    //     content: project.describe(),
                    //     name:    Some("Instructor".into()),
                    // },
                    ChatCompletionRequestMessage {
                        role:          Role::User,
                        content:       feedback.into(),
                        name:          Some("Student".into()),
                        function_call: None,
                    },
                    context,
                    ChatCompletionRequestMessage {
                        role:          Role::System,
                        content:       format!(
                            include_str!("prompts/mutation_testing.md"),
                            test = target_test.join(", "),
                            class = target_class.join(", ")
                        )
                        .into(),
                        name:          Some("Instructor".into()),
                        function_call: None,
                    },
                ])
            } else {
                None
            };

            Ok(GradeResult {
                requirement: req_name,
                grade: Grade::new((out_of as u32).saturating_sub(penalty).into(), out_of),
                reason: format!("-{penalty} Penalty due to surviving mutations"),
                prompt,
            })
        } else {
            let mut output = [
                String::from_utf8(child.stderr)?,
                String::from_utf8(child.stdout)?,
            ]
            .concat();
            eprintln!("{output}");
            if output.len() > PROMPT_TRUNCATE {
                output.truncate(PROMPT_TRUNCATE);
                output.push_str("...[TRUNCATED]");
            }

            let prompt = if !output.is_empty() {
                Some(vec![
                    ChatCompletionRequestMessage {
                        role:          Role::System,
                        content:       SYSTEM_MESSAGE.to_string().into(),
                        name:          Some("Instructor".into()),
                        function_call: None,
                    },
                    // ChatCompletionRequestMessage {
                    //     role:    Role::System,
                    //     content: project.describe(),
                    //     name:    Some("Instructor".into()),
                    // },
                    ChatCompletionRequestMessage {
                        role:          Role::User,
                        content:       Some(output),
                        name:          Some("Student".into()),
                        function_call: None,
                    },
                    ChatCompletionRequestMessage {
                        role:          Role::System,
                        content:       format!(
                            include_str!("prompts/mutation_testing_2.md"),
                            test = target_test.join(", "),
                            class = target_class.join(", ")
                        )
                        .into(),
                        name:          Some("Instructor".into()),
                        function_call: None,
                    },
                ])
            } else {
                None
            };
            Ok(GradeResult {
                requirement: req_name,
                grade: Grade::new(0.0, out_of),
                reason: String::from(
                    "Something went wrong while running mutation tests, skipping.",
                ),
                prompt,
            })
        }
    }
}

#[derive(Clone, Default)]
/// Grades using hidden tests. Test file is downloaded, ran, and then cleaned up
/// before returning.
pub struct ByHiddenTestGrader {
    /// URL to download test source from.
    pub url:             String,
    /// name of hidden test class.
    pub test_class_name: String,
    /// points to give if all tests pass.
    pub out_of:          f64,
    /// name of requirement.
    pub req_name:        String,
}

impl ByHiddenTestGrader {
    /// gets the `url` field.
    pub fn url(&mut self) -> String {
        self.url.clone()
    }

    /// sets the `url` field.
    pub fn set_url(mut self, url: String) -> Self {
        self.url = url;
        self
    }

    /// gets the `test_class_name` field
    pub fn test_class_name(&mut self) -> String {
        self.test_class_name.clone()
    }

    /// sets the `test_class_name` field
    pub fn set_test_class_name(mut self, test_class_name: String) -> Self {
        self.test_class_name = test_class_name;
        self
    }

    /// gets the `out_of` field
    pub fn out_of(&mut self) -> f64 {
        self.out_of
    }

    /// sets the `out_of` field
    pub fn set_out_of(mut self, out_of: f64) -> Self {
        self.out_of = out_of;
        self
    }

    /// gets the `req_name` field
    pub fn req_name(&mut self) -> String {
        self.req_name.clone()
    }

    /// sets the `req_name` field
    pub fn set_req_name(mut self, req_name: String) -> Self {
        self.req_name = req_name;
        self
    }

    #[generate_rhai_variant(Fallible)]
    /// Grades using hidden tests. Test file is downloaded, ran, and then
    /// cleaned up before returning.
    pub fn grade_by_hidden_tests(&mut self) -> Result<GradeResult> {
        let url = self.url();
        let test_class_name = self.test_class_name();
        let out_of = self.out_of();
        let req_name = self.req_name();

        let test_source = reqwest::blocking::get(&url)
            .context(format!("Failed to download {url}"))?
            .bytes()
            .context(format!("Failed to get response as bytes: {url}"))?;

        let path = ROOT_DIR.join(format!("{test_class_name}.java"));
        let mut file = fs::File::create(&path)?;
        file.write_all(&test_source)?;

        let project = match Project::new() {
            Ok(a) => a,
            Err(e) => {
                fs::remove_file(&path)?;
                return Err(e);
            }
        };

        let grader = ByUnitTestGrader {
            test_files: vec![Dynamic::from(test_class_name)],
            expected_tests: Array::new(),
            project,
            out_of,
            req_name,
        };

        let out = match grader.grade_by_tests() {
            Ok(o) => o,
            Err(e) => {
                fs::remove_file(&path)?;
                return Err(e);
            }
        };

        fs::remove_file(&path)?;
        Ok(out)
    }
}

/// Represents output format settings for Gradescope submissions.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum GradescopeOutputFormat {
    /// Plain text format.
    Text,
    /// HTML format.
    Html,
    /// This is very similar to the "html" format option but will also convert
    /// \n into <br /> and \n\n+ into a page break.
    SimpleFormat,
    /// Markdown format.
    Md,
    /// ANSI format for including ANSI escape codes (often used in terminal
    /// outputs).
    Ansi,
}

/// Represents visibility settings for Gradescope submissions and test cases.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum GradescopeVisibility {
    /// Hidden from students.
    Hidden,
    /// Visible after the due date of the assignment.
    AfterDueDate,
    /// Visible after the grades are published.
    AfterPublished,
    /// Always visible to students.
    Visible,
}

/// Represents the status of a test case in Gradescope submissions.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum GradescopeStatus {
    /// Indicates the test case passed successfully.
    Passed,
    /// Indicates the test case failed.
    Failed,
}

/// Represents the overall submission data.
#[derive(Serialize, Deserialize, Debug, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[builder(doc)]
pub struct GradescopeSubmission {
    /// Optional overall score. Overrides total of test cases if specified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score: Option<f64>,

    /// Optional execution time in seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_time: Option<u32>,

    /// Optional text relevant to the entire submission.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,

    /// Optional output format settings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_format: Option<GradescopeOutputFormat>,

    /// Optional default output format for test case outputs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_output_format: Option<GradescopeOutputFormat>,

    /// Optional default output format for test case names.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_name_format: Option<GradescopeOutputFormat>,

    /// Optional visibility setting.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<GradescopeVisibility>,

    /// Optional stdout visibility setting.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdout_visibility: Option<GradescopeVisibility>,

    /// Optional extra data to be stored.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<serde_json::Value>,

    /// Optional test cases.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tests: Option<Vec<GradescopeTestCase>>,

    /// Optional leaderboard setup.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub leaderboard: Option<Vec<GradescopeLeaderboardEntry>>,
}

/// Represents an individual test case.
#[derive(Serialize, Deserialize, Debug, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[builder(doc)]
pub struct GradescopeTestCase {
    /// Optional score for the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score: Option<f64>,

    /// Optional maximum score for the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_score: Option<f64>,

    /// Optional status of the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<GradescopeStatus>,

    /// Optional name of the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Optional formatting for the test case name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_format: Option<GradescopeOutputFormat>,

    /// Optional number for the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub number: Option<String>,

    /// Optional detailed output for the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,

    /// Optional formatting for the test case output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_format: Option<GradescopeOutputFormat>,

    /// Optional tags associated with the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,

    /// Optional visibility setting for the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<GradescopeVisibility>,

    /// Optional extra data to be stored with the test case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<serde_json::Value>,
}

/// Represents an entry in the leaderboard.
#[derive(Serialize, Deserialize, Debug, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[builder(doc)]
pub struct GradescopeLeaderboardEntry {
    /// Name of the leaderboard metric.
    pub name: String,

    /// Value of the leaderboard metric.
    pub value: String,

    /// Optional ordering for the leaderboard metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order: Option<String>,
}

/// What kind of file the SLO is for.
#[derive(Debug)]
enum SLOFileType {
    /// Only source files.
    Source,
    /// Only test files.
    Test,
    /// Both source and test files.
    SourceAndTest,
}

#[generate_rhai_variant(Fallible)]
/// Print grade result
///
/// * `results`: array of GradeResults to print in a table.
/// * `gradescope_config`: map of gradescope configuration options, which can
///   contain:
///     - `source_files`: array of source files to provide feedback on in the
///       submission. Defaults to empty array.
///     - `test_files`: array of test files to provide feedback on in the
///       submission. Defaults to empty array.
///     - `project_title`: title of the project. Defaults to empty string.
///     - `project_description`: description of the project. Defaults to empty
///       string.
///     - `pass_threshold`: threshold for passing the project. Defaults to 0.7.
///     - `show_table`: whether to show the grading table. Defaults to true.
///     - `results_json`: whether to write the gradescope results in JSON
///       format. Defaults to false.
///     - `feedback`: whether to provide feedback on penalties to students.
///       Defaults to false.
///     - `leaderboard`: whether to produce leaderboard entries. Also produces
///       relevant SLO feedback. Defaults to false.
///     - `debug`: whether to write gradescope JSON within the current
///       directory. Defaults to false.
///     - `slo_algorithmic_solutions`: whether to provide feedback on
///       Algorithmic Solutions SLO. Defaults to false.
///     - `slo_code_readability`: whether to provide feedback on Code
///       Readability and Formatting SLO. Defaults to false.
///     - `slo_comments`: whether to provide feedback on Comments SLO. Defaults
///       to false.
///     - `slo_error_handling`: whether to provide feedback on Error Handling
///       SLO. Defaults to false.
///     - `slo_logic`: whether to provide feedback on Logic SLO. Defaults to
///       false.
///     - `slo_naming_conventions`: whether to provide feedback on Naming
///       Conventions SLO. Defaults to false.
///     - `slo_oop_programming`: whether to provide feedback on Object Oriented
///       Programming SLO. Defaults to false.
///     - `slo_syntax`: whether to provide feedback on Syntax SLO. Defaults to
///       false.
///     - `slo_testing`: whether to provide feedback on Testing SLO. Defaults to
///       false.
pub fn show_result(results: Array, gradescope_config: rhai::Map) -> Result<()> {
    let results: Vec<GradeResult> = results
        .iter()
        .map(|f| f.clone().cast::<GradeResult>())
        .collect();
    let source_files = gradescope_config
        .get("source_files")
        .unwrap_or(&Dynamic::from(Array::new()))
        .clone()
        .cast::<Array>()
        .iter()
        .map(|f| f.clone().cast::<String>())
        .collect::<Vec<String>>();

    let test_files = gradescope_config
        .get("test_files")
        .unwrap_or(&Dynamic::from(Array::new()))
        .clone()
        .cast::<Array>()
        .iter()
        .map(|f| f.clone().cast::<String>())
        .collect::<Vec<String>>();

    let project_title = gradescope_config
        .get("project_title")
        .unwrap_or(&Dynamic::from(String::new()))
        .clone()
        .cast::<String>();
    let project_description = gradescope_config
        .get("project_description")
        .unwrap_or(&Dynamic::from(String::new()))
        .clone()
        .cast::<String>();
    let pass_threshold = gradescope_config
        .get("pass_threshold")
        .unwrap_or(&Dynamic::from(0.7))
        .clone()
        .cast::<f64>();

    let get_or_default = |f: &str, d: bool| -> bool {
        gradescope_config
            .get(f)
            .unwrap_or(&Dynamic::from(d))
            .clone()
            .cast::<bool>()
    };
    let show_table = get_or_default("show_table", true);
    let gradescope_json = get_or_default("results_json", false);
    let gradescope_feedback = get_or_default("feedback", false);
    let gradescope_leaderboard = get_or_default("leaderboard", false);
    let gradescope_debug = get_or_default("debug", false);

    let slos = vec![
        (
            "slo_algorithmic_solutions",
            "Algorithmic Solutions",
            ALGORITHMIC_SOLUTIONS_SLO.as_str(),
            SLOFileType::Source,
        ),
        (
            "slo_code_readability",
            "Code Readability and Formatting",
            CODE_READABILITY_SLO.as_str(),
            SLOFileType::SourceAndTest,
        ),
        (
            "slo_comments",
            "Comments",
            COMMENTS_WRITTEN_SLO.as_str(),
            SLOFileType::SourceAndTest,
        ),
        (
            "slo_error_handling",
            "Error Handling",
            ERROR_HANDLING_SLO.as_str(),
            SLOFileType::SourceAndTest,
        ),
        (
            "slo_logic",
            "Logic",
            LOGIC_SLO.as_str(),
            SLOFileType::Source,
        ),
        (
            "slo_naming_conventions",
            "Naming Conventions",
            NAMING_CONVENTIONS_SLO.as_str(),
            SLOFileType::SourceAndTest,
        ),
        (
            "slo_oop_programming",
            "Object Oriented Programming",
            OBJECT_ORIENTED_PROGRAMMING_SLO.as_str(),
            SLOFileType::Source,
        ),
        (
            "slo_sytax",
            "Syntax",
            SYNTAX_SLO.as_str(),
            SLOFileType::SourceAndTest,
        ),
        (
            "slo_testing",
            "Testing",
            TESTING_SLO.as_str(),
            SLOFileType::Test,
        ),
    ];

    let (grade, out_of) = results.iter().fold((0f64, 0f64), |acc, r| {
        (acc.0 + r.grade.grade, acc.1 + r.grade.out_of)
    });

    if show_table {
        eprintln!(
            "{}",
            results
                .clone()
                .table()
                .with(Panel::header("Grading Overview"))
                .with(Panel::footer(format!("Total: {grade:.2}/{out_of:.2}")))
                .with(Modify::new(Rows::new(1..)).with(Width::wrap(24).keep_words()))
                .with(
                    Modify::new(Rows::first())
                        .with(Alignment::center())
                        .with(Alignment::center_vertical()),
                )
                .with(
                    Modify::new(Rows::last())
                        .with(Alignment::center())
                        .with(Alignment::center_vertical()),
                )
                .with(tabled::Style::modern())
        );
    }

    if gradescope_json {
        let project = Project::new()?;
        let mut test_cases = vec![];
        for result in results {
            let mut result = result.clone();

            let feedback = if gradescope_feedback {
                generate_single_feedback(&result)?
            } else {
                String::new()
            };

            let test_case = GradescopeTestCase::builder()
                .name(result.requirement())
                .name_format(GradescopeOutputFormat::Text)
                .max_score(result.out_of())
                .score(result.grade())
                .status(if result.grade() > pass_threshold * result.out_of() {
                    GradescopeStatus::Passed
                } else {
                    GradescopeStatus::Failed
                })
                .output(feedback)
                .output_format(GradescopeOutputFormat::Md)
                .build();

            test_cases.push(test_case);
        }

        let leaderboard_entries = if gradescope_leaderboard {
            let runtime = RUNTIME.handle().clone();

            if grade > pass_threshold * out_of {
                ensure!(
                    !project_title.is_empty(),
                    "Project title must be specified to generate SLO feedback",
                );
                ensure!(
                    !project_description.is_empty(),
                    "Project description must be specified to generate SLO feedback",
                );

                let mut leaderboard_entries = Vec::new();
                let mut slo_requests = Vec::new();

                for (slo_key, slo_name, slo_system_message, slo_file_type) in slos {
                    if !get_or_default(slo_key, false) {
                        continue;
                    }
                    let relevant_files: Vec<File> = match slo_file_type {
                        SLOFileType::Source => source_files
                            .iter()
                            .filter_map(|x| project.identify(x).ok())
                            .collect(),
                        SLOFileType::Test => test_files
                            .iter()
                            .filter_map(|x| project.identify(x).ok())
                            .collect(),
                        SLOFileType::SourceAndTest => source_files
                            .iter()
                            .chain(test_files.clone().iter())
                            .filter_map(|x| project.identify(x).ok())
                            .collect(),
                    };

                    let relevant_file_codes: Vec<String> = relevant_files
                        .clone()
                        .into_iter()
                        .map(|x| x.parser().code())
                        .collect();

                    ensure!(
                        !relevant_file_codes.is_empty(),
                        "No relevant files ({:?}) with source code found for SLO {}",
                        slo_file_type,
                        slo_key
                    );

                    let mut student_message = vec![format!(
                        "# Submission for {project_title}\n\nDescription: {project_description}"
                    )];

                    relevant_files
                        .into_iter()
                        .zip(relevant_file_codes)
                        .for_each(|(file, code)| {
                            student_message.push(format!(
                                "\n\n## Contents of {file_name}\n\n```java\n{code}\n```",
                                file_name = file.proper_name(),
                                code = code
                            ));
                        });

                    let student_message = student_message.join("\n\n");
                    let messages = vec![
                        ChatCompletionRequestMessage {
                            role:          Role::System,
                            content:       slo_system_message.to_string().into(),
                            name:          Some("Instructor".into()),
                            function_call: None,
                        },
                        ChatCompletionRequestMessage {
                            role:          Role::User,
                            content:       student_message.into(),
                            name:          Some("Student".into()),
                            function_call: None,
                        },
                    ];

                    slo_requests.push(runtime.spawn(async move {
                        let together_client = async_openai::Client::with_config(
                            OpenAIConfig::new()
                                .with_api_base(
                                    std::env::var("OPENAI_ENDPOINT")
                                        .expect("OPENAI_ENDPOINT must be set for SLO feedback"),
                                )
                                .with_api_key(
                                    std::env::var("OPENAI_API_KEY_SLO")
                                        .expect("OPENAI_API_KEY_SLO must be set for SLO feedback"),
                                ),
                        );
                        let together_client = together_client.chat();

                        (
                            slo_name,
                            together_client
                                .create(CreateChatCompletionRequest {
                                    model: std::env::var("OPENAI_MODEL")
                                        .expect("OPENAI_MODEL must be set for SLO feedback"),
                                    messages: messages.clone(),
                                    temperature: Some(0.0),
                                    top_p: Some(1.0),
                                    n: Some(1),
                                    stream: Some(false),
                                    // max_tokens: Some(3072),
                                    ..Default::default()
                                })
                                .await,
                        )
                    }));
                }

                let slo_requests = slo_requests.into_iter().collect::<FuturesUnordered<_>>();
                let slo_responses = runtime.block_on(async { try_join_all(slo_requests).await })?;

                for (name, resp) in slo_responses {
                    let resp = resp?
                        .choices
                        .first()
                        .unwrap()
                        .message
                        .content
                        .clone()
                        .unwrap_or_default();

                    let proficiency = if resp.contains("### Proficiency: *****") {
                        String::from("*****")
                    } else if resp.contains("### Proficiency: ****") {
                        String::from("****")
                    } else if resp.contains("### Proficiency: ***") {
                        String::from("***")
                    } else if resp.contains("### Proficiency: **") {
                        String::from("**")
                    } else if resp.contains("### Proficiency: *") {
                        String::from("*")
                    } else {
                        String::from("")
                    };

                    test_cases.push(
                        GradescopeTestCase::builder()
                            .name(name.to_string())
                            .name_format(GradescopeOutputFormat::Text)
                            .output(resp.clone())
                            .output_format(GradescopeOutputFormat::Md)
                            .max_score(0f64)
                            .score(0f64)
                            .build(),
                    );

                    leaderboard_entries.push(
                        GradescopeLeaderboardEntry::builder()
                            .name(name.to_string())
                            .value(proficiency)
                            .build(),
                    );
                }

                Some(leaderboard_entries)
            } else {
                Some(
                    slos.iter()
                        .filter_map(|(slo_key, slo_name, _, _)| {
                            if get_or_default(slo_key, false) {
                                Some(
                                    GradescopeLeaderboardEntry::builder()
                                        .name(slo_name.to_string())
                                        .value(String::new())
                                        .build(),
                                )
                            } else {
                                None
                            }
                        })
                        .collect::<Vec<GradescopeLeaderboardEntry>>(),
                )
            }
        } else {
            None
        };

        let submission = GradescopeSubmission::builder()
            .tests(Some(test_cases))
            .test_output_format(GradescopeOutputFormat::Md)
            .test_name_format(GradescopeOutputFormat::Text)
            .stdout_visibility(GradescopeVisibility::Visible)
            .visibility(GradescopeVisibility::Visible)
            .leaderboard(leaderboard_entries)
            .build();

        let mut file = fs::File::create(if gradescope_debug {
            "./results.json"
        } else {
            "/autograder/results/results.json"
        })?;
        file.write_all(serde_json::to_string_pretty(&submission)?.as_bytes())?;
    }

    Ok(())
}

#[derive(Clone, Default)]
/// string. Any difference results in a `0` grade.
/// A grader that grades by diffing an `expected` string with an `actual`
pub struct DiffGrader {
    /// name of requirement
    pub req_name:    String,
    /// points to give if all tests pass
    pub out_of:      f64,
    /// the project to grade
    pub project:     Project,
    /// Java file to run
    pub file:        String,
    /// the expected output
    pub expected:    Array,
    /// the actual output
    pub input:       Array,
    /// ignore case when comparing
    pub ignore_case: bool,
}

impl DiffGrader {
    /// creates a new DiffGrader
    pub fn new() -> Self {
        Self::default()
    }

    /// gets the `req_name` field
    pub fn req_name(&mut self) -> String {
        self.req_name.clone()
    }

    /// sets the `req_name` field
    pub fn set_req_name(mut self, req_name: String) -> Self {
        self.req_name = req_name;
        self
    }

    /// gets the `out_of` field
    pub fn out_of(&mut self) -> f64 {
        self.out_of
    }

    /// sets the `out_of` field
    pub fn set_out_of(mut self, out_of: f64) -> Self {
        self.out_of = out_of;
        self
    }

    /// gets the `expected` field
    pub fn expected(&mut self) -> Array {
        self.expected.clone()
    }

    /// sets the `expected` field
    pub fn set_expected(mut self, expected: Array) -> Self {
        self.expected = expected;
        self
    }

    /// gets the `actual` field
    pub fn input(&mut self) -> Array {
        self.input.clone()
    }

    /// sets the `actual` field
    pub fn set_input(mut self, input: Array) -> Self {
        self.input = input;
        self
    }

    /// gets the `project` field
    pub fn project(&mut self) -> Project {
        self.project.clone()
    }

    /// sets the `project` field
    pub fn set_project(mut self, project: Project) -> Self {
        self.project = project;
        self
    }

    /// gets the `file` field
    pub fn file(&mut self) -> String {
        self.file.clone()
    }

    /// sets the `file` field
    pub fn set_file(mut self, file: String) -> Self {
        self.file = file;
        self
    }

    /// gets the `ignore_case` field
    pub fn ignore_case(&mut self) -> bool {
        self.ignore_case
    }

    /// sets the `ignore_case` field
    pub fn set_ignore_case(mut self, ignore_case: bool) -> Self {
        self.ignore_case = ignore_case;
        self
    }

    #[generate_rhai_variant(Fallible)]
    /// Grades by diffing the `expected` and `actual` strings.
    pub fn grade_by_diff(&mut self) -> Result<GradeResult> {
        ensure!(
            !self.expected.is_empty() & !self.input.is_empty(),
            "At least one test case (input-expected pair) must be provided"
        );
        ensure!(
            self.expected.len() == self.input.len(),
            "expected and input case arrays must be of the same length"
        );

        let file = self.project.identify(&self.file)?;
        let mut prompts = vec![];

        for (expected, input) in self.expected.iter().zip(self.input.iter()) {
            let expected = {
                let expected = expected.clone().cast::<String>();
                if self.ignore_case {
                    expected.to_lowercase().trim().to_string()
                } else {
                    expected.trim().to_string()
                }
            };
            let input = input.clone().cast::<String>();

            let actual_out = {
                let out = match file.run(Some(input.clone())) {
                    Ok(out) => out,
                    Err(JavaFileError::AtRuntime {
                        output,
                        diags,
                    }) => {
                        let messages = vec![
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       SYSTEM_MESSAGE.to_string().into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                            ChatCompletionRequestMessage {
                                role:          Role::User,
                                content:       format!(
                                    "Error while running -\n```\n{}\n```",
                                    output
                                )
                                .into(),
                                name:          Some("Student".into()),
                                function_call: None,
                            },
                            get_source_context(diags, self.project.clone(), 3, 6, 6, false, None)?,
                        ];
                        return Ok(GradeResult {
                            requirement: self.req_name.clone(),
                            grade:       Grade::new(0.0, self.out_of),
                            reason:      "Error running file for some cases.".to_string(),
                            prompt:      Some(messages),
                        });
                    }
                    Err(JavaFileError::DuringCompilation {
                        stacktrace,
                        diags,
                    }) => {
                        let messages = vec![
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       SYSTEM_MESSAGE.to_string().into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                            ChatCompletionRequestMessage {
                                role:          Role::User,
                                content:       format!(
                                    "Error while compiling -\n```\n{}\n```",
                                    stacktrace
                                )
                                .into(),
                                name:          Some("Student".into()),
                                function_call: None,
                            },
                            get_source_context(diags, self.project.clone(), 3, 6, 6, false, None)?,
                        ];
                        return Ok(GradeResult {
                            requirement: self.req_name.clone(),
                            grade:       Grade::new(0.0, self.out_of),
                            reason:      "Error compiling file for some cases.".to_string(),
                            prompt:      Some(messages),
                        });
                    }
                    Err(e) => {
                        let messages = vec![
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       SYSTEM_MESSAGE.to_string().into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                            ChatCompletionRequestMessage {
                                role:          Role::User,
                                content:       format!("Unknown error -\n```\n{:?}\n```", e).into(),
                                name:          Some("Student".into()),
                                function_call: None,
                            },
                        ];
                        return Ok(GradeResult {
                            requirement: self.req_name.clone(),
                            grade:       Grade::new(0.0, self.out_of),
                            reason:      "Unknown error while running file for some cases."
                                .to_string(),
                            prompt:      Some(messages),
                        });
                    }
                };

                if self.ignore_case {
                    out.to_lowercase().trim().to_string()
                } else {
                    out.trim().to_string()
                }
            };

            let diff = diff_unicode_words(Algorithm::Patience, &expected, &actual_out);

            let mut is_equal = true;
            let mut expected = String::new();
            let mut actual = String::new();

            for (change, value) in diff {
                match change {
                    ChangeTag::Equal => {
                        expected.push_str(value);
                        actual.push_str(value);
                    }
                    ChangeTag::Insert => {
                        actual.push_str(format!("{}", value.green()).as_str());
                        if !value.trim().is_empty() {
                            is_equal = false;
                        }
                    }
                    ChangeTag::Delete => {
                        expected.push_str(format!("{}", value.red()).as_str());
                        if !value.trim().is_empty() {
                            is_equal = false;
                        }
                    }
                }
            }

            if !is_equal {
                let prompt = format!(
                    "Comparing expected and actual output for \
                     {}:\n```{inp}Expected:\n{}\nActual:\n{}\n```\n",
                    file.file_name(),
                    expected,
                    actual,
                    inp = if self.input.is_empty() {
                        String::new()
                    } else {
                        format!("\nInput:\n`{}`\n", input)
                    },
                );

                eprintln!("{prompt}");
                prompts.push(prompt);
            }
        }

        if prompts.is_empty() {
            Ok(GradeResult {
                requirement: self.req_name.clone(),
                grade:       Grade {
                    grade:  self.out_of,
                    out_of: self.out_of,
                },
                reason:      "Got expected output".to_string(),
                prompt:      None,
            })
        } else {
            let context = format!(
                "{prompt}\n\nSource code:\n```java\n{code}\n```\nMy tests are failing due to the \
                 above.",
                prompt = prompts.join("\n\n"),
                code = file.parser().code()
            );

            Ok(GradeResult {
                requirement: self.req_name.clone(),
                grade:       Grade {
                    grade:  0.0,
                    out_of: self.out_of,
                },
                reason:      "See above.".to_string(),
                prompt:      Some(vec![
                    ChatCompletionRequestMessage {
                        role:          Role::System,
                        content:       SYSTEM_MESSAGE.to_string().into(),
                        name:          Some("Instructor".into()),
                        function_call: None,
                    },
                    ChatCompletionRequestMessage {
                        role:          Role::System,
                        content:       Some(context),
                        name:          Some("Student".into()),
                        function_call: None,
                    },
                ]),
            })
        }
    }
}

/// Schema for `prompts` table
#[derive(Serialize, Debug)]
pub struct PromptRow {
    /// UUID of data entry
    id:               String,
    /// ChatGPT message prompt
    messages:         Option<Vec<ChatCompletionRequestMessage>>,
    /// Name of the autograder requirement
    requirement_name: String,
    /// Reasons for penalty
    reason:           String,
    /// Grade/out_of as a string
    grade:            String,
    /// Status of prompt response generation - not_started, started, completed
    status:           String,
}

#[generate_rhai_variant(Fallible)]
/// Generates feedback for a single `GradeResult` and posts it to the database.
fn generate_single_feedback(result: &GradeResult) -> Result<String> {
    let rt = RUNTIME.handle().clone();

    if result.grade.grade < result.grade.out_of {
        let id = uuid::Uuid::new_v4().to_string();
        let mut result = result.clone();
        let body = PromptRow {
            id:               id.clone(),
            messages:         result.prompt(),
            requirement_name: result.requirement(),
            reason:           result.reason(),
            grade:            result.grade.to_string(),
            status:           "not_started".into(),
        };

        let messages = serde_json::to_string(&body)?;

        // Post to the database
        rt.block_on(async {
            POSTGREST_CLIENT
                .from("prompts")
                .insert(messages)
                .execute()
                .await
        })?;

        // Return feedback URL
        Ok(format!(
            "- For explanation and feedback on `{}` (refer rubric), please \
             see this link - https://feedback.dhruvdh.com/{}",
            result.requirement(),
            id
        ))
    } else {
        Ok(String::from(
            "This type of feedback cannot be generated for submissions without penalty.",
        ))
    }
}

#[generate_rhai_variant(Fallible)]
/// Generates a FEEDBACK file after prompting ChatGPT for feedback on an array
/// of results.
pub fn generate_feedback(results: Array) -> Result<()> {
    let mut feedback = vec!["## Understanding Your Autograder Results\n".to_string()];

    for result in results.iter().map(|f| f.clone().cast::<GradeResult>()) {
        match generate_single_feedback(&result) {
            Ok(fb) => feedback.push(fb),
            Err(e) => eprintln!("Error generating feedback: {}", e),
        }
    }

    if !feedback.is_empty() {
        let feedback = feedback.join("\n");
        fs::write("FEEDBACK", &feedback).context("Something went wrong writing FEEDBACK file.")?;
        eprintln!("{}", &feedback);
    } else {
        fs::write(
            "FEEDBACK",
            "This type of feedback cannot be generated for submissions without penalty.",
        )
        .context("Something went wrong writing FEEDBACK file.")?;
    }

    Ok(())
}

#[derive(Default, Debug, Clone)]
/// A struct to represent a treesitter query.
pub struct Query {
    /// The query to run.
    query:   String,
    /// The capture to extract from the query.
    capture: String,
    /// A function pointer to filter the matches using. Must return a boolean.
    filter:  Option<FnPtr>,
}

impl Query {
    /// Creates a new query with default values (empty strings).
    pub fn new() -> Self {
        Self::default()
    }

    /// Gets the query to run.
    pub fn query(&self) -> String {
        unescape(&format!("{:#?}", self.query)).unwrap()
    }

    /// Sets the query to run.
    pub fn set_query(mut self, query: String) -> Self {
        self.query = query;
        self
    }

    /// Gets the captures to extract from the query.
    pub fn capture(&self) -> String {
        self.capture.clone()
    }

    /// Sets the captures to extract from the query.
    pub fn set_capture(mut self, capture: String) -> Self {
        self.capture = capture;
        self
    }

    /// Gets the function to filter the results of the query.
    pub fn filter(&self) -> Option<FnPtr> {
        self.filter.clone()
    }

    /// Set the function to filter the results of the query.
    pub fn set_filter(mut self, filter: FnPtr) -> Self {
        self.filter = Some(filter);
        self
    }
}

/// An enum to represent possible errors when running a query.
#[derive(thiserror::Error, Debug)]
pub enum QueryError {
    /// No file was selected to run the query on.
    #[error("No file was selected to run the query on.")]
    NoFileSelected,
    /// No capture was selected to extract from the query.
    #[error("No capture was selected to extract from the query: {0}")]
    NoCaptureSelected(String),
    /// No previous query to add capture or filter to.
    #[error("No previous query to add capture or filter to.")]
    NoPreviousQuery,
    /// The file selected to run the query on does not exist.
    #[error("The file selected (`{0}`) to run the query on could not be found.")]
    FileNotFound(String),
    /// The query could not be run.
    #[error(
        "This query could not be run, likely due to a syntax \
         error.\nQuery:\n```\n{q}\n```\nError:\n```\n{e}\n```"
    )]
    DuringQueryExecution {
        /// The query that could not be run.
        q: String,
        /// The error that occurred.
        e: String,
    },
    /// No matches found for a previously selected capture, all subsequent
    /// queries will return nothing.
    #[error(
        "No matches found for a previously selected capture: `{0}`, all subsequent queries will \
         return nothing."
    )]
    NoMatchesFound(String),
    /// Unknown error.
    #[error("Unknown error: {0}")]
    Unknown(#[from] anyhow::Error),
}

#[derive(Default, Clone)]
/// An enum to represent the constraint of a query.
pub enum QueryConstraint {
    #[default]
    /// The query must match at least once.
    MustMatchAtLeastOnce,
    /// The query must match exactly once.
    MustMatchExactlyNTimes(usize),
    /// Must not match.
    MustNotMatch,
}

#[derive(Default, Clone)]
/// A struct to represent a query grader.
pub struct QueryGrader {
    /// The name of the requirement.
    req_name:   String,
    /// The grade for the requirement.
    out_of:     f64,
    /// The queries to run.
    queries:    Vec<Query>,
    /// The input to run the queries on.
    project:    Project,
    /// The file to run the query on.
    file:       String,
    /// The constraint of the query.
    constraint: QueryConstraint,
    /// The reason to share with the student.
    reason:     String,
}

impl QueryGrader {
    /// Creates a new query grader with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Gets the name of the requirement.
    pub fn req_name(&self) -> &str {
        &self.req_name
    }

    /// Sets the name of the requirement.
    pub fn set_req_name(mut self, req_name: String) -> Self {
        self.req_name = req_name;
        self
    }

    /// Gets the "out of" grade for the requirement.
    pub fn out_of(&self) -> f64 {
        self.out_of
    }

    /// Sets the "out of" grade for the requirement.
    pub fn set_out_of(mut self, out_of: f64) -> Self {
        self.out_of = out_of;
        self
    }

    /// Gets the file to run the query on.
    pub fn file(&self) -> &str {
        &self.file
    }

    /// Sets the file to run the query on.
    pub fn set_file(mut self, file: String) -> Self {
        self.file = file;
        self
    }

    /// Gets the project to run the query on.
    pub fn project(&self) -> &Project {
        &self.project
    }

    /// Sets the project to run the query on.
    pub fn set_project(mut self, project: Project) -> Self {
        self.project = project;
        self
    }

    /// Gets the queries to run.
    pub fn queries(&self) -> Vec<Query> {
        self.queries.clone()
    }

    /// Gets the constraint of the query.
    pub fn constraint(&self) -> QueryConstraint {
        self.constraint.clone()
    }

    /// Sets the constraint of the query to "must match at least once".
    pub fn must_match_at_least_once(mut self) -> Self {
        self.constraint = QueryConstraint::MustMatchAtLeastOnce;
        self
    }

    /// Sets the constraint of the query to "must match exactly n times".
    pub fn must_match_exactly_n_times(mut self, n: usize) -> Self {
        self.constraint = QueryConstraint::MustMatchExactlyNTimes(n);
        self
    }

    /// Sets the constraint of the query to "must not match".
    pub fn must_not_match(mut self) -> Self {
        self.constraint = QueryConstraint::MustNotMatch;
        self
    }

    /// Gets the reason to share with the student.
    pub fn reason(&self) -> &str {
        &self.reason
    }

    /// Sets the reason to share with the student.
    pub fn set_reason(mut self, reason: String) -> Self {
        self.reason = reason;
        self
    }

    #[generate_rhai_variant(Fallible)]
    /// Adds a query to run.
    /// If no file has been selected, this will throw an error.
    pub fn query(#[allow(unused_mut)] mut self, q: String) -> Result<Self, QueryError> {
        if self.file.is_empty() {
            return Err(QueryError::NoFileSelected);
        }

        self.queries.push(Query {
            query:   q,
            capture: String::new(),
            filter:  None,
        });

        Ok(self)
    }

    #[generate_rhai_variant(Fallible)]
    /// Adds a capture to the last query.
    /// If no queries have been added, this will throw an error.
    pub fn capture(#[allow(unused_mut)] mut self, c: String) -> Result<Self, QueryError> {
        if let Some(last) = self.queries.last_mut() {
            *last = last.clone().set_capture(c);
            Ok(self)
        } else {
            Err(QueryError::NoPreviousQuery)
        }
    }

    #[generate_rhai_variant(Fallible)]
    /// Adds a capture to the last query.
    /// If no queries have been added, this will throw an error.
    pub fn filter(#[allow(unused_mut)] mut self, f: FnPtr) -> Result<Self, QueryError> {
        if let Some(last) = self.queries.last_mut() {
            *last = last.clone().set_filter(f);
            Ok(self)
        } else {
            Err(QueryError::NoPreviousQuery)
        }
    }

    /// Selects entire method body and returns
    pub fn method_body_with_name(mut self, method_name: String) -> Self {
        self.queries.push(Query {
            query:   format!(
                include_str!("queries/method_body_with_name.scm"),
                method_name
            ),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects entire method body and returns
    pub fn method_body_with_return_type(mut self, return_type: String) -> Self {
        self.queries.push(Query {
            query:   format!(
                include_str!("queries/method_body_with_return_type.scm"),
                return_type
            ),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects and returns the entire main method
    pub fn main_method(mut self) -> Self {
        self.queries.push(Query {
            query:   include_str!("queries/main_method.scm").to_string(),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects entire class body with name
    pub fn class_body_with_name(mut self, class_name: String) -> Self {
        self.queries.push(Query {
            query:   format!(include_str!("queries/class_with_name.scm"), class_name),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects local variable declaration statements
    pub fn local_variables(mut self) -> Self {
        self.queries.push(Query {
            query:   String::from("((local_variable_declaration) @var)"),
            capture: "var".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects local variable declaration statements with supplied name
    pub fn local_variables_with_name(mut self, name: String) -> Self {
        self.queries.push(Query {
            query:   format!(include_str!("queries/local_variable_with_name.scm"), name),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects local variable declaration statements with supplied type
    pub fn local_variables_with_type(mut self, type_name: String) -> Self {
        self.queries.push(Query {
            query:   format!(
                include_str!("queries/local_variable_with_type.scm"),
                type_name
            ),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects if statements (entire, including else if and else)
    pub fn if_statements(mut self) -> Self {
        self.queries.push(Query {
            query:   String::from("((if_statement) @if)"),
            capture: "if".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects for loops
    pub fn for_loops(mut self) -> Self {
        self.queries.push(Query {
            query:   String::from("((for_statement) @for)"),
            capture: "for".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects while loops
    pub fn while_loops(mut self) -> Self {
        self.queries.push(Query {
            query:   String::from("((while_statement) @while)"),
            capture: "while".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects method invocations
    pub fn method_invocations(mut self) -> Self {
        self.queries.push(Query {
            query:   include_str!("queries/method_invocation.scm").to_string(),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects method invocations with supplied name
    pub fn method_invocations_with_name(mut self, name: String) -> Self {
        self.queries.push(Query {
            query:   format!(
                include_str!("queries/method_invocations_with_name.scm"),
                name
            ),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects method invocations with supplied arguments
    pub fn method_invocations_with_arguments(mut self, name: String) -> Self {
        self.queries.push(Query {
            query:   format!(
                include_str!("queries/method_invocations_with_arguments.scm"),
                name
            ),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    /// Selects method invocations with supplied object
    pub fn method_invocations_with_object(mut self, name: String) -> Self {
        self.queries.push(Query {
            query:   format!(
                include_str!("queries/method_invocations_with_object.scm"),
                name
            ),
            capture: "body".to_string(),
            filter:  None,
        });
        self
    }

    #[generate_rhai_variant(Fallible)]
    /// Runs the queries, and returns the result.
    /// TODO: Make it so that it doesn't parse a new piece of code, just filters
    /// out the irrelevant line ranges. This performs better but more
    /// importantly is more accurate.
    pub fn run_query(&self) -> Result<Dynamic, QueryError> {
        let engine = create_engine();
        let ast = std::sync::Arc::clone(&SCRIPT_AST);
        let ast = ast.lock().unwrap();

        let first = self
            .queries
            .first()
            .ok_or_else(|| QueryError::NoMatchesFound("No queries to run".to_string()))?;

        let file = self
            .project
            .identify(self.file())
            .map_err(|_| QueryError::FileNotFound(self.file().to_string()))?;

        let mut matches: Vec<String> = match file.query(&first.query()) {
            Ok(m) => {
                if first.capture().is_empty() {
                    return Err(QueryError::NoCaptureSelected(format!("{:#?}", first)));
                }
                let result = m
                    .iter()
                    .filter_map(|map| map.get(&first.capture()))
                    .cloned();

                let result: Vec<String> = if let Some(f) = first.filter() {
                    result
                        .filter(|x| f.call(&engine, &ast, (x.clone(),)).unwrap_or(false))
                        .collect()
                } else {
                    result.collect()
                };

                if m.is_empty() {
                    return Err(QueryError::NoMatchesFound(
                        unescape(&format!("{:#?}", first)).context("Unescape error")?,
                    ));
                }
                result
            }
            Err(e) => {
                return Err(QueryError::DuringQueryExecution {
                    q: first.query(),
                    e: format!("{:#?}", e),
                })
            }
        };

        if self.queries.len() == 1 {
            return Ok(matches.into());
        }

        for (prev_q, q) in self.queries().into_iter().tuple_windows() {
            if matches.is_empty() {
                return Err(QueryError::NoMatchesFound(
                    unescape(&format!("{:#?}", prev_q)).context("Unescape error")?,
                ));
            }

            if q.capture().is_empty() {
                return Err(QueryError::NoCaptureSelected(format!("{:#?}", q)));
            }

            let mut new_matches = vec![];

            for code in matches {
                let parser = Parser::new(code, *JAVA_TS_LANG).context(format!(
                    "Failed to create parser for query: `{}`",
                    q.query()
                ))?;

                match parser.query(&q.query()) {
                    Ok(m) => {
                        let result = m.iter().filter_map(|map| map.get(&q.capture())).cloned();

                        let mut result: Vec<String> = if let Some(f) = q.filter() {
                            result
                                .filter(|x| f.call(&engine, &ast, (x.clone(),)).unwrap_or(false))
                                .collect()
                        } else {
                            result.collect()
                        };

                        new_matches.append(&mut result)
                    }
                    Err(e) => {
                        return Err(QueryError::DuringQueryExecution {
                            q: q.query(),
                            e: format!("{:#?}", e),
                        })
                    }
                };
            }

            matches = new_matches;
        }

        Ok(matches.into())
    }

    #[generate_rhai_variant(Fallible)]
    /// Grades the file according to the supplied queries, captures, and
    /// constraints.
    pub fn grade_by_query(self) -> Result<GradeResult> {
        let reason = if self.reason.trim().is_empty() {
            eprintln!(
                "Warning: No reason provided for query grading. Feedback to student will not be \
                 very helpful."
            );
            match self.constraint {
                QueryConstraint::MustMatchAtLeastOnce => {
                    "Query Constraint: Must match at least once.".to_string()
                }
                QueryConstraint::MustMatchExactlyNTimes(n) => {
                    format!("Query Constraint: Must match exactly {n} times.")
                }
                QueryConstraint::MustNotMatch => "Query Constraint: Must not match.".to_string(),
            }
        } else {
            self.reason.to_string()
        };

        let result: Vec<String> = match self.run_query() {
            Ok(r) => {
                let r: Array = r.cast();
                r.into_iter().map(|s| s.cast()).collect()
            }
            Err(e) => {
                return Ok(GradeResult {
                    requirement: self.req_name.clone(),
                    grade: Grade {
                        grade:  0.0,
                        out_of: self.out_of,
                    },
                    reason,
                    prompt: Some(vec![
                        ChatCompletionRequestMessage {
                            role:          Role::System,
                            content:       SYSTEM_MESSAGE.to_string().into(),
                            name:          Some("Instructor".into()),
                            function_call: None,
                        },
                        ChatCompletionRequestMessage {
                            role:          Role::System,
                            content:       format!(
                                "Something went wrong when using treesitter queries to grade \
                                 `{}`. Error message:\n\n```\n{}\n```\n",
                                self.file, e
                            )
                            .into(),
                            name:          Some("Instructor".into()),
                            function_call: None,
                        },
                    ]),
                })
            }
        };

        match self.constraint {
            QueryConstraint::MustMatchAtLeastOnce => {
                if result.is_empty() {
                    Ok(GradeResult {
                        requirement: self.req_name.clone(),
                        grade: Grade {
                            grade:  0.0,
                            out_of: self.out_of,
                        },
                        reason,
                        prompt: Some(vec![
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       SYSTEM_MESSAGE.to_string().into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       format!(
                                    "For file `{}`: {}.",
                                    self.file, self.reason
                                )
                                .into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                        ]),
                    })
                } else {
                    Ok(GradeResult {
                        requirement: self.req_name.clone(),
                        grade: Grade {
                            grade:  self.out_of,
                            out_of: self.out_of,
                        },
                        reason,
                        prompt: None,
                    })
                }
            }
            QueryConstraint::MustMatchExactlyNTimes(n) => {
                if result.len() == n {
                    Ok(GradeResult {
                        requirement: self.req_name.clone(),
                        grade: Grade {
                            grade:  self.out_of,
                            out_of: self.out_of,
                        },
                        reason,
                        prompt: None,
                    })
                } else {
                    Ok(GradeResult {
                        requirement: self.req_name.clone(),
                        grade: Grade {
                            grade:  0.0,
                            out_of: self.out_of,
                        },
                        reason,
                        prompt: Some(vec![
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       SYSTEM_MESSAGE.to_string().into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       format!("For file `{}`: {}", self.file, self.reason)
                                    .into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                        ]),
                    })
                }
            }
            QueryConstraint::MustNotMatch => {
                if result.is_empty() {
                    Ok(GradeResult {
                        requirement: self.req_name.clone(),
                        grade: Grade {
                            grade:  self.out_of,
                            out_of: self.out_of,
                        },
                        reason,
                        prompt: None,
                    })
                } else {
                    Ok(GradeResult {
                        requirement: self.req_name.clone(),
                        grade: Grade {
                            grade:  0.0,
                            out_of: self.out_of,
                        },
                        reason,
                        prompt: Some(vec![
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       SYSTEM_MESSAGE.to_string().into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                            ChatCompletionRequestMessage {
                                role:          Role::System,
                                content:       format!("For file `{}`: {}", self.file, self.reason)
                                    .into(),
                                name:          Some("Instructor".into()),
                                function_call: None,
                            },
                        ]),
                    })
                }
            }
        }
    }
}

// Allowed because CustomType is volatile, not deprecated
#[allow(deprecated)]
/// Allows registering custom types with Rhai.
impl CustomType for Grade {
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("Grade")
            .with_fn("grade", Self::grade)
            .with_fn("grade", Self::set_grade)
            .with_fn("out_of", Self::out_of)
            .with_fn("out_of", Self::set_out_of)
            .with_fn("new_grade", Self::new)
            .with_fn("from_string", Self::grade_from_string_script)
            .with_fn("to_string", Self::to_string);
    }
}

// Allowed because CustomType is volatile, not deprecated
#[allow(deprecated)]
/// Allows registering custom types with Rhai.
impl CustomType for GradeResult {
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("GradeResult")
            .with_fn("requirement", Self::requirement)
            .with_fn("requirement", Self::set_requirement)
            .with_fn("grade", Self::grade)
            .with_fn("grade", Self::set_grade)
            .with_fn("out_of", Self::out_of)
            .with_fn("out_of", Self::set_out_of)
            .with_fn("reason", Self::reason)
            .with_fn("reason", Self::set_reason)
            .with_fn("new_grade_result", Self::default);
    }
}

// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
/// Allows registering custom types with Rhai
impl CustomType for DocsGrader {
    /// Builds a custom type to be registered with Rhai
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("DocsGrader")
            .with_fn("req_name", Self::req_name)
            .with_fn("req_name", Self::set_req_name)
            .with_fn("project", Self::project)
            .with_fn("project", Self::set_project)
            .with_fn("files", Self::files)
            .with_fn("files", Self::set_files)
            .with_fn("out_of", Self::out_of)
            .with_fn("out_of", Self::set_out_of)
            .with_fn("penalty", Self::penalty)
            .with_fn("penalty", Self::set_penalty)
            .with_fn("new_docs_grader", Self::default)
            .with_fn("run", Self::grade_docs_script);
    }
}

// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
/// Allows registering custom types with Rhai
impl CustomType for ByUnitTestGrader {
    /// Builds a custom type to be registered with Rhai
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("ByUnitTestGrader")
            .with_fn("test_files", Self::test_files)
            .with_fn("test_files", Self::set_test_files)
            .with_fn("project", Self::project)
            .with_fn("project", Self::set_project)
            .with_fn("expected_tests", Self::expected_tests)
            .with_fn("expected_tests", Self::set_expected_tests)
            .with_fn("out_of", Self::out_of)
            .with_fn("out_of", Self::set_out_of)
            .with_fn("req_name", Self::req_name)
            .with_fn("req_name", Self::set_req_name)
            .with_fn("new_by_unit_test_grader", Self::default)
            .with_fn("run", Self::grade_by_tests_script);
    }
}

// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
/// Allows registering custom types with Rhai
impl CustomType for UnitTestGrader {
    /// Builds a custom type to be registered with Rhai
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("UnitTestGrader")
            .with_fn("req_name", Self::get_req_name)
            .with_fn("req_name", Self::set_req_name)
            .with_fn("out_of", Self::get_out_of)
            .with_fn("out_of", Self::set_out_of)
            .with_fn("target_test", Self::get_target_test)
            .with_fn("target_test", Self::set_target_test)
            .with_fn("target_class", Self::get_target_class)
            .with_fn("target_class", Self::set_target_class)
            .with_fn("excluded_methods", Self::get_excluded_methods)
            .with_fn("excluded_methods", Self::set_excluded_methods)
            .with_fn("avoid_calls_to", Self::get_avoid_calls_to)
            .with_fn("avoid_calls_to", Self::set_avoid_calls_to)
            .with_fn("new_unit_test_grader", Self::default)
            .with_fn("run", Self::grade_unit_tests_script);
    }
}

// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
/// Allows registering custom types with Rhai.
impl CustomType for ByHiddenTestGrader {
    /// Builds a custom type to be registered with Rhai.
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("ByHiddenTestGrader")
            .with_fn("url", Self::url)
            .with_fn("url", Self::set_url)
            .with_fn("test_class_name", Self::test_class_name)
            .with_fn("test_class_name", Self::set_test_class_name)
            .with_fn("out_of", Self::out_of)
            .with_fn("out_of", Self::set_out_of)
            .with_fn("req_name", Self::req_name)
            .with_fn("req_name", Self::set_req_name)
            .with_fn("new_by_hidden_test_grader", Self::default)
            .with_fn("run", Self::grade_by_hidden_tests_script);
    }
}

// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
/// Allows registering custom types with Rhai.
impl CustomType for DiffGrader {
    /// Builds a custom type to be registered with Rhai.
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("DiffGrader")
            .with_fn("req_name", Self::req_name)
            .with_fn("req_name", Self::set_req_name)
            .with_fn("out_of", Self::out_of)
            .with_fn("out_of", Self::set_out_of)
            .with_fn("expected", Self::expected)
            .with_fn("expected", Self::set_expected)
            .with_fn("input", Self::input)
            .with_fn("input", Self::set_input)
            .with_fn("project", Self::project)
            .with_fn("project", Self::set_project)
            .with_fn("file", Self::file)
            .with_fn("file", Self::set_file)
            .with_fn("ignore_case", Self::ignore_case)
            .with_fn("ignore_case", Self::set_ignore_case)
            .with_fn("new_diff_grader", Self::default)
            .with_fn("run", Self::grade_by_diff_script);
    }
}

// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
/// Allows registering custom types with Rhai.
impl CustomType for Query {
    /// Builds a custom type to be registered with Rhai.
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("Query")
            .with_fn("new_query", Self::new)
            .with_fn("query", Self::query)
            .with_fn("query", Self::set_query)
            .with_fn("capture", Self::capture)
            .with_fn("capture", Self::set_capture);
    }
}

// Allowed because CustomType is not deprecated, just volatile
#[allow(deprecated)]
/// Allows registering custom types with Rhai.
impl CustomType for QueryGrader {
    /// Builds a custom type to be registered with Rhai.
    fn build(mut builder: rhai::TypeBuilder<Self>) {
        builder
            .with_name("QueryGrader")
            .with_fn("req_name", Self::req_name)
            .with_fn("req_name", Self::set_req_name)
            .with_fn("out_of", Self::out_of)
            .with_fn("out_of", Self::set_out_of)
            .with_fn("file", Self::file)
            .with_fn("file", Self::set_file)
            .with_fn("project", Self::project)
            .with_fn("project", Self::set_project)
            .with_fn("queries", Self::queries)
            .with_fn("query", Self::query_script)
            .with_fn("capture", Self::capture_script)
            .with_fn("reason", Self::reason)
            .with_fn("reason", Self::set_reason)
            .with_fn("must_match_at_least_once", Self::must_match_at_least_once)
            .with_fn(
                "must_match_exactly_n_times",
                Self::must_match_exactly_n_times,
            )
            .with_fn("must_not_match", Self::must_not_match)
            .with_fn("method_body_with_name", Self::method_body_with_name)
            .with_fn(
                "method_body_with_return_type",
                Self::method_body_with_return_type,
            )
            .with_fn("main_method", Self::main_method)
            .with_fn("class_body_with_name", Self::class_body_with_name)
            .with_fn("local_variables", Self::local_variables)
            .with_fn("local_variables_with_name", Self::local_variables_with_name)
            .with_fn("local_variables_with_type", Self::local_variables_with_type)
            .with_fn("if_statements", Self::if_statements)
            .with_fn("for_loops", Self::for_loops)
            .with_fn("while_loops", Self::while_loops)
            .with_fn("method_invocations", Self::method_invocations)
            .with_fn(
                "method_invocations_with_name",
                Self::method_invocations_with_name,
            )
            .with_fn(
                "method_invocations_with_arguments",
                Self::method_invocations_with_arguments,
            )
            .with_fn(
                "method_invocations_with_object",
                Self::method_invocations_with_object,
            )
            .with_fn("filter", Self::filter_script)
            .with_fn("run_query", Self::run_query_script)
            .with_fn("run", Self::grade_by_query_script)
            .with_fn("new_query_grader", Self::default);
    }
}