battler 0.9.1

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

use anyhow::Result;
use battler_data::{
    Boost,
    BoostTable,
    DefaultTrueBool,
    Fraction,
    Gender,
    Id,
    Identifiable,
    MoveTarget,
    Nature,
    PartialStatTable,
    Stat,
    StatOrderIterator,
    StatTable,
    SwitchType,
    Type,
};
use hashbrown::{
    HashMap,
    HashSet,
};
use serde::{
    Deserialize,
    Serialize,
};
use zone_alloc::ElementRef;

use crate::{
    battle::{
        CoreBattle,
        MonContext,
        MonHandle,
        MoveHandle,
        MoveOutcome,
        Player,
        SelectReason,
        Side,
        SpeedOrderable,
        calculate_hidden_power_type,
        calculate_mon_stats,
        core_battle::{
            CatchEntry,
            FaintEntry,
        },
        core_battle_actions,
        core_battle_effects,
        core_battle_logs,
        mon_states,
    },
    battle_log_entry,
    dex::Dex,
    effect::{
        AppliedEffectHandle,
        AppliedEffectLocation,
        EffectHandle,
        LinkedEffectsManager,
        fxlang,
    },
    error::{
        WrapOptionError,
        WrapResultError,
        general_error,
    },
    log::{
        BattleLoggable,
        UncommittedBattleLogEntry,
    },
    mons::Species,
    moves::Move,
    teams::MonData,
};

fn default_ball() -> String {
    return "Poké Ball".to_owned();
}

/// The physical details of a [`Mon`].
///
/// Copied by "Illusion."
#[derive(Debug, Clone)]
pub struct PhysicalMonDetails {
    pub name: String,
    pub species: String,
    pub gender: Gender,
    pub shiny: bool,
}

/// Public [`Mon`] details, which are shared to both sides of a battle when the Mon
/// appears or during Team Preview.
#[derive(Debug, Clone)]
pub struct PublicMonDetails {
    pub physical_details: PhysicalMonDetails,
    pub level: u8,
}

impl BattleLoggable for PublicMonDetails {
    fn log(&self, entry: &mut UncommittedBattleLogEntry) {
        entry.set("species", self.physical_details.species.clone());
        entry.set("level", self.level);
        entry.set("gender", &self.physical_details.gender);
        if self.physical_details.shiny {
            entry.add_flag("shiny");
        }
    }
}

/// Public details for an active [`Mon`], which are shared to both sides of a battle when the Mon
/// appears in the battle.
#[derive(Debug, Clone)]
pub struct ActiveMonDetails {
    pub public_details: PublicMonDetails,
    pub player_id: String,
    pub side_position: usize,
    pub health: String,
    pub status: String,
    pub tera: Option<Type>,
}

impl BattleLoggable for ActiveMonDetails {
    fn log(&self, entry: &mut UncommittedBattleLogEntry) {
        entry.set("player", self.player_id.clone());
        entry.set("position", self.side_position);
        entry.set("name", self.public_details.physical_details.name.clone());
        entry.set("health", &self.health);
        if !self.status.is_empty() {
            entry.set("status", &self.status);
        }
        if let Some(tera) = self.tera {
            entry.set("tera", tera);
        }
        self.public_details.log(entry);
    }
}

/// Public details for an active [`Mon`]'s position.
pub struct MonPositionDetails {
    pub name: String,
    pub player_id: String,
    pub side_position: Option<usize>,
}

impl Display for MonPositionDetails {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.side_position {
            Some(position) => write!(f, "{},{},{}", self.name, self.player_id, position),
            None => write!(f, "{},{}", self.name, self.player_id),
        }
    }
}

/// A single move slot for a Mon.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MoveSlot {
    pub id: Id,
    pub name: String,
    pub pp: u8,
    pub max_pp: u8,
    pub target: MoveTarget,
    pub typ: Type,
    pub disabled: bool,
    pub used: bool,
    pub simulated: bool,
}

impl MoveSlot {
    /// Creates a new move slot.
    pub fn new(id: Id, name: String, pp: u8, max_pp: u8, target: MoveTarget, typ: Type) -> Self {
        Self {
            id,
            name,
            pp,
            max_pp,
            target,
            typ,
            disabled: false,
            used: false,
            simulated: false,
        }
    }

    /// Creates a new simulated move slot.
    pub fn new_simulated(
        id: Id,
        name: String,
        pp: u8,
        max_pp: u8,
        target: MoveTarget,
        typ: Type,
    ) -> Self {
        Self {
            id,
            name,
            typ,
            pp,
            max_pp,
            target,
            disabled: false,
            used: false,
            simulated: true,
        }
    }
}

/// The effective ability of a [`Mon`][`crate::battle::Mon`].
#[derive(Debug, Default, Clone)]
pub struct EffectiveAbility {
    /// Ability ID.
    pub id: Id,
    /// Any sub-abilities.
    pub sub_abilities: Vec<Id>,
}

/// A single ability slot for a Mon.
#[derive(Debug, Default, Clone)]
pub struct AbilitySlot {
    pub ability: EffectiveAbility,
    pub effect_state: fxlang::EffectState,
}

/// Data for a single move on a [`Mon`].
///
/// Makes a copy of underlying data so that it can be stored on move requests.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MonMoveSlotData {
    pub id: Id,
    pub name: String,
    pub pp: u8,
    pub max_pp: u8,
    pub target: MoveTarget,
    #[serde(rename = "type")]
    pub typ: Type,
    pub disabled: bool,
}

impl MonMoveSlotData {
    pub fn from(context: &mut MonContext, move_slot: &MoveSlot) -> Result<Self> {
        let mon_handle = context.mon_handle();
        let mov = context.battle().dex.moves.get_by_id(&move_slot.id)?;
        let name = mov.data.name.clone();
        let id = mov.id().clone();
        // Some moves may have a special target, depending on the user's type (e.g., Curse).
        let (target, typ) = core_battle_actions::run_in_using_move_state(context, |context| {
            let target =
                core_battle_effects::run_effect_event_with_options::<_, _, Option<MoveTarget>>(
                    context,
                    fxlang::BattleEvent::MoveTargetOverride,
                    (),
                    core_battle_effects::RunEffectEventOptions {
                        effects: Vec::from_iter([AppliedEffectHandle::new(
                            EffectHandle::InactiveMove(move_slot.id.clone()),
                            AppliedEffectLocation::MonInactiveMove(mon_handle),
                        )]),
                    },
                )
                .unwrap_or(move_slot.target);
            let typ =
                core_battle_actions::move_type_for_display(context, &id).unwrap_or(move_slot.typ);
            (target, typ)
        });

        let mut disabled = move_slot.disabled;
        if move_slot.pp == 0 {
            disabled = true;
        }
        Ok(Self {
            name,
            id,
            pp: move_slot.pp,
            max_pp: move_slot.max_pp,
            target,
            typ,
            disabled,
        })
    }
}

/// Persistent battle state for a single [`Move`] on a [`Mon`].
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MonPersistentMoveData {
    pub name: String,
    pub pp: u8,
}

/// Data about a single [`Mon`]'s summary, which is its out-of-battle state.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MonSummaryData {
    pub name: String,
    pub species: String,
    pub level: u8,
    pub gender: Gender,
    pub nature: Nature,
    pub shiny: bool,
    pub ball: Option<String>,
    pub hp: u16,
    pub friendship: u8,
    pub experience: u32,
    pub stats: StatTable,
    pub evs: StatTable,
    pub ivs: StatTable,
    pub moves: Vec<MonPersistentMoveData>,
    pub ability: String,
    pub item: Option<String>,
    pub status: Option<String>,
    pub hidden_power_type: Type,
}

/// Data about a single [`Mon`]'s battle state.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MonBattleData {
    pub summary: MonSummaryData,
    pub species: String,
    pub hp: u16,
    pub max_hp: u16,
    pub health: String,
    pub types: Vec<Type>,
    pub active: bool,
    pub player_team_position: usize,
    pub player_effective_team_position: usize,
    pub player_active_position: Option<usize>,
    pub side_position: Option<usize>,
    pub stats: PartialStatTable,
    pub boosts: BoostTable,
    pub moves: Vec<MonMoveSlotData>,
    pub ability: String,
    pub item: Option<String>,
    pub status: Option<String>,
}

/// Request for a single [`Mon`] to move.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MonMoveRequest {
    pub team_position: usize,
    pub moves: Vec<MonMoveSlotData>,
    #[serde(default)]
    pub z_moves: Vec<Option<MonMoveSlotData>>,
    #[serde(default)]
    pub max_moves: Vec<MonMoveSlotData>,
    #[serde(default)]
    pub trapped: bool,
    #[serde(default)]
    pub can_mega_evolve: bool,
    #[serde(default)]
    pub can_z_move: bool,
    #[serde(default)]
    pub can_ultra_burst: bool,
    #[serde(default)]
    pub can_dynamax: bool,
    #[serde(default)]
    pub can_terastallize: bool,
    #[serde(default)]
    pub locked_into_move: bool,
}

/// Request for a single [`Mon`] to learn a move.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MonLearnMoveRequest {
    pub team_position: usize,
    pub id: Id,
    pub name: String,
}

/// An interface that implements [`SpeedOrderable`][`crate::battle::SpeedOrderable`] for [`Mon`]s.
pub struct SpeedOrderableMon {
    pub mon_handle: MonHandle,
    pub speed: u32,
    pub ability_effect_order: u32,
}

impl SpeedOrderable for SpeedOrderableMon {
    fn order(&self) -> u32 {
        0
    }

    fn priority(&self) -> i32 {
        0
    }

    fn sub_priority(&self) -> i32 {
        0
    }

    fn speed(&self) -> u32 {
        self.speed
    }

    fn sub_order(&self) -> u32 {
        self.ability_effect_order
    }
}

/// Information about a single attack received by a [`Mon`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReceivedAttackEntry {
    pub source: MonHandle,
    pub source_side: usize,
    pub source_position: usize,
    pub damage: u16,
    pub turn: u64,
}

/// The context of an effect that is triggering a stat calculation.
#[derive(Clone)]
pub struct CalculateStatContext {
    pub effect: EffectHandle,
    pub source: MonHandle,
}

/// How a Mon exited the battle.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum MonExitType {
    Fainted,
    Caught,
}

/// Policy for a Mon's HP should be updated when recalculating stats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecalculateStatsHpPolicy {
    DoNotUpdate,
    KeepHealthRatio { silent: bool },
    KeepHealthRatioCeiling,
    KeepDamageTaken { silent: bool },
}

impl RecalculateStatsHpPolicy {
    fn keep_health_ratio(&self) -> bool {
        match self {
            Self::KeepHealthRatio { .. } | Self::KeepHealthRatioCeiling => true,
            _ => false,
        }
    }

    fn use_ceil(&self) -> bool {
        match self {
            Self::KeepHealthRatioCeiling => true,
            _ => false,
        }
    }

    fn silent(&self) -> bool {
        match self {
            Self::KeepHealthRatio { silent } | Self::KeepDamageTaken { silent } => *silent,
            _ => false,
        }
    }
}

/// The type of forme change the Mon has undergone.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MonSpecialFormeChangeType {
    MegaEvolution,
    PrimalReversion,
    UltraBurst,
    Gigantamax,
}

/// State for the Mon going into the next turn.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct MonNextTurnState {
    pub locked_move: Option<String>,
    pub trapped: bool,
    pub cannot_receive_items: bool,
    pub can_mega_evolve: bool,
    pub can_z_move: bool,
    pub can_ultra_burst: bool,
    pub can_dynamax: bool,
    pub can_terastallize: bool,
}

/// Switch data for a Mon.
#[derive(Debug, Default, Clone)]
pub struct MonSwitchState {
    /// The Mon needs to switch out at the end of the turn.
    pub needs_switch: Option<SwitchType>,
    /// The Mon is forced to switch out immediately.
    pub force_switch: Option<SwitchType>,
    /// The `BeforeSwitchOut` event already ran so it should be skipped.
    pub skip_before_switch_out: bool,
    /// The Mon is switched out.
    pub being_called_back: bool,
    /// The Mon is switching in.
    pub switching_in: bool,
}

/// Cache for move slot effects.
#[derive(Debug, Default, Clone)]
pub struct MoveSlotEffectCache {
    pub typ: Option<Type>,
}

/// Cache for Mon effects.
#[derive(Debug, Default, Clone)]
pub struct MonEffectCache {
    pub effective_types: Option<Vec<Type>>,
    pub effective_types_no_added_type: Option<Vec<Type>>,
    pub effective_types_before_forced_types: Option<Vec<Type>>,
    pub effective_tera_type: Option<Type>,

    pub effective_ability: Option<Option<EffectiveAbility>>,
    pub effective_item: Option<Option<Id>>,

    pub effective_weather: Option<Option<Id>>,
    pub effective_terrain: Option<Option<Id>>,

    pub override_weather: Option<Option<Id>>,

    pub berry_eating_health: Option<u16>,
    pub can_heal: Option<bool>,
    pub can_suppress_ability: Option<bool>,
    pub can_suppress_item: Option<bool>,
    pub is_asleep: Option<bool>,
    pub is_away_from_field: Option<bool>,
    pub is_behind_substitute: Option<bool>,
    pub is_choice_locked: Option<bool>,
    pub is_contact_proof: Option<bool>,
    pub is_grounded: Option<bool>,
    pub is_immune_to_entry_hazards: Option<bool>,
    pub is_soundproof: Option<bool>,
    pub is_semi_invulnerable: Option<bool>,

    pub move_slot_effects: HashMap<Id, MoveSlotEffectCache>,
}

/// Volatile state for a Mon.
#[derive(Debug, Default, Clone)]
pub struct MonVolatileState {
    /// The current species.
    pub species: Id,
    /// The weight of the Mon.
    pub weight: u32,

    /// Current base stats.
    pub base_stored_stats: StatTable,
    /// Current stats.
    pub stats: StatTable,
    /// Current stat boosts.
    pub boosts: BoostTable,
    /// Current speed.
    pub speed: u32,

    /// Volatile effect state for the Mon.
    pub volatile_mon_effect_state: fxlang::EffectState,
    /// Current moves.
    pub move_slots: Vec<MoveSlot>,
    /// Current types.
    pub types: Vec<Type>,
    /// Added type.
    pub added_type: Option<Type>,
    /// The current ability.
    pub ability_slot: AbilitySlot,
    /// Effect state for the item.
    pub item_state: fxlang::EffectState,
    /// The last item used.
    pub last_item: Option<Id>,
    /// Volatile statuses.
    pub volatiles: HashMap<Id, fxlang::EffectState>,

    /// Is the Mon transformed into another?
    pub transformed: bool,
    /// The Mon's physical appearance.
    pub illusion: Option<PhysicalMonDetails>,

    /// The Mon is using a move.
    pub using_move: bool,
    /// The last move selected.
    pub last_move_selected: Option<Id>,
    /// The last move used for the Mon.
    pub last_move: Option<MoveHandle>,
    /// The last move used by the Mon, which can be different from `last_move` if that
    /// move executed a different move (like Metronome).
    pub last_move_used: Option<MoveHandle>,

    /// The outcome of a move used this turn.
    pub move_this_turn_outcome: Option<MoveOutcome>,
    /// The outcome of a move used last turn.
    pub move_last_turn_outcome: Option<MoveOutcome>,
    /// The last position targeted by a move.
    pub last_move_target_location: Option<isize>,

    /// Was the Mon damaged this turn?
    pub damaged_this_turn: bool,
    /// Were the Mon's stats raised this turn?
    pub stats_raised_this_turn: bool,
    /// Were the Mon's stats lowered this turn?
    pub stats_lowered_this_turn: bool,
    /// Did the Mon used an item this turn?
    pub item_used_this_turn: bool,
    /// Did the Mon switch out this turn?
    pub switched_out_this_turn: bool,

    /// Set of foes that appeared while this Mon was active.
    pub foes_fought_while_active: HashSet<MonHandle>,
    /// Attacks received by the Mon.
    pub received_attacks: Vec<ReceivedAttackEntry>,
    /// Total times attacked.
    ///
    /// May be overwritten from the Mon's real value.
    pub times_attacked: u64,

    /// A Mon needs to be selected by the player.
    pub select: Option<SelectReason>,

    /// Cache for Mon effects.
    pub effect_cache: MonEffectCache,
}

/// A Mon in a battle, which battles against other Mons.
pub struct Mon {
    pub player: usize,
    pub side: usize,

    pub name: String,

    /// The original base species of the Mon when the battle started.
    pub original_base_species: Id,
    /// The base species of the Mon, which represents the Mon's permanent physical appearance. In
    /// other words, this species is preserved on switch out.
    ///
    /// NOTE: Not the same as [`battler_data::SpeciesData::base_species`].
    pub base_species: Id,

    /// `true` if the Mon is in an active position.
    ///
    /// The Mon may or may not be fainted.
    pub active: bool,
    pub active_turns: u32,
    pub active_move_actions: u32,
    pub active_position: Option<usize>,
    pub old_active_position: Option<usize>,

    /// The position on the player's team when the battle started.
    pub team_position: usize,

    /// The position on the player's team considering switches throughout the battle.
    pub effective_team_position: usize,

    pub base_stored_stats: StatTable,
    pub ivs: StatTable,
    pub evs: StatTable,

    pub level: u8,
    pub experience: u32,
    pub friendship: u8,
    pub nature: Nature,
    pub true_nature: Nature,
    pub gender: Gender,
    pub shiny: bool,
    pub ball: Option<Id>,
    pub hidden_power_type: Type,
    pub different_original_trainer: bool,
    pub dynamax_level: u8,
    pub gigantamax_factor: bool,
    pub tera_type: Type,

    pub mon_effect_state: fxlang::EffectState,
    pub base_move_slots: Vec<MoveSlot>,
    pub original_base_ability: Id,
    pub base_ability: Id,
    pub original_item: Option<Id>,
    pub item: Option<Id>,
    pub status: Option<Id>,
    pub status_state: fxlang::EffectState,

    pub initial_hp: Option<u16>,
    pub hp: u16,
    pub base_max_hp: u16,
    pub max_hp: u16,
    pub exited: Option<MonExitType>,
    pub newly_switched: bool,
    pub ate_item: bool,
    pub times_attacked: u64,

    pub next_turn_state: MonNextTurnState,
    pub switch_state: MonSwitchState,
    pub volatile_state: MonVolatileState,

    /// The move the Mon is actively performing, excluding any externally-called move.
    pub non_external_active_move: Option<MoveHandle>,
    /// The move the Mon is actively performing.
    pub active_move: Option<MoveHandle>,

    pub learnable_moves: Vec<Id>,

    pub revert_forme_change_on_exit: bool,
    pub special_forme_change_type: Option<MonSpecialFormeChangeType>,
    pub dynamaxed: bool,
    pub terastallized: Option<Type>,
    pub terastallization_state: fxlang::EffectState,
}

// Construction and initialization logic.
impl Mon {
    /// Creates a new Mon.
    pub fn new(data: MonData, team_position: usize, dex: &Dex) -> Result<Self> {
        // Resolve IDs so we do not store aliases.
        let species = dex
            .species
            .get(&data.species)
            .wrap_error_with_message("species not found")?
            .id()
            .clone();
        let item = data
            .item
            .map(|item| {
                dex.items
                    .get(&item)
                    .wrap_error_with_message("item not found")
                    .map(|item| item.id().clone())
            })
            .transpose()?;
        let ability = dex
            .abilities
            .get(&data.ability)
            .wrap_error_with_message("ability not found")?
            .id()
            .clone();

        let mut base_move_slots = Vec::with_capacity(data.moves.len());
        for (i, move_name) in data.moves.iter().enumerate() {
            let mov = dex.moves.get(move_name)?;
            let max_pp = if mov.data.no_pp_boosts {
                mov.data.pp
            } else {
                let pp_boosts = data.pp_boosts.get(i).cloned().unwrap_or(0).min(3);
                ((mov.data.pp as u32) * (pp_boosts as u32 + 5) / 5) as u8
            };
            let pp = data
                .persistent_battle_data
                .move_pp
                .get(i)
                .cloned()
                .unwrap_or(max_pp);
            let pp = pp.min(max_pp);
            base_move_slots.push(MoveSlot::new(
                mov.id().clone(),
                mov.data.name.clone(),
                pp,
                max_pp,
                mov.data.target.clone(),
                mov.data.primary_type,
            ));
        }

        let hidden_power_type = data
            .hidden_power_type
            .unwrap_or(calculate_hidden_power_type(&data.ivs));

        let ball = data
            .ball
            .map(|ball| {
                if ball.is_empty() {
                    default_ball()
                } else {
                    ball
                }
            })
            .map(|ball| Id::from(ball));

        Ok(Self {
            player: usize::MAX,
            side: usize::MAX,
            name: data.name,
            original_base_species: species.clone(),
            base_species: species,
            active: false,
            active_turns: 0,
            active_move_actions: 0,
            active_position: None,
            old_active_position: None,
            team_position,
            effective_team_position: team_position,
            base_stored_stats: StatTable::default(),
            ivs: data.ivs,
            evs: data.evs,
            level: data.level,
            experience: data.experience,
            friendship: data.friendship,
            nature: data.nature,
            true_nature: data.true_nature.unwrap_or(data.nature),
            gender: data.gender,
            shiny: data.shiny,
            ball,
            hidden_power_type,
            different_original_trainer: data.different_original_trainer,
            dynamax_level: data.dynamax_level,
            gigantamax_factor: data.gigantamax_factor,
            tera_type: data.tera_type.unwrap_or(Type::None),
            mon_effect_state: fxlang::EffectState::default(),
            base_move_slots,
            original_base_ability: ability.clone(),
            base_ability: ability,
            original_item: item.clone(),
            item,
            status: data
                .persistent_battle_data
                .status
                .map(|status| Id::from(status)),
            status_state: fxlang::EffectState::default(),
            initial_hp: data.persistent_battle_data.hp,
            hp: 0,
            base_max_hp: 0,
            max_hp: 0,
            exited: None,
            newly_switched: false,
            ate_item: false,
            times_attacked: 0,
            next_turn_state: MonNextTurnState::default(),
            switch_state: MonSwitchState::default(),
            volatile_state: MonVolatileState::default(),
            non_external_active_move: None,
            active_move: None,
            learnable_moves: Vec::default(),
            revert_forme_change_on_exit: false,
            special_forme_change_type: None,
            dynamaxed: false,
            terastallized: None,
            terastallization_state: fxlang::EffectState::default(),
        })
    }

    /// Initializes a Mon for battle.
    ///
    /// This *must* be called at the very beginning of a battle, as it sets up important fields on
    /// the Mon, such as its stats.
    pub fn initialize(context: &mut MonContext) -> Result<()> {
        let base_species = context.mon().original_base_species.clone();
        let base_ability = context.mon().original_base_ability.clone();
        Self::set_base_species(context, &base_species, &base_ability)?;

        Self::clear_volatile(context, true)?;
        Self::recalculate_base_stats(
            context,
            RecalculateStatsHpPolicy::KeepDamageTaken { silent: true },
        )?;

        // Generate level from experience points if needed.
        if context.mon().level == 0 {
            let species = context
                .battle()
                .dex
                .species
                .get_by_id(&context.mon().base_species)?;
            context.mon_mut().level = species
                .data
                .leveling_rate
                .level_from_exp(context.mon().experience);
        } else if context.mon().experience == 0 {
            let species = context
                .battle()
                .dex
                .species
                .get_by_id(&context.mon().base_species)?;
            context.mon_mut().experience =
                species.data.leveling_rate.exp_at_level(context.mon().level);
        }

        // Set the initial HP, which may signal that the Mon is already fainted.
        let mut hp = context.mon().initial_hp.unwrap_or(context.mon().max_hp);
        if hp > context.mon().max_hp {
            hp = context.mon().max_hp;
        }
        context.mon_mut().hp = hp;
        if context.mon().hp == 0 {
            context.mon_mut().exited = Some(MonExitType::Fainted);
        }

        let mon_handle = context.mon_handle();
        context.mon_mut().mon_effect_state = fxlang::EffectState::initial_effect_state(
            context.as_battle_context_mut(),
            None,
            Some(mon_handle),
            None,
        )?;

        if context.mon().status.is_some() {
            context.mon_mut().status_state = fxlang::EffectState::initial_effect_state(
                context.as_battle_context_mut(),
                None,
                Some(mon_handle),
                None,
            )?;
        }

        if context.mon().tera_type == Type::None
            && let Some(first_type) = context.mon().volatile_state.types.first()
        {
            context.mon_mut().tera_type = *first_type;
        }

        Ok(())
    }
}

// Basic getters.
impl Mon {
    fn health(&self, actual_health: bool, public_base: u32) -> (u32, u32) {
        if actual_health {
            return self.actual_health();
        }
        if self.hp == 0 || self.max_hp == 0 {
            return (self.hp as u32, self.max_hp as u32);
        }
        let ratio = Fraction::new(self.hp as u32, self.max_hp as u32);
        // Always round up to avoid returning 0 when the Mon is not fainted.
        let mut percentage = (ratio * public_base).ceil();

        // Round down if the Mon is damaged.
        if percentage == public_base && ratio < Fraction::new(1, 1) {
            percentage = public_base - 1;
        }

        (percentage, public_base)
    }

    fn health_string(&self, actual_health: bool, public_base: u32) -> String {
        let (hp, max_hp) = self.health(actual_health, public_base);
        if hp == 0 || max_hp == 0 {
            return "0".to_owned();
        }
        format!("{hp}/{max_hp}")
    }

    fn actual_health(&self) -> (u32, u32) {
        (self.hp as u32, self.max_hp as u32)
    }

    fn actual_health_string(&self) -> String {
        if self.hp == 0 || self.max_hp == 0 {
            return "0".to_owned();
        }
        format!("{}/{}", self.hp, self.max_hp)
    }

    /// The physical details for the Mon.
    pub fn physical_details(context: &MonContext) -> Result<PhysicalMonDetails> {
        if let Some(illusion) = context.mon().volatile_state.illusion.clone() {
            return Ok(illusion);
        }

        let species = context
            .battle()
            .dex
            .species
            .get_by_id(&context.mon().volatile_state.species)?
            .data
            .name
            .clone();
        Ok(PhysicalMonDetails {
            name: context.mon().name.clone(),
            species,
            gender: context.mon().gender.clone(),
            shiny: context.mon().shiny,
        })
    }

    /// The public details for the Mon.
    pub fn public_details(context: &MonContext) -> Result<PublicMonDetails> {
        Ok(PublicMonDetails {
            physical_details: Self::physical_details(context)?,
            level: context.mon().level,
        })
    }

    fn active_details(context: &mut MonContext, secret: bool) -> Result<ActiveMonDetails> {
        let status = match context.mon().status.clone() {
            Some(status) => CoreBattle::get_effect_by_id(context.as_battle_context_mut(), &status)?
                .name()
                .to_owned(),
            None => String::new(),
        };
        Ok(ActiveMonDetails {
            public_details: Self::public_details(context)?,
            player_id: context.player().id.clone(),
            side_position: Self::position_on_side(context)
                .wrap_expectation("expected mon to be active")?
                + 1,
            health: if secret {
                context.mon().actual_health_string()
            } else {
                Self::public_health_string(context)
            },
            status,
            tera: context.mon().terastallized,
        })
    }

    /// The public details for the active Mon.
    pub fn public_active_details(context: &mut MonContext) -> Result<ActiveMonDetails> {
        Self::active_details(context, false)
    }

    /// The private details for the active Mon.
    pub fn private_active_details(context: &mut MonContext) -> Result<ActiveMonDetails> {
        Self::active_details(context, true)
    }

    fn public_name(&self) -> &str {
        match &self.volatile_state.illusion {
            Some(illusion) => &illusion.name,
            None => &self.name,
        }
    }

    /// The public details for the Mon when an action is made.
    pub fn position_details(context: &MonContext) -> Result<MonPositionDetails> {
        Ok(MonPositionDetails {
            name: context.mon().public_name().to_owned(),
            player_id: context.player().id.clone(),
            side_position: Self::position_on_side(context).map(|position| position + 1),
        })
    }

    /// Same as [`Self::position_details`], but it also considers the previous active position of
    /// the Mon.
    pub fn position_details_or_previous(context: &MonContext) -> Result<MonPositionDetails> {
        Ok(MonPositionDetails {
            name: context.mon().public_name().to_owned(),
            player_id: context.player().id.clone(),
            side_position: Self::position_on_side_or_previous(context).map(|position| position + 1),
        })
    }

    /// The public health of the Mon.
    pub fn public_health(context: &MonContext) -> (u32, u32) {
        context.mon().health(
            context.battle().engine_options.reveal_actual_health,
            context.battle().engine_options.public_health_base,
        )
    }

    /// The public health of the Mon, always based as a percentage.
    pub fn public_health_percentage(context: &MonContext) -> (u32, u32) {
        context
            .mon()
            .health(false, context.battle().engine_options.public_health_base)
    }

    /// The public health of the Mon.
    pub fn public_health_string(context: &MonContext) -> String {
        context.mon().health_string(
            context.battle().engine_options.reveal_actual_health,
            context.battle().engine_options.public_health_base,
        )
    }

    /// The secret health of the Mon.
    pub fn secret_health_string(context: &MonContext) -> String {
        context.mon().actual_health_string()
    }

    fn moves_and_locked_move(
        context: &mut MonContext,
    ) -> Result<(Vec<MonMoveSlotData>, Option<String>)> {
        let locked_move = context.mon().next_turn_state.locked_move.clone();
        let moves = Self::moves_with_locked_move(context, locked_move.as_deref())?;
        let has_usable_move = moves.iter().any(|mov| !mov.disabled);
        let moves = if has_usable_move { moves } else { Vec::new() };
        Ok((moves, locked_move))
    }

    /// Looks up all move slot data.
    ///
    /// If a Mon has a locked move, only that move will appear. Thus, this data is effectively
    /// viewed as the Mon's available move options.
    pub fn moves(context: &mut MonContext) -> Result<Vec<MonMoveSlotData>> {
        Self::moves_and_locked_move(context).map(|(moves, _)| moves)
    }

    /// Looks up all Z-Move slot data.
    ///
    /// Does not account for locked moves.
    fn z_moves(context: &mut MonContext) -> Result<Vec<Option<MoveSlot>>> {
        let mut z_moves = Vec::default();
        for mut move_slot in context.mon().volatile_state.move_slots.clone() {
            let move_slot =
                if let Some(z_move) = core_battle_actions::z_move_by_id(context, &move_slot.id)? {
                    let mov = context.battle().dex.moves.get_by_id(&z_move)?;
                    move_slot.id = mov.id().clone();
                    move_slot.name = mov.data.name.clone();
                    move_slot.target = mov.data.target;
                    Some(move_slot)
                } else {
                    None
                };
            z_moves.push(move_slot);
        }
        Ok(z_moves)
    }

    /// Looks up all Max Move slot data.
    ///
    /// Does not account for locked moves.
    fn max_moves(context: &mut MonContext) -> Result<Vec<MoveSlot>> {
        let mut max_moves = context.mon().volatile_state.move_slots.clone();
        for move_slot in &mut max_moves {
            if let Some(max_move) = core_battle_actions::max_move_by_id(context, &move_slot.id)? {
                let mov = context.battle().dex.moves.get_by_id(&max_move)?;
                move_slot.id = mov.id().clone();
                move_slot.name = mov.data.name.clone();
                move_slot.target = mov.data.target;
            }
        }
        Ok(max_moves)
    }

    fn position_on_side_by_active_position(context: &MonContext, active_position: usize) -> usize {
        let player = context.player();
        let position = active_position
            + player.position * context.battle().format.battle_type.active_per_player();
        position
    }

    /// The Mon's current position on its side.
    ///
    /// A side is shared by multiple players, who each can have multiple Mons active at a time. This
    /// position is intended to be scoped to the side, so all active Mons on a side have a unique
    /// position.
    ///
    /// Side position is a zero-based integer index in the range `[0, active_mons)`, where
    /// `active_mons` is the number of active Mons on the side. This is calculated by
    /// `players_on_side * active_per_player`.
    pub fn position_on_side(context: &MonContext) -> Option<usize> {
        Some(Self::position_on_side_by_active_position(
            context,
            context.mon().active_position?,
        ))
    }

    /// Same as [`Self::position_on_side`], but also returns the previous position of the Mon.
    pub fn position_on_side_or_previous(context: &MonContext) -> Option<usize> {
        Some(Self::position_on_side_by_active_position(
            context,
            context
                .mon()
                .active_position
                .or(context.mon().old_active_position)?,
        ))
    }

    fn relative_location(
        mon_position: usize,
        target_position: usize,
        same_side: bool,
        mons_per_side: usize,
    ) -> isize {
        if same_side {
            let diff = (target_position).abs_diff(mon_position);
            let diff = diff as isize;
            -diff
        } else {
            let flipped_position = mons_per_side - target_position - 1;
            let diff = (flipped_position).abs_diff(mon_position);
            let diff = diff + 1;
            diff as isize
        }
    }

    /// Calculates the relative location of the given target position.
    ///
    /// Relative location is essentially the Manhattan distance between this Mon and the target Mon.
    /// It is negative if the Mon is on the same side and positive if the Mon is on the opposite
    /// side.
    pub fn relative_location_of_target(
        context: &MonContext,
        target_side: usize,
        target_position: usize,
    ) -> Result<isize> {
        let mon = context.mon();
        let mon_side = mon.side;
        let mon_position =
            Self::position_on_side(context).wrap_expectation("expected mon to have a position")?;

        // Note that this calculation assumes that both sides have the same amount of players,
        // but battles are not required to validate this. Nonetheless, this calculation is still
        // correct, since players are positioned from left to right.
        //
        // The "Players Per Side" clause can be used to validate that both sides have the same
        // amount of players.
        //
        // There can still be weird behavior in a multi-battle or triple battle where remaining
        // Mons are not adjacent to one another. Shifting logic should be implemented somewhere
        // higher up so that `Self::position_on_side` returns the correct value after shifting.
        let mons_per_side = context.battle().max_side_length();

        if target_position >= mons_per_side {
            return Err(general_error(format!(
                "target position {target_position} is out of bounds",
            )));
        }

        Ok(Self::relative_location(
            mon_position,
            target_position,
            mon_side == target_side,
            mons_per_side,
        ))
    }

    /// Gets the target Mon based on this Mon's position.
    pub fn get_target(context: &mut MonContext, target: isize) -> Result<Option<MonHandle>> {
        if target == 0 {
            return Err(general_error("target cannot be 0"));
        }
        let mut side_context = context.pick_side_context(target < 0)?;
        let position = (target.abs() - 1) as usize;
        Side::mon_in_position(&mut side_context, position)
    }

    /// Gets the target Mon's position based on this Mon's position.
    pub fn get_target_location(context: &mut MonContext, target: MonHandle) -> Result<isize> {
        let target_context = context.as_battle_context_mut().mon_context(target)?;
        let target_side = target_context.mon().side;
        let target_position = Self::position_on_side(&target_context)
            .wrap_expectation("expected target to have a position")?
            + 1;
        if target_side == context.mon().side {
            Ok(-(target_position as isize))
        } else {
            Ok(target_position as isize)
        }
    }

    /// Checks if the given Mon is an ally.
    pub fn is_ally(&self, mon: &Mon) -> bool {
        self.side == mon.side
    }

    /// Checks if the given Mon is adjacent to this Mon.
    pub fn is_adjacent(context: &mut MonContext, other: MonHandle) -> Result<bool> {
        let side = context.mon().side;
        let position = match Self::position_on_side(context) {
            Some(position) => position,
            None => return Ok(false),
        };
        let other_context = context.as_battle_context_mut().mon_context(other)?;
        let other_side = other_context.mon().side;
        let mut other_position = match Self::position_on_side(&other_context) {
            Some(position) => position,
            None => return Ok(false),
        };

        if side != other_side {
            let mons_per_side = context.battle().max_side_length();
            if position >= mons_per_side {
                return Err(general_error(format!(
                    "mon position {position} is out of bounds"
                )));
            }
            // Flip the position.
            other_position = mons_per_side - other_position - 1;
        }

        let reach = context.battle().format.rules.numeric_rules.adjacency_reach as usize - 1;
        let diff = if position > other_position {
            position - other_position
        } else {
            other_position - position
        };

        Ok(diff <= reach)
    }

    /// Creates an iterator over all active allies.
    pub fn active_allies<'m>(context: &'m mut MonContext) -> impl Iterator<Item = MonHandle> + 'm {
        let side = context.side().index;
        let mon_handle = context.mon_handle();
        context
            .battle()
            .active_mon_handles_on_side(side)
            .filter(move |mon| *mon != mon_handle)
    }

    /// Creates an iterator over all active allies and this Mon.
    pub fn active_allies_and_self<'m>(
        context: &'m mut MonContext,
    ) -> impl Iterator<Item = MonHandle> + 'm {
        let side = context.side().index;
        context.battle().active_mon_handles_on_side(side)
    }

    /// Creates an iterator over all adjacent allies.
    pub fn adjacent_allies(
        context: &mut MonContext,
    ) -> Result<impl Iterator<Item = MonHandle> + use<>> {
        let allies = context
            .battle()
            .active_mon_handles_on_side(context.mon().side)
            .collect::<Vec<_>>();
        let mut adjacent_allies = Vec::new();
        for ally in allies {
            if context.mon_handle() != ally && Self::is_adjacent(context, ally)? {
                adjacent_allies.push(ally);
            }
        }
        Ok(adjacent_allies.into_iter())
    }

    /// Creates an iterator over all adjacent allies and this Mon.
    pub fn adjacent_allies_and_self(
        context: &mut MonContext,
    ) -> Result<impl Iterator<Item = MonHandle>> {
        Ok(Self::adjacent_allies(context)?.chain(iter::once(context.mon_handle())))
    }

    /// Checks if the given Mon is a foe.
    pub fn is_foe(&self, mon: &Mon) -> bool {
        self.side != mon.side
    }

    /// Creates an iterator over all active foes.
    pub fn active_foes<'m>(context: &'m mut MonContext) -> impl Iterator<Item = MonHandle> + 'm {
        let foe_side = context.foe_side().index;
        context.battle().active_mon_handles_on_side(foe_side)
    }

    /// Creates an iterator over all adjacent foes.
    pub fn adjacent_foes(context: &mut MonContext) -> Result<impl Iterator<Item = MonHandle>> {
        let foes = Self::active_foes(context).collect::<Vec<_>>();
        let mut adjacent_foes = Vec::new();
        for foe in foes {
            if Self::is_adjacent(context, foe)? {
                adjacent_foes.push(foe);
            }
        }
        Ok(adjacent_foes.into_iter())
    }

    fn calculate_stat_internal(
        context: &mut MonContext,
        stat: Stat,
        unboosted: bool,
        boost: Option<i8>,
        unmodified: bool,
        stat_user: Option<MonHandle>,
        calculate_stat_context: Option<CalculateStatContext>,
    ) -> Result<u16> {
        let stat_user = stat_user.unwrap_or(context.mon_handle());

        if stat == Stat::HP {
            return Err(general_error(
                "HP should be read directly, not by calling get_stat",
            ));
        }

        let mut value = context.mon().volatile_state.stats.get(stat);

        if !unmodified {
            value = core_battle_effects::run_event_with_input::<_, _, Option<u16>>(
                context,
                fxlang::BattleEvent::CalculateStat,
                [value.into(), stat.into()],
            )
            .unwrap_or(value);
        }

        if !unboosted {
            let mut boosts = context.mon().volatile_state.boosts.clone();

            if let Some(boost) = boost {
                boosts.set(stat.try_into()?, boost);
            }

            let boosts = match &calculate_stat_context {
                Some(calculate_stat_context) => {
                    core_battle_effects::run_event_with_relay::<_, BoostTable>(
                        &mut context.as_battle_context_mut().applying_effect_context(
                            calculate_stat_context.effect.clone(),
                            Some(calculate_stat_context.source),
                            stat_user,
                            None,
                        )?,
                        fxlang::BattleEvent::ModifyBoosts,
                        boosts,
                    )
                }
                None => core_battle_effects::run_event_with_relay::<_, BoostTable>(
                    &mut context.as_battle_context_mut().mon_context(stat_user)?,
                    fxlang::BattleEvent::ModifyBoosts,
                    boosts,
                ),
            };

            let boost = boosts.get(stat.try_into()?);

            static BOOST_TABLE: [(u16, u16); 7] =
                [(1, 1), (3, 2), (2, 1), (5, 2), (3, 1), (7, 2), (4, 1)];
            let boost = boost.max(-6).min(6);
            let (num, den) = BOOST_TABLE[boost.abs() as usize];
            let boost_fraction = Fraction::new(num, den);
            if boost >= 0 {
                value = boost_fraction.mul(value).floor();
            } else {
                value = boost_fraction.inverse().mul(value).floor();
            }
        }
        if !unmodified {
            if let Some(modify_event) = match stat {
                Stat::HP => None,
                Stat::Atk => Some(fxlang::BattleEvent::ModifyAtk),
                Stat::Def => Some(fxlang::BattleEvent::ModifyDef),
                Stat::SpAtk => Some(fxlang::BattleEvent::ModifySpA),
                Stat::SpDef => Some(fxlang::BattleEvent::ModifySpD),
                Stat::Spe => Some(fxlang::BattleEvent::ModifySpe),
            } {
                value = match calculate_stat_context {
                    Some(calculate_stat_context) => {
                        let mon_handle = context.mon_handle();
                        core_battle_effects::run_event_with_relay::<_, u16>(
                            &mut context.as_battle_context_mut().applying_effect_context(
                                calculate_stat_context.effect,
                                Some(calculate_stat_context.source),
                                mon_handle,
                                None,
                            )?,
                            modify_event,
                            value,
                        )
                    }
                    None => core_battle_effects::run_event_with_relay::<_, u16>(
                        context,
                        modify_event,
                        value,
                    ),
                }
            }
        }

        Ok(value)
    }

    /// Calculates the current value for the given [`Stat`] on a [`Mon`].
    ///
    /// Similar to [`Self::get_stat`], but can take in custom boosts and modifiers.
    pub fn calculate_stat(
        context: &mut MonContext,
        stat: Stat,
        boost: i8,
        stat_user: Option<MonHandle>,
        calculate_stat_context: Option<CalculateStatContext>,
    ) -> Result<u16> {
        Self::calculate_stat_internal(
            context,
            stat,
            false,
            Some(boost),
            false,
            stat_user,
            calculate_stat_context,
        )
    }

    /// Gets the current value for the given [`Stat`] on a [`Mon`] after all boosts/drops and
    /// modifications.
    pub fn get_stat(
        context: &mut MonContext,
        stat: Stat,
        unboosted: bool,
        unmodified: bool,
    ) -> Result<u16> {
        Self::calculate_stat_internal(context, stat, unboosted, None, unmodified, None, None)
    }

    /// Gets the Mon's best stat based on its current stat values.
    pub fn best_stat(context: &mut MonContext, unboosted: bool, unmodified: bool) -> Result<Stat> {
        Ok(StatOrderIterator::new()
            .filter(|stat| *stat != Stat::HP)
            .map(|stat| Mon::get_stat(context, stat, unboosted, unmodified).map(|val| (stat, val)))
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .rev()
            .max_by_key(|(_, val)| *val)
            .wrap_expectation("best stat yielded no stats")?
            .0)
    }

    /// Calculates the speed value to use for battle action ordering.
    pub fn action_speed(context: &mut MonContext) -> Result<u16> {
        let speed = Self::get_stat(context, Stat::Spe, false, false)?;
        let speed = core_battle_effects::run_event_with_relay::<_, u16>(
            context,
            fxlang::BattleEvent::ModifyActionSpeed,
            speed,
        );
        Ok(speed)
    }

    /// Updates the speed of the Mon, called at the end of each turn.
    pub fn update_speed(context: &mut MonContext) -> Result<()> {
        context.mon_mut().volatile_state.speed = Self::action_speed(context)? as u32;
        Ok(())
    }

    fn indexed_move_slot(&self, move_id: &Id) -> Option<(usize, &MoveSlot)> {
        self.volatile_state
            .move_slots
            .iter()
            .enumerate()
            .find(|(_, move_slot)| &move_slot.id == move_id)
    }

    fn move_slot(&self, move_id: &Id) -> Option<&MoveSlot> {
        self.indexed_move_slot(move_id)
            .map(|(_, move_slot)| move_slot)
    }

    /// Looks up the move slot index of the given move ID.
    pub fn move_slot_index(&self, move_id: &Id) -> Option<usize> {
        self.indexed_move_slot(move_id).map(|(i, _)| i)
    }

    fn indexed_move_slot_mut(&mut self, move_id: &Id) -> Option<(usize, &mut MoveSlot)> {
        self.volatile_state
            .move_slots
            .iter_mut()
            .enumerate()
            .find(|(_, move_slot)| &move_slot.id == move_id)
    }

    fn indexed_base_move_slot_mut(&mut self, move_id: &Id) -> Option<(usize, &mut MoveSlot)> {
        self.base_move_slots
            .iter_mut()
            .enumerate()
            .find(|(_, move_slot)| &move_slot.id == move_id)
    }

    fn move_slot_mut(&mut self, move_id: &Id) -> Option<&mut MoveSlot> {
        self.indexed_move_slot_mut(move_id)
            .map(|(_, move_slot)| move_slot)
    }

    fn base_move_slot_mut(&mut self, move_id: &Id) -> Option<&mut MoveSlot> {
        self.indexed_base_move_slot_mut(move_id)
            .map(|(_, move_slot)| move_slot)
    }

    /// Calculates the Mon's weight.
    pub fn get_weight(context: &mut MonContext) -> u32 {
        core_battle_effects::run_event_with_relay::<_, u32>(
            context,
            fxlang::BattleEvent::ModifyWeight,
            context.mon().volatile_state.weight,
        )
    }

    /// Creates a speed-orderable object for the Mon.
    pub fn speed_orderable(context: &MonContext) -> SpeedOrderableMon {
        SpeedOrderableMon {
            mon_handle: context.mon_handle(),
            speed: context.mon().volatile_state.speed,
            ability_effect_order: 0,
        }
    }

    /// Creates a speed-orderable object for the Mon, with the ability effect order for ties.
    pub fn speed_orderable_with_ability_effect_order(context: &MonContext) -> SpeedOrderableMon {
        SpeedOrderableMon {
            mon_handle: context.mon_handle(),
            speed: context.mon().volatile_state.speed,
            ability_effect_order: context
                .mon()
                .volatile_state
                .ability_slot
                .effect_state
                .effect_order(),
        }
    }
}

// Request getters.
impl Mon {
    /// Generates battle request data.
    pub fn battle_request_data(context: &mut MonContext) -> Result<MonBattleData> {
        let side_position = Self::position_on_side(context);
        let species = context
            .battle()
            .dex
            .species
            .get_by_id(&context.mon().volatile_state.species)?
            .data
            .name
            .clone();
        let ability = context
            .battle()
            .dex
            .abilities
            .get_by_id(&context.mon().volatile_state.ability_slot.ability.id)?
            .data
            .name
            .clone();
        let item = if let Some(item) = &context.mon().item {
            Some(
                context
                    .battle()
                    .dex
                    .items
                    .get_by_id(item)?
                    .data
                    .name
                    .clone(),
            )
        } else {
            None
        };
        Ok(MonBattleData {
            summary: Self::summary_request_data(context)?,
            species,
            hp: context.mon().hp,
            max_hp: context.mon().max_hp,
            health: context.mon().actual_health_string(),
            types: context.mon().volatile_state.types.clone(),
            active: context.mon().active,
            player_team_position: context.mon().team_position,
            player_effective_team_position: context.mon().effective_team_position,
            player_active_position: context.mon().active_position,
            side_position,
            stats: context.mon().volatile_state.stats.without_hp(),
            boosts: context.mon().volatile_state.boosts.clone(),
            moves: context
                .mon()
                .volatile_state
                .move_slots
                .clone()
                .into_iter()
                .map(|move_slot| MonMoveSlotData::from(context, &move_slot))
                .collect::<Result<Vec<_>>>()?,
            ability,
            item,
            status: context
                .mon()
                .status
                .as_ref()
                .map(|status| status.to_string()),
        })
    }

    /// Generates summary request data.
    pub fn summary_request_data(context: &mut MonContext) -> Result<MonSummaryData> {
        let species = context
            .battle()
            .dex
            .species
            .get_by_id(&context.mon().original_base_species)?
            .data
            .name
            .clone();
        let ability = context
            .battle()
            .dex
            .abilities
            .get_by_id(&context.mon().original_base_ability)?
            .data
            .name
            .clone();
        let item = match &context.mon().item {
            Some(item) => Some(
                context
                    .battle()
                    .dex
                    .items
                    .get_by_id(item)?
                    .data
                    .name
                    .clone(),
            ),
            None => None,
        };
        let ball = match &context.mon().ball {
            Some(ball) => Some(
                context
                    .battle()
                    .dex
                    .items
                    .get_by_id(ball)?
                    .data
                    .name
                    .clone(),
            ),
            None => None,
        };
        Ok(MonSummaryData {
            name: context.mon().name.clone(),
            species,
            level: context.mon().level,
            gender: context.mon().gender,
            nature: context.mon().nature,
            shiny: context.mon().shiny,
            ball,
            hp: context.mon().hp,
            friendship: context.mon().friendship,
            experience: context.mon().experience,
            stats: context.mon().base_stored_stats.clone(),
            evs: context.mon().evs.clone(),
            ivs: context.mon().ivs.clone(),
            moves: context
                .mon()
                .base_move_slots
                .clone()
                .into_iter()
                .map(|move_slot| MonPersistentMoveData {
                    name: move_slot.name.clone(),
                    pp: move_slot.pp,
                })
                .collect::<Vec<_>>(),
            ability,
            item,
            status: context
                .mon()
                .status
                .as_ref()
                .map(|status| status.to_string()),
            hidden_power_type: context.mon().hidden_power_type,
        })
    }

    /// Generates request data for a turn.
    pub fn move_request(context: &mut MonContext) -> Result<MonMoveRequest> {
        let (mut moves, mut locked_move) = Self::moves_and_locked_move(context)?;
        if moves.is_empty() {
            // No moves, the Mon must use Struggle.
            locked_move = Some("struggle".to_owned());
            moves = Vec::from_iter([MonMoveSlotData {
                name: "Struggle".to_owned(),
                id: Id::from_known("struggle"),
                pp: 1,
                max_pp: 1,
                target: MoveTarget::RandomNormal,
                typ: Type::None,
                disabled: false,
            }]);
        }

        let mut request = MonMoveRequest {
            team_position: context.mon().team_position,
            moves,
            z_moves: Vec::default(),
            max_moves: Vec::default(),
            trapped: false,
            can_mega_evolve: false,
            can_z_move: false,
            can_ultra_burst: false,
            can_dynamax: false,
            can_terastallize: false,
            locked_into_move: false,
        };

        let can_switch = Player::can_switch(context.as_player_context_mut());
        if can_switch && context.mon().next_turn_state.trapped {
            request.trapped = true;
        }

        if locked_move.is_none() {
            request.can_mega_evolve = context.mon().next_turn_state.can_mega_evolve;
            request.can_z_move = context.mon().next_turn_state.can_z_move;
            request.can_ultra_burst = context.mon().next_turn_state.can_ultra_burst;
            request.can_dynamax = context.mon().next_turn_state.can_dynamax;
            request.can_terastallize = context.mon().next_turn_state.can_terastallize;

            // Communicate Z-Moves, mostly for player's convenience.
            //
            // The actual Z-Move is decided immediately when the move is used.
            if request.can_z_move {
                request.z_moves = Self::z_moves(context)?
                    .into_iter()
                    .map(|move_slot| match move_slot {
                        Some(move_slot) => Ok(Some(MonMoveSlotData::from(context, &move_slot)?)),
                        None => Ok(None),
                    })
                    .collect::<Result<_>>()?;
            }

            // Communicate Max Moves, mostly for the player's convenience.
            //
            // The actual Max Move is decided immediately when the move is used.
            if request.can_dynamax || context.mon().dynamaxed {
                request.max_moves = Self::max_moves(context)?
                    .into_iter()
                    .map(|move_slot| MonMoveSlotData::from(context, &move_slot))
                    .collect::<Result<_>>()?;
            }
        } else {
            request.locked_into_move = true;
        }

        Ok(request)
    }

    /// Generates request data for learnable moves.
    pub fn learn_move_request(context: &mut MonContext) -> Result<Option<MonLearnMoveRequest>> {
        // Stable sort the moves that can be learned for consistency.
        context.mon_mut().learnable_moves.sort_by(|a, b| a.cmp(&b));

        // Moves must be learned one at a time.
        match context.mon().learnable_moves.first() {
            Some(learnable_move) => {
                let name = context
                    .battle()
                    .dex
                    .moves
                    .get_by_id(learnable_move)
                    .wrap_error_with_format(format_args!(
                        "move id {} was not found in the move dex for learning a move",
                        learnable_move,
                    ))?
                    .data
                    .name
                    .clone();
                Ok(Some(MonLearnMoveRequest {
                    team_position: context.mon().team_position,
                    id: learnable_move.clone(),
                    name,
                }))
            }
            None => Ok(None),
        }
    }

    /// The affection level of the Mon, based on its friendship.
    pub fn affection_level(&self) -> u8 {
        match self.friendship {
            0 => 0,
            1..=49 => 1,
            50..=99 => 2,
            100..=149 => 3,
            150..=254 => 4,
            255 => 5,
        }
    }
}

impl Mon {
    fn new_volatile_state(context: &mut MonContext) -> Result<MonVolatileState> {
        let mon_handle = context.mon_handle();
        Ok(MonVolatileState {
            species: context.mon().base_species.clone(),
            weight: 0, // Updated by set_species.
            base_stored_stats: context.mon().base_stored_stats.clone(),
            stats: context.mon().base_stored_stats.clone(),
            boosts: BoostTable::default(),
            speed: 0, // Updated by set_species.
            volatile_mon_effect_state: fxlang::EffectState::initial_effect_state(
                context.as_battle_context_mut(),
                None,
                Some(mon_handle),
                None,
            )?,
            move_slots: context.mon().base_move_slots.clone(),
            types: Vec::default(), // Updated by set_species.
            added_type: None,
            ability_slot: AbilitySlot {
                ability: EffectiveAbility {
                    id: context.mon().base_ability.clone(),
                    sub_abilities: Vec::default(),
                },
                effect_state: fxlang::EffectState::initial_effect_state(
                    context.as_battle_context_mut(),
                    None,
                    Some(mon_handle),
                    None,
                )?,
            },
            item_state: context
                .mon()
                .item
                .clone()
                .map(|_| {
                    Ok::<_, anyhow::Error>(fxlang::EffectState::initial_effect_state(
                        context.as_battle_context_mut(),
                        None,
                        Some(mon_handle),
                        None,
                    )?)
                })
                .transpose()?
                .unwrap_or_default(),
            last_item: None,
            volatiles: HashMap::default(),
            transformed: false,
            illusion: None,
            using_move: false,
            last_move_selected: None,
            last_move: None,
            last_move_used: None,
            move_this_turn_outcome: None,
            move_last_turn_outcome: None,
            last_move_target_location: None,
            damaged_this_turn: false,
            stats_raised_this_turn: false,
            stats_lowered_this_turn: false,
            item_used_this_turn: false,
            switched_out_this_turn: false,
            foes_fought_while_active: HashSet::default(),
            received_attacks: Vec::default(),
            times_attacked: context.mon().times_attacked,
            select: None,
            effect_cache: MonEffectCache::default(),
        })
    }
    /// Clears all volatile effects.
    pub fn clear_volatile(context: &mut MonContext, clear_switch_flags: bool) -> Result<()> {
        if clear_switch_flags {
            context.mon_mut().switch_state = MonSwitchState::default();
        }

        {
            let mon_handle = context.mon_handle();
            let volatiles = context
                .mon()
                .volatile_state
                .volatiles
                .keys()
                .cloned()
                .collect::<Vec<_>>();
            let mut context = context
                .as_battle_context_mut()
                .effect_context(EffectHandle::Condition(Id::from_known("switchout")), None)?;
            for volatile in volatiles {
                LinkedEffectsManager::remove_by_id(
                    &mut context,
                    &volatile,
                    AppliedEffectLocation::MonVolatile(mon_handle),
                )?;
            }
        }

        context.mon_mut().volatile_state = Self::new_volatile_state(context)?;

        let species = context.mon().base_species.clone();
        Self::set_species(context, &species, RecalculateStatsHpPolicy::DoNotUpdate)?;
        Ok(())
    }

    /// Recalculates a Mon's base stats.
    ///
    /// Should only be used when a Mon levels up.
    pub fn recalculate_base_stats(
        context: &mut MonContext,
        hp_policy: RecalculateStatsHpPolicy,
    ) -> Result<()> {
        let species = context
            .battle()
            .dex
            .species
            .get_by_id(&context.mon().base_species)?;

        let mut stats = calculate_mon_stats(
            &species.data.base_stats,
            &context.mon().ivs,
            &context.mon().evs,
            context.mon().level,
            context.mon().nature,
        );
        // Forced max HP always overrides stat calculations.
        if let Some(max_hp) = species.data.max_hp {
            stats.hp = max_hp;
        }

        let new_base_max_hp = stats.hp;
        context.mon_mut().base_max_hp = new_base_max_hp;

        Self::update_max_hp(context, hp_policy)?;

        context.mon_mut().base_stored_stats = stats.clone();

        Ok(())
    }

    /// Updates the Mon's maximum HP.
    pub fn update_max_hp(
        context: &mut MonContext,
        hp_policy: RecalculateStatsHpPolicy,
    ) -> Result<()> {
        if hp_policy == RecalculateStatsHpPolicy::DoNotUpdate {
            return Ok(());
        }

        // Stats must have already been recalculated.
        let new_base_max_hp = context.mon().volatile_state.stats.hp;
        context.mon_mut().base_max_hp = new_base_max_hp;

        let species = context
            .battle()
            .dex
            .species
            .get_by_id(&context.mon().volatile_state.species)?;

        let new_max_hp = if species.data.max_hp.is_none() && context.mon().dynamaxed {
            let ratio =
                Fraction::new(3, 2) + Fraction::new(1, 20) * context.mon().dynamax_level as u16;
            (ratio * context.mon().base_max_hp).floor()
        } else {
            context.mon().base_max_hp
        };

        // Mon is being initialized.
        if context.mon().max_hp == 0 || hp_policy == RecalculateStatsHpPolicy::DoNotUpdate {
            context.mon_mut().max_hp = new_max_hp;
            context.mon_mut().hp = context.mon().hp.min(context.mon().max_hp);
            return Ok(());
        }

        let new_hp = if hp_policy.keep_health_ratio() {
            let mut current_health = if context.mon().max_hp > 0 {
                Fraction::new(context.mon().hp as u32, context.mon().max_hp as u32)
            } else {
                Fraction::from(1u32)
            };
            if current_health > 1 {
                current_health = Fraction::from(1u32);
            }
            let hp = current_health * new_max_hp as u32;
            if hp_policy.use_ceil() {
                hp.ceil() as u16
            } else {
                hp.floor() as u16
            }
        } else {
            let damage_taken = if context.mon().hp > context.mon().max_hp {
                0
            } else {
                context.mon().max_hp - context.mon().hp
            };
            if context.mon().hp == 0 {
                0
            } else if new_max_hp < damage_taken {
                1
            } else {
                new_max_hp - damage_taken
            }
        };

        let previous_max_hp = context.mon().max_hp;
        context.mon_mut().max_hp = new_max_hp;

        let previous_hp = context.mon().hp;
        context.mon_mut().hp = new_hp;

        // Battle log must reflect new HP.
        let log_new_hp = context.mon().hp > 0
            && (previous_hp != context.mon().hp || previous_max_hp != context.mon().max_hp);
        if log_new_hp && !hp_policy.silent() {
            core_battle_logs::set_hp(context, None, None)?;
        }

        Ok(())
    }

    /// The current un-Dynamaxed HP of the Mon.
    pub fn undynamaxed_hp(&self) -> u16 {
        self.undynamaxed_hp_calculation(self.hp)
    }

    /// Calculates the un-Dynamaxed HP for a given value.
    pub fn undynamaxed_hp_calculation(&self, hp: u16) -> u16 {
        if self.dynamaxed {
            (Fraction::new(self.base_max_hp, self.max_hp) * hp).ceil()
        } else {
            hp
        }
    }

    /// Recalculates a Mon's stats.
    pub fn recalculate_stats(
        context: &mut MonContext,
        hp_policy: RecalculateStatsHpPolicy,
    ) -> Result<()> {
        let species = context
            .battle()
            .dex
            .species
            .get_by_id(&context.mon().volatile_state.species)?;

        let mut stats = calculate_mon_stats(
            &species.data.base_stats,
            &context.mon().ivs,
            &context.mon().evs,
            context.mon().level,
            context.mon().nature,
        );
        // Forced max HP always overrides stat calculations.
        if let Some(max_hp) = species.data.max_hp {
            stats.hp = max_hp;
        }

        Mon::set_stats(context, stats, true, hp_policy)?;

        Ok(())
    }

    /// Sets the base species of the Mon.
    pub fn set_base_species(
        context: &mut MonContext,
        base_species: &Id,
        base_ability: &Id,
    ) -> Result<()> {
        let species = context.battle().dex.species.get_by_id(base_species)?;

        context.mon_mut().base_species = species.id().clone();

        let ability = context.battle().dex.abilities.get_by_id(&base_ability)?;
        context.mon_mut().base_ability = ability.id().clone();

        Ok(())
    }

    /// Sets the species of the Mon.
    pub fn set_species(
        context: &mut MonContext,
        species: &Id,
        hp_policy: RecalculateStatsHpPolicy,
    ) -> Result<bool> {
        let species = context.battle().dex.species.get_by_id(species)?;

        // SAFETY: Nothing we do below will invalidate any data.
        let species = unsafe {
            core::mem::transmute::<ElementRef<'_, Species>, ElementRef<'_, Species>>(species)
        };

        let previous_species = context.mon().volatile_state.species.clone();

        context.mon_mut().volatile_state.species = species.id().clone();
        context.mon_mut().volatile_state.types = Vec::with_capacity(4);
        context
            .mon_mut()
            .volatile_state
            .types
            .push(species.data.primary_type);
        if let Some(secondary_type) = species.data.secondary_type {
            context.mon_mut().volatile_state.types.push(secondary_type);
        }

        Self::recalculate_stats(context, hp_policy)?;
        context.mon_mut().volatile_state.weight = species.data.weight;

        Ok(context.mon().volatile_state.species != previous_species)
    }

    /// Looks up the base species of this Mon's base species.
    pub fn base_species_of_species(context: &MonContext) -> Result<Id> {
        CoreBattle::base_species_of_species(
            context.as_battle_context(),
            &context.mon().base_species,
        )
    }

    /// Overwrites the move slot at the given index.
    pub fn overwrite_move_slot(
        &mut self,
        index: usize,
        new_move_slot: MoveSlot,
        override_base_slot: bool,
    ) -> Result<()> {
        if override_base_slot {
            *self
                .base_move_slots
                .get_mut(index)
                .wrap_not_found_error_with_format(format_args!("move slot in index {index}"))? =
                new_move_slot.clone();
        }
        *self
            .volatile_state
            .move_slots
            .get_mut(index)
            .wrap_not_found_error_with_format(format_args!("move slot in index {index}"))? =
            new_move_slot;
        Ok(())
    }

    /// Clears all stat boosts.
    pub fn clear_boosts(&mut self) {
        self.volatile_state.boosts = BoostTable::new();
    }

    /// Decreases the weight of the Mon.
    pub fn decrease_weight(&mut self, delta: u32) {
        self.volatile_state.weight = self.volatile_state.weight.saturating_sub(delta).max(1);
    }

    fn moves_with_locked_move(
        context: &mut MonContext,
        locked_move: Option<&str>,
    ) -> Result<Vec<MonMoveSlotData>> {
        // First, check if the Mon is locked into a certain move.
        if let Some(locked_move) = locked_move {
            let locked_move_id = Id::from(locked_move.as_ref());
            // Recharge and Pass are special moves when the Mon cannot really move.
            if locked_move_id.eq("recharge") {
                return Ok(Vec::from_iter([MonMoveSlotData {
                    name: "Recharge".to_owned(),
                    id: Id::from_known("recharge"),
                    pp: 0,
                    max_pp: 0,
                    target: MoveTarget::User,
                    typ: Type::None,
                    disabled: false,
                }]));
            } else if locked_move_id.eq("pass") {
                return Ok(Vec::from_iter([MonMoveSlotData {
                    name: "Pass".to_owned(),
                    id: Id::from_known("pass"),
                    pp: 0,
                    max_pp: 0,
                    target: MoveTarget::User,
                    typ: Type::None,
                    disabled: false,
                }]));
            }

            // A Mon can be locked into a move it does not know.
            let locked_move = context.battle().dex.moves.get_by_id(&locked_move_id)?;
            return Ok(Vec::from_iter([MonMoveSlotData {
                name: locked_move.data.name.clone(),
                id: locked_move.id().clone(),
                pp: 0,
                max_pp: 0,
                target: MoveTarget::Scripted,
                typ: locked_move.data.primary_type,
                disabled: false,
            }]));
        }

        // Else, generate move details for each move.
        let move_slots = context.mon().volatile_state.move_slots.clone();
        move_slots
            .into_iter()
            .map(|move_slot| MonMoveSlotData::from(context, &move_slot))
            .collect()
    }

    /// Switches the Mon into the given position for the player.
    pub fn switch_in(context: &mut MonContext, position: usize) -> Result<()> {
        context.mon_mut().active = true;
        context.mon_mut().active_turns = 0;
        context.mon_mut().active_move_actions = 0;
        context.mon_mut().active_position = Some(position);
        context.mon_mut().newly_switched = true;
        context.mon_mut().effective_team_position = position;

        context.mon_mut().switch_state.switching_in = false;

        let mon_handle = context.mon_handle();
        context
            .player_mut()
            .set_active_position(position, Some(mon_handle))?;

        for move_slot in &mut context.mon_mut().volatile_state.move_slots {
            move_slot.used = false;
        }

        let ability_order = context.battle_mut().next_effect_order();
        context
            .mon_mut()
            .volatile_state
            .ability_slot
            .effect_state
            .set_effect_order(ability_order);

        if context.mon().item.is_some() {
            let item_order = context.battle_mut().next_effect_order();
            context
                .mon_mut()
                .volatile_state
                .item_state
                .set_effect_order(item_order);
        }
        Ok(())
    }

    /// Switches the Mon out of its active position.
    pub fn switch_out(context: &mut MonContext) -> Result<()> {
        context.mon_mut().active = false;
        context.mon_mut().old_active_position = context.mon().active_position;
        if let Some(old_active_position) = context.mon().old_active_position {
            context
                .player_mut()
                .set_active_position(old_active_position, None)?;
        }
        context.mon_mut().active_position = None;
        Ok(())
    }

    /// Sets the active move.
    pub fn set_active_move(&mut self, active_move: MoveHandle, external: bool) {
        self.active_move = Some(active_move);
        if !external {
            self.non_external_active_move = Some(active_move);
        }
    }

    /// Clears the active move.
    pub fn clear_active_move(&mut self) {
        self.active_move = None;
    }

    /// Checks the PP for the given move.
    ///
    /// Returns if the move can be used with the PP deduction.
    pub fn check_pp(&self, move_id: &Id, amount: u8) -> bool {
        if let Some(move_slot) = self.move_slot(move_id) {
            if amount > move_slot.pp {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    fn deduct_pp_from_move_slot(move_slot: &mut MoveSlot, amount: u8) -> u8 {
        let before = move_slot.pp;
        move_slot.used = true;
        if amount > move_slot.pp {
            move_slot.pp = 0;
        } else {
            move_slot.pp -= amount;
        }
        before - move_slot.pp
    }

    /// Deducts PP from the given move.
    pub fn deduct_pp(&mut self, move_id: &Id, amount: u8) -> u8 {
        let mut move_slot_index = None;
        let mut pp = 0;
        let mut delta = 0;
        if let Some((i, move_slot)) = self.indexed_move_slot_mut(move_id) {
            delta = Self::deduct_pp_from_move_slot(move_slot, amount);
            if !move_slot.simulated {
                move_slot_index = Some(i);
                pp = move_slot.pp;
            }
        }

        if let Some(index) = move_slot_index {
            if let Some(base_move_slot) = self.base_move_slots.get_mut(index) {
                base_move_slot.pp = pp;
            }
        } else if let Some(move_slot) = self.base_move_slot_mut(move_id) {
            // Required for cases where the Mon's moveset changes after it uses the move, such as
            // Transform.
            delta = Self::deduct_pp_from_move_slot(move_slot, amount);
        }

        delta
    }

    /// Restores PP for the given move.
    pub fn restore_pp(&mut self, move_id: &Id, amount: u8) -> u8 {
        let mut move_slot_index = None;
        let mut pp = 0;
        let mut delta = 0;
        if let Some((i, move_slot)) = self.indexed_move_slot_mut(move_id) {
            let before = move_slot.pp;
            let max_diff = move_slot.max_pp - move_slot.pp;
            if amount > max_diff {
                move_slot.pp = move_slot.max_pp;
            } else {
                move_slot.pp += amount;
            }
            if !move_slot.simulated {
                move_slot_index = Some(i);
                pp = move_slot.pp;
            }
            delta = move_slot.pp - before;
        }

        if let Some(index) = move_slot_index {
            if let Some(base_move_slot) = self.base_move_slots.get_mut(index) {
                base_move_slot.pp = pp;
            }
        }

        delta
    }

    /// Sets the PP for a given move.
    pub fn set_pp(&mut self, move_id: &Id, amount: u8) -> u8 {
        let mut move_slot_index = None;
        let mut pp = 0;
        if let Some((i, move_slot)) = self.indexed_move_slot_mut(move_id) {
            move_slot.pp = amount;
            if move_slot.pp > move_slot.max_pp {
                move_slot.pp = move_slot.max_pp;
            }

            if !move_slot.simulated {
                move_slot_index = Some(i);
                pp = move_slot.pp;
            }
        }

        if let Some(index) = move_slot_index {
            if let Some(base_move_slot) = self.base_move_slots.get_mut(index) {
                base_move_slot.pp = pp;
            }
        }

        pp
    }

    /// Increases friendship based on the current friendship level.
    pub fn increase_friendship(context: &mut MonContext, delta: [u8; 3]) {
        let delta = delta[(context.mon().friendship / 100) as usize];
        let delta = core_battle_effects::run_event_with_relay::<_, u8>(
            context,
            fxlang::BattleEvent::ModifyFriendshipIncrease,
            delta,
        );
        let max_delta = u8::MAX - context.mon().friendship;
        context.mon_mut().friendship += delta.min(max_delta);
    }

    /// Increases friendship based on the current friendship level.
    pub fn decrease_friendship(context: &mut MonContext, delta: [u8; 3]) {
        let delta = delta[(context.mon().friendship / 100) as usize];
        let max_delta = context.mon().friendship;
        context.mon_mut().friendship -= delta.min(max_delta);
    }

    /// Sets friendship directly.
    pub fn set_friendship(context: &mut MonContext, value: u8) {
        context.mon_mut().friendship = value;
    }

    /// Checks if the Mon is immune to the given type.
    pub fn is_immune(context: &mut MonContext, typ: Type) -> Result<bool> {
        if !context.mon().active {
            return Ok(false);
        }

        if !*core_battle_effects::run_event_with_input::<_, _, DefaultTrueBool>(
            context,
            fxlang::BattleEvent::NegateImmunity,
            typ,
        ) {
            return Ok(false);
        }

        if !*core_battle_effects::run_event_with_input::<_, _, DefaultTrueBool>(
            context,
            fxlang::BattleEvent::TypeImmunity,
            typ,
        ) {
            return Ok(true);
        }

        let types = mon_states::effective_types(context);
        let immune = context.battle().check_type_immunity(typ, &types);

        Ok(immune)
    }

    /// Applies damage to the Mon.
    pub fn damage(
        context: &mut MonContext,
        damage: u16,
        source: Option<MonHandle>,
        effect: Option<&EffectHandle>,
    ) -> Result<u16> {
        if context.mon().hp == 0 || damage == 0 {
            return Ok(0);
        }
        let damage = context.mon().hp.min(damage);
        context.mon_mut().hp -= damage;
        if context.mon().hp == 0 {
            Self::faint(context, source, effect)?;
        }
        Ok(damage)
    }

    /// Faints the Mon, placing it in the queue to be processed.
    pub fn faint(
        context: &mut MonContext,
        source: Option<MonHandle>,
        effect: Option<&EffectHandle>,
    ) -> Result<()> {
        if !context.mon().active {
            return Ok(());
        }
        context.mon_mut().hp = 0;
        context.mon_mut().switch_state.needs_switch = None;
        let mon_handle = context.mon_handle();
        context.battle_mut().faint_queue.push_back(FaintEntry {
            target: mon_handle,
            source,
            effect: effect.cloned(),
        });
        Ok(())
    }

    /// Catches the Mon, placing it in the queue to be processed.
    pub fn catch(
        context: &mut MonContext,
        player: usize,
        item: Id,
        shakes: u8,
        critical: bool,
    ) -> Result<()> {
        if !context.mon().active {
            return Ok(());
        }
        context.mon_mut().switch_state.needs_switch = None;
        let mon_handle = context.mon_handle();
        context.battle_mut().catch_queue.push_back(CatchEntry {
            target: mon_handle,
            player,
            item,
            shakes,
            critical,
        });
        Ok(())
    }

    /// Heals the Mon.
    pub fn heal(&mut self, mut damage: u16) -> Result<u16> {
        if self.hp == 0 || damage == 0 || self.hp > self.max_hp {
            return Ok(0);
        }
        self.hp += damage;
        if self.hp > self.max_hp {
            damage -= self.hp - self.max_hp;
            self.hp = self.max_hp;
        }
        Ok(damage)
    }

    /// Clears the Mon's state when it exits the battle.
    pub fn clear_state_on_exit(context: &mut MonContext, exit_type: MonExitType) -> Result<()> {
        let effect = match exit_type {
            MonExitType::Fainted => EffectHandle::Condition(Id::from_known("faint")),
            MonExitType::Caught => EffectHandle::Condition(Id::from_known("catch")),
        };
        let mut context = context.applying_effect_context(effect, None, None)?;
        core_battle_actions::end_ability_even_if_exiting(&mut context, true)?;

        core_battle_actions::revert_on_exit(&mut context)?;

        Self::clear_volatile(&mut context.target_context()?, false)?;

        context.target_mut().exited = Some(exit_type);
        match exit_type {
            MonExitType::Fainted => {
                context.target_mut().status = Some(Id::from_known("fnt"));
            }
            MonExitType::Caught => (),
        }

        let mut context = context.target_context()?;
        Self::switch_out(&mut context)?;
        Self::clear_volatile(&mut context, true)?;

        Ok(())
    }

    /// Revives the Mon so that it can be used again.
    pub fn revive(context: &mut MonContext, hp: u16) -> Result<u16> {
        if context.mon().exited != Some(MonExitType::Fainted) {
            return Ok(0);
        }

        context.mon_mut().exited = None;
        context.mon_mut().status = None;
        context.mon_mut().hp = 1;
        Self::set_hp(context, hp)?;
        Self::clear_volatile(context, true)?;
        Ok(context.mon().hp)
    }

    /// Caps the given boosts based on the Mon's existing boosts.
    pub fn cap_boosts(context: &MonContext, boosts: BoostTable) -> BoostTable {
        BoostTable::from_iter(boosts.non_zero_iter().map(|(boost, value)| {
            let current_value = context.mon().volatile_state.boosts.get(boost);
            (
                boost,
                (current_value + value).max(-6).min(6) - current_value,
            )
        }))
    }

    /// Applies the given stat boost.
    pub fn boost_stat(context: &mut MonContext, boost: Boost, value: i8) -> i8 {
        let current_value = context.mon().volatile_state.boosts.get(boost);
        let new_value = current_value + value;
        let new_value = new_value.max(-6).min(6);
        context
            .mon_mut()
            .volatile_state
            .boosts
            .set(boost, new_value);
        new_value - current_value
    }

    /// Sets the Mon's boosted stats directly.
    pub fn set_boosts(context: &mut MonContext, boosts: &BoostTable) {
        for (boost, val) in boosts.non_zero_iter() {
            context.mon_mut().volatile_state.boosts.set(boost, val);
        }
    }

    /// Counts the positive boosts applied to the Mon.
    pub fn positive_boosts(context: &MonContext) -> u8 {
        let mut boosts = 0;
        for (_, val) in context.mon().volatile_state.boosts.non_zero_iter() {
            if val > 0 {
                boosts += val as u8;
            }
        }
        boosts
    }

    /// Checks if the Mon has an ability.
    pub fn has_ability(context: &mut MonContext, id: &Id) -> bool {
        mon_states::effective_ability(context).is_some_and(|ability| ability.id == *id)
    }

    /// Checks if the Mon has an item.
    pub fn has_item(context: &mut MonContext, id: &Id) -> bool {
        mon_states::effective_item(context).is_some_and(|item| item == *id)
    }

    /// Checks if the Mon has a type.
    pub fn has_type(context: &mut MonContext, typ: Type) -> bool {
        mon_states::has_type(context, typ)
    }

    /// Checks if the Mon has the given type, before forced types (e.g., Terastallization).
    pub fn has_type_before_forced_types(context: &mut MonContext, typ: Type) -> bool {
        mon_states::has_type_before_forced_types(context, typ)
    }

    /// Checks if the Mon has a volatile effect.
    pub fn has_volatile(context: &mut MonContext, id: &Id) -> bool {
        context.mon().volatile_state.volatiles.contains_key(id)
    }

    /// Resets the Mon's state for the next turn.
    pub fn reset_state_for_next_turn(context: &mut MonContext) -> Result<()> {
        context.mon_mut().active_turns += 1;

        context.mon_mut().newly_switched = false;
        context.mon_mut().old_active_position = None;

        context.mon_mut().volatile_state.move_last_turn_outcome =
            context.mon().volatile_state.move_this_turn_outcome;
        context.mon_mut().volatile_state.move_this_turn_outcome = None;
        context.mon_mut().volatile_state.damaged_this_turn = false;
        context.mon_mut().volatile_state.stats_raised_this_turn = false;
        context.mon_mut().volatile_state.stats_lowered_this_turn = false;
        context.mon_mut().volatile_state.item_used_this_turn = false;
        context.mon_mut().volatile_state.switched_out_this_turn = false;

        for move_slot in &mut context.mon_mut().volatile_state.move_slots {
            move_slot.disabled = false;
        }

        core_battle_effects::run_event::<_, ()>(context, fxlang::BattleEvent::DisableMove);
        core_battle_effects::run_event::<_, ()>(context, fxlang::BattleEvent::OverwriteMove);

        for move_slot in context.mon_mut().volatile_state.move_slots.clone() {
            core_battle_effects::run_effect_event::<_, ()>(
                &mut context.applying_effect_context(
                    EffectHandle::InactiveMove(move_slot.id.clone()),
                    None,
                    None,
                )?,
                fxlang::BattleEvent::DisableMove,
            );
        }

        context.mon_mut().next_turn_state = MonNextTurnState::default();

        if Self::trapped(context)? {
            core_battle_actions::trap_mon(context)?;
        }

        if core_battle_effects::run_event_with_options::<_, _, bool>(
            context,
            fxlang::BattleEvent::PreventUsedItems,
            (),
            core_battle_effects::RunEventOptions {
                return_first_value: true,
                ..Default::default()
            },
        ) {
            context.mon_mut().next_turn_state.cannot_receive_items = true;
        }

        if core_battle_actions::can_mega_evolve(context)?.is_some() {
            context.mon_mut().next_turn_state.can_mega_evolve = true;
        }

        let z_moves = core_battle_actions::can_z_move(context)?;
        if z_moves.iter().any(|mov| mov.is_some()) {
            context.mon_mut().next_turn_state.can_z_move = true;
        }

        if core_battle_actions::can_ultra_burst(context)?.is_some() {
            context.mon_mut().next_turn_state.can_ultra_burst = true;
        }

        if core_battle_actions::can_dynamax(context)?.is_some() {
            context.mon_mut().next_turn_state.can_dynamax = true;
        }

        if core_battle_actions::can_terastallize(context)?.is_some() {
            context.mon_mut().next_turn_state.can_terastallize = true;
        }

        if let Some(locked_move) = core_battle_effects::run_event::<_, Option<String>>(
            context,
            fxlang::BattleEvent::LockMove,
        ) {
            context.mon_mut().next_turn_state.locked_move = Some(locked_move);

            // A Mon with a locked move is trapped and cannot do anything else.
            context.mon_mut().next_turn_state.trapped = true;
            context.mon_mut().next_turn_state.cannot_receive_items = true;
            context.mon_mut().next_turn_state.can_mega_evolve = false;
            context.mon_mut().next_turn_state.can_z_move = false;
            context.mon_mut().next_turn_state.can_ultra_burst = false;
            context.mon_mut().next_turn_state.can_dynamax = false;
            context.mon_mut().next_turn_state.can_terastallize = false;
        }

        Ok(())
    }

    /// Disables the given move.
    pub fn disable_move(context: &mut MonContext, move_id: &Id) -> Result<()> {
        match context.mon_mut().move_slot_mut(move_id) {
            Some(move_slot) => {
                move_slot.disabled = true;
            }
            None => (),
        }
        Ok(())
    }

    fn remove_move_from_learnable_moves(&mut self, move_id: &Id) {
        self.learnable_moves
            .retain(|learn_move| learn_move != move_id);
    }

    /// Checks if the Mon can learn the move.
    pub fn can_learn_move(context: &mut MonContext, move_id: &Id) -> bool {
        context
            .mon()
            .base_move_slots
            .iter()
            .all(|move_slot| &move_slot.id != move_id)
    }

    /// Learns a move, overwriting the given move slot.
    ///
    /// If the move slot is invalid for the base move slots on the Mon, but the battle format allows
    /// for a move in this slot, the move will be added to the Mon's base move slots. If not, the
    /// move is not learned.
    pub fn learn_move(
        context: &mut MonContext,
        move_id: &Id,
        forget_move_slot: usize,
    ) -> Result<()> {
        let mov = context.battle().dex.moves.get_by_id(move_id)?;
        // SAFETY: The move is borrowed with reference counting, so no mutable reference can be
        // taken without causing an error elsewhere.
        let mov =
            unsafe { core::mem::transmute::<ElementRef<'_, Move>, ElementRef<'_, Move>>(mov) };
        let (forget_move_slot, forget_move_slot_index) =
            match context.mon_mut().base_move_slots.get_mut(forget_move_slot) {
                None => {
                    if forget_move_slot
                        >= context.battle().format.rules.numeric_rules.max_move_count as usize
                    {
                        let event = battle_log_entry!(
                            "didnotlearnmove",
                            ("mon", Self::position_details(context)?),
                            ("move", mov.data.name.clone())
                        );
                        context.battle_mut().log(event);
                        context.mon_mut().remove_move_from_learnable_moves(move_id);
                        return Ok(());
                    }
                    context.mon_mut().base_move_slots.push(MoveSlot::new(
                        Id::from_known("placeholder"),
                        String::new(),
                        0,
                        0,
                        MoveTarget::Normal,
                        Type::Normal,
                    ));
                    let index = context.mon().base_move_slots.len() - 1;
                    (
                        // SAFETY: We insert this element directly above.
                        context.mon_mut().base_move_slots.last_mut().unwrap(),
                        index,
                    )
                }
                Some(move_slot) => (move_slot, forget_move_slot),
            };

        let new_move_slot = MoveSlot::new(
            mov.id().clone(),
            mov.data.name.clone(),
            mov.data.pp,
            mov.data.pp,
            mov.data.target.clone(),
            mov.data.primary_type,
        );

        let old_name = forget_move_slot.name.clone();
        *forget_move_slot = new_move_slot.clone();

        // We also need to overwrite the Mon's move for the battle.
        if !context.mon().volatile_state.transformed {
            match context
                .mon_mut()
                .volatile_state
                .move_slots
                .get_mut(forget_move_slot_index)
            {
                Some(move_slot) => {
                    *move_slot = new_move_slot;
                }
                None => {
                    context
                        .mon_mut()
                        .volatile_state
                        .move_slots
                        .push(new_move_slot);
                }
            }
        }

        let mut event = battle_log_entry!(
            "learnedmove",
            ("mon", Self::position_details(context)?),
            ("move", mov.data.name.clone()),
        );
        if !old_name.is_empty() {
            event.set("forgot", old_name);
        }
        context.battle_mut().log(event);
        context.mon_mut().remove_move_from_learnable_moves(move_id);

        Ok(())
    }

    /// Checks if the Mon is trapped.
    pub fn trapped(context: &mut MonContext) -> Result<bool> {
        let trapped = core_battle_effects::run_event_with_options::<_, _, bool>(
            context,
            fxlang::BattleEvent::TrapMon,
            (),
            core_battle_effects::RunEventOptions {
                return_first_value: true,
                ..Default::default()
            },
        );
        Ok(trapped)
    }

    /// Checks if the Mon can escape from battle.
    pub fn can_escape(context: &mut MonContext) -> Result<bool> {
        let can_escape = !Self::trapped(context)?;
        let can_escape = core_battle_effects::run_event_with_options::<_, _, Option<bool>>(
            context,
            fxlang::BattleEvent::CanEscape,
            (),
            core_battle_effects::RunEventOptions {
                return_first_value: true,
                ..Default::default()
            },
        )
        .unwrap_or(can_escape);
        Ok(can_escape)
    }

    /// Checks if the Mon can Dynamax, based on its own effects.
    pub fn can_dynamax(context: &mut MonContext) -> Result<bool> {
        let can_dynamax = true;
        let can_dynamax = core_battle_effects::run_event_with_options::<_, _, Option<bool>>(
            context,
            fxlang::BattleEvent::CanDynamax,
            (),
            core_battle_effects::RunEventOptions {
                return_first_value: true,
                ..Default::default()
            },
        )
        .unwrap_or(can_dynamax);
        Ok(can_dynamax)
    }

    /// Sets the HP on the Mon directly, returning the delta.
    pub fn set_hp(context: &mut MonContext, mut hp: u16) -> Result<i32> {
        if context.mon().hp == 0 {
            return Ok(0);
        }
        if hp < 1 {
            hp = 1;
        }
        let mut delta = context.mon().hp as i32 - hp as i32;
        context.mon_mut().hp = hp;
        if context.mon().hp > context.mon().max_hp {
            let hp_delta = context.mon().hp - context.mon().max_hp;
            delta -= hp_delta as i32;
            context.mon_mut().hp = context.mon().max_hp;
        }

        core_battle_logs::set_hp(context, None, None)?;
        Ok(delta)
    }

    /// Forces a Mon to be fully healed.
    ///
    /// WARNING: This method is completely silent, so the heal will not be made known and will run
    /// no events. It is intended to be used by the "Heal Ball" item after catching a Mon.
    pub fn force_fully_heal(context: &mut MonContext) -> Result<()> {
        let max_hp = context.mon().max_hp;
        context.mon_mut().heal(max_hp)?;

        context.mon_mut().status = None;

        for (move_id, max_pp) in context
            .mon()
            .base_move_slots
            .iter()
            .map(|move_slot| (move_slot.id.clone(), move_slot.max_pp))
            .collect::<Vec<_>>()
        {
            context.mon_mut().restore_pp(&move_id, max_pp);
        }

        Ok(())
    }

    /// Sets the Mon's stats directly.
    pub fn set_stats(
        context: &mut MonContext,
        stats: StatTable,
        preserve_overrides: bool,
        hp_policy: RecalculateStatsHpPolicy,
    ) -> Result<()> {
        if !preserve_overrides {
            context.mon_mut().volatile_state.base_stored_stats = stats.clone();
            context.mon_mut().volatile_state.stats = stats;
        } else {
            for (stat, val) in &stats {
                if context.mon().volatile_state.base_stored_stats.get(stat)
                    == context.mon().volatile_state.stats.get(stat)
                {
                    context.mon_mut().volatile_state.stats.set(stat, val);
                }
            }
            context.mon_mut().volatile_state.base_stored_stats = stats.clone();
        }

        Self::update_speed(context)?;
        Self::update_max_hp(context, hp_policy)?;

        Ok(())
    }

    /// Sets the Mon's types directly.
    pub fn set_types(context: &mut MonContext, types: Vec<Type>) -> Result<()> {
        context.mon_mut().volatile_state.types = types;

        if let Some(added_type) = context.mon().volatile_state.added_type
            && context.mon().volatile_state.types.contains(&added_type)
        {
            context.mon_mut().volatile_state.added_type = None;
        }

        Ok(())
    }
}

#[cfg(test)]
mod mon_test {
    use crate::battle::Mon;

    #[test]
    fn relative_location_for_triples() {
        assert_eq!(Mon::relative_location(0, 0, true, 3), 0);
        assert_eq!(Mon::relative_location(0, 1, true, 3), -1);
        assert_eq!(Mon::relative_location(0, 2, true, 3), -2);
        assert_eq!(Mon::relative_location(1, 0, true, 3), -1);
        assert_eq!(Mon::relative_location(1, 1, true, 3), 0);
        assert_eq!(Mon::relative_location(1, 2, true, 3), -1);
        assert_eq!(Mon::relative_location(2, 0, true, 3), -2);
        assert_eq!(Mon::relative_location(2, 1, true, 3), -1);
        assert_eq!(Mon::relative_location(2, 2, true, 3), 0);

        assert_eq!(Mon::relative_location(0, 0, false, 3), 3);
        assert_eq!(Mon::relative_location(0, 1, false, 3), 2);
        assert_eq!(Mon::relative_location(0, 2, false, 3), 1);
        assert_eq!(Mon::relative_location(1, 0, false, 3), 2);
        assert_eq!(Mon::relative_location(1, 1, false, 3), 1);
        assert_eq!(Mon::relative_location(1, 2, false, 3), 2);
        assert_eq!(Mon::relative_location(2, 0, false, 3), 1);
        assert_eq!(Mon::relative_location(2, 1, false, 3), 2);
        assert_eq!(Mon::relative_location(2, 2, false, 3), 3);
    }

    #[test]
    fn relative_location_for_doubles_and_multi() {
        assert_eq!(Mon::relative_location(0, 0, true, 2), 0);
        assert_eq!(Mon::relative_location(0, 1, true, 2), -1);
        assert_eq!(Mon::relative_location(1, 0, true, 2), -1);
        assert_eq!(Mon::relative_location(1, 1, true, 2), 0);

        assert_eq!(Mon::relative_location(0, 0, false, 2), 2);
        assert_eq!(Mon::relative_location(0, 1, false, 2), 1);
        assert_eq!(Mon::relative_location(1, 0, false, 2), 1);
        assert_eq!(Mon::relative_location(1, 1, false, 2), 2);
    }

    #[test]
    fn relative_location_for_singles() {
        assert_eq!(Mon::relative_location(0, 0, true, 1), 0);
        assert_eq!(Mon::relative_location(0, 0, false, 1), 1);
    }
}