bevy_mod_scripting_bindings 0.24.0

Core traits and structures required for smoothly interfacing with other languages in a generic way
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
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
//!
//! Implementations of [`WorldExtensions`] trait on the world guard.

use super::{
    AnyTypeRegistration, AppScriptCallbackRunners, AppScriptComponentRegistry, EnumVariantRef,
    ReflectBase, ReflectBaseType, ReflectReference, ScriptBundleRegistration,
    ScriptComponentRegistration, ScriptResourceRegistration, ScriptTypeRegistration, StaticTypeRef,
    Union,
    function::{
        namespace::FunctionScope,
        script_function::{AppScriptFunctionRegistry, DynamicScriptFunction, FunctionCallContext},
    },
    schedule::AppScheduleRegistry,
    script_value::ScriptValue,
    static_type::{ReflectNoTypeFunctions, registered_type_info},
};
use crate::{
    AppScriptTypeCatalogue, DynamicComponent, DynamicComponentInfo, SCRIPT_NAMESPACE_PREFIX,
    ScriptEvent, ScriptEventRegistration, ScriptNamedSet, ScriptQueryBuilder, ScriptQueryResult,
    ScriptSystemSetRegistry,
    error::InteropError,
    function::{from::V, from_ref::FromScriptErased, into::IntoScript},
    script_path, validate_script_namespace_and_name,
};
use ::{
    bevy_asset::{AssetServer, Handle, LoadState},
    bevy_ecs::{
        component::ComponentId,
        entity::Entity,
        reflect::{ReflectBundle, ReflectEvent, ReflectFromWorld, ReflectMessage, ReflectResource},
        world::World,
    },
    bevy_reflect::{PartialReflect, std_traits::ReflectDefault},
};
use bevy_app::AppExit;
use bevy_asset::AssetPath;
use bevy_ecs::schedule::SystemSet;
use bevy_ecs::{
    component::{Component, ComponentCloneBehavior, ComponentDescriptor, Mutable},
    hierarchy::{ChildOf, Children},
    observer::{Observer, On},
    resource::Resource,
    system::Commands,
    world::{CommandQueue, DeferredWorld, Mut},
};
use bevy_mod_scripting_asset::ScriptAsset;
use bevy_mod_scripting_script::{Recipients, ScriptAttachment};
use bevy_mod_scripting_world::{CachedRegistry, RegistryCache, WorldAccessGuard, WorldGuard};
use bevy_reflect::{GetTypeRegistration, Reflect, TypeRegistration};
use bevy_system_reflection::{ReflectSchedule, ReflectSystemSet};
use std::{
    alloc::Layout,
    any::TypeId,
    borrow::Cow,
    cell::{Ref, RefCell},
    collections::VecDeque,
    mem::needs_drop,
    rc::Rc,
    sync::Arc,
};

/// Functional extensions to the [`WorldGuard`]
pub trait WorldExtensions {
    /// Spawns a new empty entity and returns its ID.
    fn spawn(&self) -> Result<Entity, InteropError>;

    /// Despawns the given entity (also removes its Children component).
    fn despawn(&self, entity: Entity) -> Result<(), InteropError>;

    /// Despawns the entity and all of its descendants.
    fn despawn_recursive(&self, parent: Entity) -> Result<(), InteropError>;

    /// Despawns only the descendants of the given entity.
    fn despawn_descendants(&self, parent: Entity) -> Result<(), InteropError>;

    /// Checks whether the entity exists and is valid.
    fn is_valid_entity(&self, entity: Entity) -> Result<bool, InteropError>;

    /// Alias for `is_valid_entity`.
    fn has_entity(&self, entity: Entity) -> Result<bool, InteropError>;

    /// Runs a query and returns matching entities and component references.
    fn query(&self, query: ScriptQueryBuilder)
    -> Result<VecDeque<ScriptQueryResult>, InteropError>;

    /// Inserts a component value into an entity.
    fn insert_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
        value: ReflectReference,
    ) -> Result<(), InteropError>;

    /// Adds a default-constructed component to an entity.
    fn add_default_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
    ) -> Result<(), InteropError>;

    /// Removes a component from an entity.
    fn remove_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
    ) -> Result<(), InteropError>;

    /// Retrieves a component reference from an entity if present.
    fn get_component(
        &self,
        entity: Entity,
        component_registration: ScriptComponentRegistration,
    ) -> Result<Option<ReflectReference>, InteropError>;

    /// Checks if an entity contains a specific component.
    fn has_component(
        &self,
        entity: Entity,
        component_id: ComponentId,
    ) -> Result<bool, InteropError>;

    /// Inserts a bundle value into an entity.
    fn insert_bundle(
        &self,
        entity: Entity,
        registration: ScriptBundleRegistration,
        value: ReflectReference,
    ) -> Result<(), InteropError>;

    /// Spawns a new entity with the given bundle value and returns its ID.
    fn spawn_bundle(
        &self,
        registration: ScriptBundleRegistration,
        value: ReflectReference,
    ) -> Result<Entity, InteropError>;

    /// Executes a closure with access to a component (if present).
    fn with_component<C: Component, O, F: FnOnce(Option<&C>) -> O>(
        &self,
        entity: Entity,
        f: F,
    ) -> Result<O, InteropError>;

    /// Executes a closure with access to a component (if present).
    fn with_component_mut<C: Component<Mutability = Mutable>, O, F: FnOnce(Option<Mut<C>>) -> O>(
        &self,
        entity: Entity,
        f: F,
    ) -> Result<O, InteropError>;

    /// Executes a closure with access to a component after inserting its default value if it doesn't exist (if present).
    fn with_or_insert_component_mut<
        C: Component<Mutability = Mutable> + Default,
        O,
        F: FnOnce(&mut C) -> O,
    >(
        &self,
        entity: Entity,
        f: F,
    ) -> Result<O, InteropError>;

    /// Retrieves a resource reference if it exists.
    fn get_resource(
        &self,
        resource_id: ComponentId,
    ) -> Result<Option<ReflectReference>, InteropError>;

    /// Removes a resource from the world.
    fn remove_resource(&self, registration: ScriptResourceRegistration)
    -> Result<(), InteropError>;

    /// Checks if a resource exists.
    fn has_resource(&self, resource_id: ComponentId) -> Result<bool, InteropError>;

    /// Executes a closure with shared access to a resource.
    fn with_resource<R: Resource, O, F: FnOnce(&R) -> O>(&self, f: F) -> Result<O, InteropError>;

    /// Executes a closure with mutable access to a resource.
    fn with_resource_mut<R: Resource<Mutability = Mutable>, O, F: FnOnce(Mut<R>) -> O>(
        &self,
        f: F,
    ) -> Result<O, InteropError>;

    /// Triggers a reflected [`bevy_ecs::event::Event`] (observer style) on the world, using the type's [`ReflectEvent`] type data.
    ///
    /// The value is cloned out of the reference first, so no access to the reference is held while observers run.
    /// Observers run synchronously with exclusive world access, this fails if any other access is currently held.
    fn trigger_event(
        &self,
        registration: ScriptTypeRegistration,
        event: &ReflectReference,
    ) -> Result<(), InteropError>;

    /// Exports the callback `label` of the script `owner` as the function `name` of a script namespace (which must start with `script.`).
    ///
    /// The function can then be called by any script through `import_namespace(namespace).name`, in any language, see [`Self::call_script_export`].
    /// Exporting the same name again from the same script replaces it, from a different script it is an error.
    fn register_script_export(
        &self,
        namespace: &str,
        name: &str,
        label: String,
        owner: ScriptAttachment,
    ) -> Result<(), InteropError>;

    /// Calls the exported function with the given full path (i.e. `script.game.spawn_enemy`) in the script that exported it,
    /// by running its callback through the callback runners.
    ///
    /// Fails if the export does not exist (anymore), if the owning script is not loaded, or if its context is busy running another callback.
    fn call_script_export(
        &self,
        path: &str,
        args: Vec<ScriptValue>,
    ) -> Result<ScriptValue, InteropError>;

    /// Registers a script event, and returns a handle to it.
    ///
    /// Fails if an event with the same name is already registered, unless `allow_existing` is set,
    /// in which case the existing event is returned instead.
    fn register_script_event(
        &self,
        namespace: &str,
        name: &str,
        allow_existing: bool,
    ) -> Result<ScriptEventRegistration, InteropError>;

    /// Registers a system set of the script `owner` in a script namespace (which must start with `script.`), and returns it.
    ///
    /// Fails if a set with the same path is already registered, unless `allow_existing` is set,
    /// in which case the existing set is returned instead. The set is removed from its namespace when its owner unloads,
    /// registering it again gives the same set.
    fn register_script_system_set(
        &self,
        namespace: &str,
        name: &str,
        allow_existing: bool,
        owner: ScriptAttachment,
    ) -> Result<ReflectSystemSet, InteropError>;

    /// Finds a system set by its full path, i.e. `transform.TransformSystems.Propagate` for a Rust set,
    /// or `script.game.ai` for a set registered by a script.
    fn get_system_set_by_name(&self, path: &str) -> Option<ReflectSystemSet>;

    /// Spawns an observer which queues the callback `label` on the script `attachment`, with the payload as argument, whenever the script event is triggered.
    ///
    /// See [`Self::add_script_observer`] for when callbacks run.
    fn add_script_event_observer(
        &self,
        event: ScriptEventRegistration,
        label: String,
        attachment: ScriptAttachment,
    ) -> Result<Entity, InteropError>;

    /// Triggers a script event with the given payload, observers of the event queue their callbacks.
    fn trigger_script_event(
        &self,
        event: ScriptEventRegistration,
        payload: ScriptValue,
    ) -> Result<(), InteropError>;

    /// Spawns an observer which queues the callback `label` on the script `attachment` whenever an event of the given type is triggered.
    ///
    /// The event type must have [`ReflectEvent`] type data. For events which are triggered for components
    /// (i.e. the lifecycle events `AddEvent`, `InsertEvent`, `DiscardEvent`, `RemoveEvent`, `DespawnEvent`), the observer runs for the given components.
    /// If `entities` is non-empty, it only runs for those entities.
    ///
    /// The callback receives a clone of the event as its only argument, and is run by the same machinery as every other script callback
    /// (see [`AppScriptCallbackRunners::run_or_queue`]): right after the operation which triggered the event, unless the script's context
    /// is busy running another callback (e.g. the one that triggered the event), in which case it is queued
    /// and runs as soon as that finishes. The order in which the observers of one event run is unspecified.
    /// The world is already past the change (i.e. removed component data is no longer readable).
    ///
    /// Returns the observer entity, despawn it to remove the observer.
    fn add_script_observer(
        &self,
        event: ScriptTypeRegistration,
        components: Vec<ScriptComponentRegistration>,
        entities: Vec<Entity>,
        label: String,
        attachment: ScriptAttachment,
    ) -> Result<Entity, InteropError>;

    /// Writes a reflected [`bevy_ecs::message::Message`] (buffered) to the world, using the type's [`ReflectMessage`] type data.
    fn write_message(
        &self,
        registration: ScriptTypeRegistration,
        message: &ReflectReference,
    ) -> Result<(), InteropError>;

    /// Executes a closure with immutable access to the world.
    fn with_world<O, F: FnOnce(&World) -> O>(&self, f: F) -> Result<O, InteropError>;

    /// Executes a closure with mutable access to the world.
    fn with_world_mut<O, F: FnOnce(&mut World) -> O>(&self, f: F) -> Result<O, InteropError>;

    /// Returns the parent of an entity if it has one.
    fn get_parent(&self, entity: Entity) -> Result<Option<Entity>, InteropError>;

    /// Returns all children of an entity.
    fn get_children(&self, entity: Entity) -> Result<Vec<Entity>, InteropError>;

    /// Appends children to the given parent entity.
    fn push_children(&self, parent: Entity, children: &[Entity]) -> Result<(), InteropError>;

    /// Inserts children at a specific index in the parent's child list.
    fn insert_children(
        &self,
        parent: Entity,
        index: usize,
        children: &[Entity],
    ) -> Result<(), InteropError>;

    /// Removes specific children from a parent entity.
    fn remove_children(&self, parent: Entity, children: &[Entity]) -> Result<(), InteropError>;

    /// Sends an AppExit::Success event to the world.
    fn exit(&self) -> Result<(), InteropError>;

    // /// Retrieves all systems in the given schedule.
    // fn systems(&self, schedule: &ReflectSchedule) -> Result<Vec<ReflectSystem>, InteropError>;

    // /// Temporarily removes a schedule, mutates it, then reinserts it.
    // fn scope_schedule<O, F>(&self, label: &ReflectSchedule, f: F) -> Result<O, InteropError>
    // where
    //     F: FnOnce(&mut World, &mut Schedule) -> O;

    /// Retrieves a schedule by its name.
    fn get_schedule_by_name(&self, schedule_name: String) -> Option<ReflectSchedule>;

    /// Loads a script asset from the given path.
    fn load_script_asset<'a>(
        &self,
        asset_path: impl Into<AssetPath<'a>>,
    ) -> Result<Handle<ScriptAsset>, InteropError>;

    /// Returns the load state of a script asset.
    fn get_script_asset_load_state(
        &self,
        script: Handle<ScriptAsset>,
    ) -> Result<LoadState, InteropError>;

    /// Calls the function with the given name registered on the given type, used to dispatch operators.
    fn call_operator(
        &self,
        type_id: TypeId,
        name: impl Into<Cow<'static, str>>,
        args: Vec<ScriptValue>,
        context: FunctionCallContext,
    ) -> Result<ScriptValue, InteropError>;

    /// Lists all functions available on a type (including reference methods).
    fn get_functions_on_type(
        &self,
        type_id: TypeId,
    ) -> Vec<(Cow<'static, str>, DynamicScriptFunction)>;

    /// Looks up a member accessed by name on a value, i.e. `value.name` in a script, before falling back to field access.
    ///
    /// Resolution order:
    /// 1. functions registered on the type itself, then those on [`ReflectReference`], which apply to all instances
    /// 2. for an enum variant: the functions of the enum, so `MyEnum.Variant:method()` works
    ///
    /// For a type registration, such as the entries of `import_namespace`, the static members of the registered type (see [`Self::lookup_static_member`])
    /// come right after the functions of the registration itself, before the functions shared by all references,
    /// so `math.Vec3.new(..)` and `my_namespace.MyEnum.Variant` work.
    ///
    /// `type_id` is the type of the value `reference` points to. Returns the name back if nothing was found.
    fn lookup_member<'n>(
        &self,
        reference: &ReflectReference,
        type_id: TypeId,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<ScriptValue, Cow<'n, str>>;

    /// Looks up anything accessible as `Type.member` on the static reference to a type in a script.
    ///
    /// Resolution order:
    /// 1. functions registered on the type itself
    /// 2. functions shared by all types (registered on [`StaticTypeRef`]), with the type bound as their first argument
    /// 3. the variants of the type, if it is an enum
    ///
    /// Returns the name back if nothing was found.
    fn lookup_static_member<'n>(
        &self,
        type_id: TypeId,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<ScriptValue, Cow<'n, str>>;

    /// Resolves a type registration by its full type path, i.e. `bevy_transform::components::transform::Transform`.
    fn get_type_by_name(&self, type_name: &str) -> Option<ScriptTypeRegistration>;

    /// Resolves a type registration and determines if it's a component or resource.
    fn get_type_registration(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<AnyTypeRegistration, InteropError>;

    /// Resolves a type registration by name with component/resource detection.
    fn get_type_registration_by_name(
        &self,
        type_name: String,
    ) -> Result<Option<AnyTypeRegistration>, InteropError>;

    /// Attempts to interpret a type as a resource type.
    fn get_resource_type(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<Result<ScriptResourceRegistration, ScriptTypeRegistration>, InteropError>;

    /// Attempts to interpret a type as a component type.
    fn get_component_type(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<Result<ScriptComponentRegistration, ScriptTypeRegistration>, InteropError>;

    /// Attempts to interpret a type as a bundle type, i.e. a type with `ReflectBundle` type data.
    fn get_bundle_type(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<Result<ScriptBundleRegistration, ScriptTypeRegistration>, InteropError>;

    /// Returns the script function registry.
    fn script_function_registry(&'_ self) -> Ref<'_, AppScriptFunctionRegistry>;

    /// Returns the callback runners of all scripting plugins.
    fn script_callback_runners(&'_ self) -> Ref<'_, AppScriptCallbackRunners>;

    /// Returns the type catalogue.
    fn type_catalogue(&'_ self) -> Ref<'_, AppScriptTypeCatalogue>;

    /// Returns the component registry.
    fn component_registry(&'_ self) -> Ref<'_, AppScriptComponentRegistry>;

    /// Returns the schedule registry.
    fn schedule_registry(&'_ self) -> Ref<'_, AppScheduleRegistry>;

    /// Returns the current attachment if the guard is being used in the context of one.
    fn current_attachment(&self) -> CurrentScriptAttachment;

    /// Sets the current attachment for the world guard context.
    fn set_current_attachment(&self, attachment: ScriptAttachment);

    /// Registers a dynamic script component in a script namespace (which must start with `script.`), and returns a reference to its registration
    ///
    /// Fails if a component with the same namespace and name is already registered, unless `allow_existing` is set,
    /// in which case the existing component's registration is returned instead.
    fn register_script_component(
        &self,
        namespace: &str,
        component_name: &str,
        allow_existing: bool,
    ) -> Result<ScriptComponentRegistration, InteropError>;

    /// Initializes cached registries from the world.
    fn setup_cache(world: &World, attachment: CurrentScriptAttachment) -> RegistryCache;

    /// Initializes cached registries from the world, from raw components.
    fn setup_cache_raw(
        attachment: CurrentScriptAttachment,
        function_registry: AppScriptFunctionRegistry,
        schedule_registry: AppScheduleRegistry,
        component_registry: AppScriptComponentRegistry,
        callback_runners: AppScriptCallbackRunners,
        type_catalogue: AppScriptTypeCatalogue,
    ) -> RegistryCache;
}

impl<'w> WorldExtensions for WorldAccessGuard<'w> {
    fn spawn(&self) -> Result<Entity, InteropError> {
        self.with_world_mut(|world| {
            let mut command_queue = CommandQueue::default();
            let mut commands = Commands::new(&mut command_queue, world);
            let id = commands.spawn_empty().id();
            command_queue.apply(world);
            id
        })
    }

    fn despawn(&self, entity: Entity) -> Result<(), InteropError> {
        if !self.is_valid_entity(entity)? {
            return Err(InteropError::missing_entity(entity));
        }

        self.with_world_mut(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(entity).remove::<Children>().despawn();
            queue.apply(world);
        })
    }

    fn despawn_recursive(&self, parent: Entity) -> Result<(), InteropError> {
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }
        self.with_world_mut(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).despawn();
            queue.apply(world);
        })
    }

    fn despawn_descendants(&self, parent: Entity) -> Result<(), InteropError> {
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }

        self.with_world_mut(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).despawn_related::<Children>();
            queue.apply(world);
        })
    }

    fn is_valid_entity(&self, entity: Entity) -> Result<bool, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        Ok(cell.get_entity(entity).is_ok() && entity.index().index() != 0)
    }

    fn has_entity(&self, entity: Entity) -> Result<bool, InteropError> {
        self.is_valid_entity(entity)
    }

    fn query(
        &self,
        query: crate::ScriptQueryBuilder,
    ) -> Result<VecDeque<ScriptQueryResult>, InteropError> {
        self.with_world_mut(|world| {
            let mut built_query =
                query.as_query_state::<Entity>(world, crate::QueryAccess::MatchOnly);
            // outside of systems, changes are relative to the last update, like `World::query`
            let (last_run, this_run) = (world.last_change_tick(), world.read_change_tick());
            let world = world.as_unsafe_world_cell_readonly();
            // Safety: we have exclusive access to the world, and only read it
            let entities = unsafe { built_query.iter_unchecked(world) };
            Ok(entities
                .filter_map(|entity| {
                    let entity = world.get_entity(entity).ok()?;
                    // Safety: we have exclusive access to the world
                    unsafe { query.result_for(entity, last_run, this_run) }
                })
                .collect())
        })?
    }

    /// insert the component into the entity
    fn insert_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
        value: ReflectReference,
    ) -> Result<(), InteropError> {
        let type_id = registration.type_registration().type_id();
        // allow enum variants, i.e. `Visibility.Hidden`, in place of values
        let value =
            crate::function::from::variant_as_value_of(&value, self, type_id).unwrap_or(value);
        let instance = <Box<dyn PartialReflect>>::from_script_erased(
            type_id,
            ScriptValue::Reference(value),
            self.clone(),
        )?;

        // inserting a value of another type panics inside bevy
        let instance_type_id = instance.get_represented_type_info().map(|i| i.type_id());
        if instance_type_id != Some(type_id) {
            return Err(InteropError::type_mismatch(type_id, instance_type_id));
        }

        let reflect = instance.try_into_reflect().map_err(|v| {
            InteropError::failed_from_reflect(
                Some(registration.type_registration().type_id()),
                format!("instance produced by conversion to target type when inserting component is not a full reflect type: {v:?}"),
            )
        })?;

        registration.insert_into_entity(self.clone(), entity, reflect)
    }

    /// add a default component to an entity
    fn add_default_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
    ) -> Result<(), InteropError> {
        let instance = default_instance(
            self.clone(),
            registration.type_registration().type_registration(),
        )?;

        registration.insert_into_entity(self.clone(), entity, instance)
    }

    /// remove the component from the entity
    fn remove_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
    ) -> Result<(), InteropError> {
        registration.remove_from_entity(self.clone(), entity)
    }

    /// get the component from the entity
    fn get_component(
        &self,
        entity: Entity,
        component_registration: ScriptComponentRegistration,
    ) -> Result<Option<ReflectReference>, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        let entity = cell
            .get_entity(entity)
            .map_err(|_| InteropError::missing_entity(entity))?;

        if entity.contains_id(component_registration.component_id) {
            Ok(Some(ReflectReference {
                base: ReflectBaseType {
                    type_id: component_registration.type_registration().type_id(),
                    base_id: ReflectBase::Component(
                        entity.id(),
                        component_registration.component_id,
                    ),
                },
                reflect_path: Default::default(),
            }))
        } else {
            Ok(None)
        }
    }

    /// check if the entity has the component
    fn has_component(
        &self,
        entity: Entity,
        component_id: ComponentId,
    ) -> Result<bool, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        let entity = cell
            .get_entity(entity)
            .map_err(|_| InteropError::missing_entity(entity))?;

        Ok(entity.contains_id(component_id))
    }

    fn insert_bundle(
        &self,
        entity: Entity,
        registration: ScriptBundleRegistration,
        value: ReflectReference,
    ) -> Result<(), InteropError> {
        let instance =
            registration.instance_from_script(self.clone(), ScriptValue::Reference(value))?;
        registration.insert_into_entity(self.clone(), entity, instance)
    }

    fn spawn_bundle(
        &self,
        registration: ScriptBundleRegistration,
        value: ReflectReference,
    ) -> Result<Entity, InteropError> {
        let instance =
            registration.instance_from_script(self.clone(), ScriptValue::Reference(value))?;
        let entity = self.spawn()?;
        if let Err(e) = registration.insert_into_entity(self.clone(), entity, instance) {
            self.despawn(entity)?;
            return Err(e);
        }
        Ok(entity)
    }

    fn with_component<C: Component, O, F: FnOnce(Option<&C>) -> O>(
        &self,
        entity: Entity,
        f: F,
    ) -> Result<O, InteropError> {
        let type_id = std::any::TypeId::of::<C>();
        let component_id = self.get_component_id(type_id)?.ok_or(
            InteropError::unregistered_component_or_resource_type(type_id),
        )?;
        self.check_archetype_access(entity, component_id, false)?;
        let cell = self.as_unsafe_world_cell()?;
        // Safety: we claimed access to this component and checked the entity is in an allowed archetype
        self.with_read_access(component_id, || {
            f(unsafe { cell.get_entity(entity).ok().and_then(|e| e.get::<C>()) })
        })
        .map_err(Into::into)
    }

    fn with_component_mut<C: Component<Mutability = Mutable>, O, F: FnOnce(Option<Mut<C>>) -> O>(
        &self,
        entity: Entity,
        f: F,
    ) -> Result<O, InteropError> {
        let type_id = std::any::TypeId::of::<C>();
        let component_id = self.get_component_id(type_id)?.ok_or(
            InteropError::unregistered_component_or_resource_type(type_id),
        )?;
        self.check_archetype_access(entity, component_id, true)?;
        let cell = self.as_unsafe_world_cell()?;
        // Safety: we claimed access to this component and checked the entity is in an allowed archetype
        self.with_write_access(component_id, || {
            f(unsafe { cell.get_entity(entity).ok().and_then(|e| e.get_mut::<C>()) })
        })
        .map_err(Into::into)
    }

    fn with_or_insert_component_mut<
        C: Component<Mutability = Mutable> + Default,
        O,
        F: FnOnce(&mut C) -> O,
    >(
        &self,
        entity: Entity,
        f: F,
    ) -> Result<O, InteropError> {
        self.with_world_mut(|world| match world.get_mut::<C>(entity) {
            Some(mut component) => f(&mut component),
            None => {
                let mut component = C::default();
                let mut commands = world.commands();
                let result = f(&mut component);
                commands.entity(entity).insert(component);
                world.flush();
                result
            }
        })
    }

    /// get the given resource
    fn get_resource(
        &self,
        resource_id: ComponentId,
    ) -> Result<Option<ReflectReference>, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        let component_info = match cell.components().get_info(resource_id) {
            Some(info) => info,
            None => return Ok(None),
        };

        Ok(Some(ReflectReference {
            base: ReflectBaseType {
                type_id: component_info
                    .type_id()
                    .ok_or_else(|| {
                        InteropError::unsupported_operation(
                            None,
                            None,
                            format!(
                                "Resource {} does not have a type id. Such resources are not supported by BMS.",
                                component_info.name()
                            ),
                        )
                    })?,
                base_id: ReflectBase::Resource(resource_id),
            },
            reflect_path: Default::default(),
        }))
    }

    fn remove_resource(
        &self,
        registration: ScriptResourceRegistration,
    ) -> Result<(), InteropError> {
        // check is a resource
        registration
            .type_registration()
            .type_registration()
            .data::<ReflectResource>()
            .ok_or_else(|| {
                InteropError::missing_type_data(
                    registration.registration.type_id(),
                    "ReflectResource".to_owned(),
                )
            })?;

        //  TODO: this shouldn't need entire world access it feels
        self.with_world_mut(|world| {
            let _ = world.remove_resource_by_id(registration.resource_id);
        })
    }

    fn has_resource(&self, resource_id: ComponentId) -> Result<bool, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        // Safety: we are not reading the value at all
        let res_ptr = unsafe { cell.get_resource_by_id(resource_id) };
        Ok(res_ptr.is_some())
    }

    fn with_resource<R: Resource, O, F: FnOnce(&R) -> O>(&self, f: F) -> Result<O, InteropError> {
        let type_id = std::any::TypeId::of::<R>();
        let resource_id = self.get_resource_id(type_id)?.ok_or(
            InteropError::unregistered_component_or_resource_type(type_id),
        )?;
        let cell = self.as_unsafe_world_cell()?;
        // Safety: we claimed access to this resource
        self.with_read_access_and_then(resource_id, || {
            Ok(f(unsafe {
                cell.get_resource::<R>()
                    .ok_or_else(|| InteropError::missing_resource(type_id))?
            }))
        })
    }

    fn with_resource_mut<R: Resource<Mutability = Mutable>, O, F: FnOnce(Mut<R>) -> O>(
        &self,
        f: F,
    ) -> Result<O, InteropError> {
        let type_id = std::any::TypeId::of::<R>();
        let resource_id = self.get_resource_id(type_id)?.ok_or(
            InteropError::unregistered_component_or_resource_type(type_id),
        )?;
        let cell = self.as_unsafe_world_cell()?;
        // Safety: we claimed access to this resource
        self.with_write_access_and_then(resource_id, || {
            Ok(f(unsafe {
                cell.get_resource_mut::<R>()
                    .ok_or_else(|| InteropError::missing_resource(type_id))?
            }))
        })
    }

    fn trigger_event(
        &self,
        registration: ScriptTypeRegistration,
        event: &ReflectReference,
    ) -> Result<(), InteropError> {
        let reflect_event = registration
            .type_registration()
            .data::<ReflectEvent>()
            .ok_or_else(|| {
                InteropError::missing_type_data(registration.type_id(), "ReflectEvent".to_owned())
            })?
            .clone();
        let value = event.to_owned_value_of_type(self.clone(), registration.type_id())?;
        let registry = self.type_registry().clone();
        self.with_world_mut(|world| {
            let registry = registry.read();
            reflect_event.trigger(world, value.as_ref(), &registry);
            // apply the commands of observers, i.e. the callbacks of script observers
            world.flush();
        })
    }

    fn add_script_observer(
        &self,
        event: ScriptTypeRegistration,
        components: Vec<ScriptComponentRegistration>,
        entities: Vec<Entity>,
        label: String,
        attachment: ScriptAttachment,
    ) -> Result<Entity, InteropError> {
        let reflect_event = event
            .type_registration()
            .data::<ReflectEvent>()
            .ok_or_else(|| {
                InteropError::missing_type_data(event.type_id(), "ReflectEvent".to_owned())
            })?
            .clone();
        let runners = self.script_callback_runners().clone();
        let recipients = Recipients::from(attachment.clone());

        let mut observer = reflect_event.create_observer(Box::new(move |event, mut world| {
            let value = match event.reflect_clone() {
                Ok(value) => value,
                Err(e) => {
                    bevy_log::error!("script observer could not clone its event: {e}");
                    return;
                }
            };
            let reference = ReflectReference::new_allocated_boxed(value);
            run_observer_callback(
                &mut world,
                &runners,
                &recipients,
                &label,
                ScriptValue::Reference(reference),
            );
        }));
        for component in components {
            observer = observer.with_component(component.component_id);
        }
        if !entities.is_empty() {
            observer = observer.with_entities(entities);
        }
        // removed again when the script is unloaded
        self.with_world_mut(|world| {
            world
                .spawn((observer, crate::ScriptObserverOwner(attachment)))
                .id()
        })
    }

    fn register_script_export(
        &self,
        namespace: &str,
        name: &str,
        label: String,
        owner: ScriptAttachment,
    ) -> Result<(), InteropError> {
        validate_script_namespace_and_name(namespace, name)?;
        self.component_registry()
            .write()
            .register_export(crate::ScriptExport {
                name: name.to_owned(),
                namespace: namespace.to_owned(),
                owner,
                label,
            })
    }

    fn call_script_export(
        &self,
        path: &str,
        args: Vec<ScriptValue>,
    ) -> Result<ScriptValue, InteropError> {
        // looked up on every call, so replaced exports are picked up and removed ones fail
        let export = self
            .component_registry()
            .read()
            .get_export(path)
            .cloned()
            .ok_or_else(|| {
                InteropError::string(format!(
                    "the exported function `{path}` does not exist (anymore): the script that exported it may have been unloaded"
                ))
            })?;
        let runners = self.script_callback_runners().clone();
        let recipients = Recipients::from(export.owner.clone());
        let results = runners.run(self.clone(), &recipients, &export.label, args)?;
        match results.into_iter().next() {
            Some((_, Ok(value))) => Ok(value),
            Some((_, Err(e))) if e.is_context_busy() => Err(InteropError::string(format!(
                "cannot call the exported function `{path}` right now: the script {} that exports it is currently running. \
                Exported functions cannot be called by a script from inside a callback of the same script context (including scripts sharing it), \
                call the function directly instead, or use `queue_script_callback`.",
                export.owner
            ))),
            Some((_, Err(e))) => Err(e),
            None => Err(InteropError::string(format!(
                "cannot call the exported function `{path}`: the script {} that exports it is not loaded",
                export.owner
            ))),
        }
    }

    fn register_script_event(
        &self,
        namespace: &str,
        name: &str,
        allow_existing: bool,
    ) -> Result<ScriptEventRegistration, InteropError> {
        validate_script_namespace_and_name(namespace, name)?;
        let path = script_path(namespace, name);
        let component_registry = self.component_registry();
        let mut registry = component_registry.write();
        if let Some(existing) = registry.get_event(&path) {
            if allow_existing {
                return Ok(existing.clone());
            }
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!(
                    "script registered event '{path}' already exists, pass `allow_existing = true` to get the existing registration instead"
                ),
            ));
        }
        if registry.get(&path).is_some() {
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!("a script registered component named '{path}' already exists"),
            ));
        }
        if registry.get_export(&path).is_some() {
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!("a function named '{path}' is already exported"),
            ));
        }
        if registry.get_system_set_owner(&path).is_some() {
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!("a script registered system set named '{path}' already exists"),
            ));
        }
        let registration = ScriptEventRegistration { name: path.into() };
        registry.register_event(registration.clone());
        Ok(registration)
    }

    fn register_script_system_set(
        &self,
        namespace: &str,
        name: &str,
        allow_existing: bool,
        owner: ScriptAttachment,
    ) -> Result<ReflectSystemSet, InteropError> {
        validate_script_namespace_and_name(namespace, name)?;
        let path = script_path(namespace, name);
        let component_registry = self.component_registry();
        let mut registry = component_registry.write();
        if registry.get_system_set_owner(&path).is_some() && !allow_existing {
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!(
                    "script registered system set '{path}' already exists, pass `allow_existing = true` to get the existing set instead"
                ),
            ));
        }
        if registry.get(&path).is_some()
            || registry.get_event(&path).is_some()
            || registry.get_export(&path).is_some()
        {
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!(
                    "a script registered component, event or exported function named '{path}' already exists"
                ),
            ));
        }
        if registry.get_system_set_owner(&path).is_none() {
            registry.register_system_set(path.clone(), owner);
        }
        Ok(ReflectSystemSet::from_interned(
            ScriptNamedSet(path).intern(),
        ))
    }

    fn get_system_set_by_name(&self, path: &str) -> Option<ReflectSystemSet> {
        let set = if path.starts_with(SCRIPT_NAMESPACE_PREFIX) {
            self.component_registry()
                .read()
                .get_system_set_owner(path)
                .map(|_| ScriptNamedSet(path.to_owned()).intern())
        } else {
            self.with_resource(|registry: &ScriptSystemSetRegistry| registry.get(path))
                .ok()
                .flatten()
        };
        set.map(ReflectSystemSet::from_interned)
    }

    fn add_script_event_observer(
        &self,
        event: ScriptEventRegistration,
        label: String,
        attachment: ScriptAttachment,
    ) -> Result<Entity, InteropError> {
        let name = event.name;
        let runners = self.script_callback_runners().clone();
        let recipients = Recipients::from(attachment.clone());
        let observer = Observer::new(move |event: On<ScriptEvent>, mut world: DeferredWorld| {
            if event.name != name {
                return;
            }
            run_observer_callback(
                &mut world,
                &runners,
                &recipients,
                &label,
                event.payload.clone(),
            );
        });
        // removed again when the script is unloaded
        self.with_world_mut(|world| {
            world
                .spawn((observer, crate::ScriptObserverOwner(attachment)))
                .id()
        })
    }

    fn trigger_script_event(
        &self,
        event: ScriptEventRegistration,
        payload: ScriptValue,
    ) -> Result<(), InteropError> {
        self.with_world_mut(|world| {
            world.trigger(ScriptEvent {
                name: event.name,
                payload,
            });
            // apply the commands of observers, i.e. the callbacks of script observers
            world.flush();
        })
    }

    fn write_message(
        &self,
        registration: ScriptTypeRegistration,
        message: &ReflectReference,
    ) -> Result<(), InteropError> {
        let reflect_message = registration
            .type_registration()
            .data::<ReflectMessage>()
            .ok_or_else(|| {
                InteropError::missing_type_data(registration.type_id(), "ReflectMessage".to_owned())
            })?
            .clone();
        let value = message.to_owned_value_of_type(self.clone(), registration.type_id())?;
        let registry = self.type_registry().clone();
        self.with_world_mut(|world| {
            let registry = registry.read();
            reflect_message.write_message(world, value.as_ref(), &registry);
        })
    }

    fn with_world<O, F: FnOnce(&World) -> O>(&self, f: F) -> Result<O, InteropError> {
        self.with_world_access(f).map_err(Into::into)
    }

    fn with_world_mut<O, F: FnOnce(&mut World) -> O>(&self, f: F) -> Result<O, InteropError> {
        self.with_world_mut_access(f).map_err(Into::into)
    }

    fn get_parent(&self, entity: Entity) -> Result<Option<Entity>, InteropError> {
        if !self.is_valid_entity(entity)? {
            return Err(InteropError::missing_entity(entity));
        }

        self.with_component(entity, |c: Option<&ChildOf>| c.map(|c| c.parent()))
    }

    fn get_children(&self, entity: Entity) -> Result<Vec<Entity>, InteropError> {
        if !self.is_valid_entity(entity)? {
            return Err(InteropError::missing_entity(entity));
        }

        self.with_component(entity, |c: Option<&Children>| {
            c.map(|c| c.to_vec()).unwrap_or_default()
        })
    }

    fn push_children(&self, parent: Entity, children: &[Entity]) -> Result<(), InteropError> {
        // verify entities exist
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }
        for c in children {
            if !self.is_valid_entity(*c)? {
                return Err(InteropError::missing_entity(*c));
            }
        }
        self.with_world_mut(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).add_children(children);
            queue.apply(world);
        })
    }

    fn insert_children(
        &self,
        parent: Entity,
        index: usize,
        children: &[Entity],
    ) -> Result<(), InteropError> {
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }

        for c in children {
            if !self.is_valid_entity(*c)? {
                return Err(InteropError::missing_entity(*c));
            }
        }

        self.with_world_mut(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).insert_children(index, children);
            queue.apply(world);
        })
    }

    fn remove_children(&self, parent: Entity, children: &[Entity]) -> Result<(), InteropError> {
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }

        for c in children {
            if !self.is_valid_entity(*c)? {
                return Err(InteropError::missing_entity(*c));
            }
        }
        self.with_world_mut(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).detach_children(children);
            queue.apply(world);
        })
    }

    fn exit(&self) -> Result<(), InteropError> {
        self.with_world_mut(|world| {
            world.write_message(AppExit::Success);
        })
    }

    fn get_schedule_by_name(&self, schedule_name: String) -> Option<ReflectSchedule> {
        let schedule_registry = self.schedule_registry();
        let schedule_registry = schedule_registry.read();

        schedule_registry
            .get_schedule_by_name(&schedule_name)
            .cloned()
    }

    fn load_script_asset<'a>(
        &self,
        asset_path: impl Into<AssetPath<'a>>,
    ) -> Result<Handle<ScriptAsset>, InteropError> {
        self.with_resource(|r: &AssetServer| r.load(asset_path))
    }

    fn get_script_asset_load_state(
        &self,
        script: Handle<ScriptAsset>,
    ) -> Result<LoadState, InteropError> {
        self.with_resource(|r: &AssetServer| r.load_state(script.id()))
    }

    fn call_operator(
        &self,
        type_id: TypeId,
        name: impl Into<Cow<'static, str>>,
        args: Vec<ScriptValue>,
        context: FunctionCallContext,
    ) -> Result<ScriptValue, InteropError> {
        // operators not defined on the type itself fall back to the generic ones on `ReflectReference`, i.e. `eq`.
        // The registry is unlocked before the call, which may look up functions itself
        let func = self.lookup_function([type_id, TypeId::of::<ReflectReference>()], name);
        match func {
            Ok(func) => func.call(args, context),
            Err(name) => Err(InteropError::missing_function(
                name.to_string(),
                FunctionScope::OnType(type_id),
                Some(context),
            )),
        }
    }

    fn get_functions_on_type(
        &self,
        type_id: TypeId,
    ) -> Vec<(Cow<'static, str>, DynamicScriptFunction)> {
        let registry = self.script_function_registry();
        let registry = registry.read();

        registry
            .iter_type(type_id)
            .chain(registry.iter_type(TypeId::of::<ReflectReference>()))
            .map(|(key, func)| (key.name.clone(), func.clone()))
            .collect()
    }

    fn lookup_member<'n>(
        &self,
        reference: &ReflectReference,
        type_id: TypeId,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<ScriptValue, Cow<'n, str>> {
        Lookups::with(self, |lookups| lookups.member(reference, type_id, name))
    }

    fn lookup_static_member<'n>(
        &self,
        type_id: TypeId,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<ScriptValue, Cow<'n, str>> {
        Lookups::with(self, |lookups| lookups.static_member(type_id, name))
    }

    fn get_type_by_name(&self, type_name: &str) -> Option<ScriptTypeRegistration> {
        let type_registry = self.type_registry();
        let type_registry = type_registry.read();
        type_registry
            .get_with_type_path(type_name)
            .map(|registration| ScriptTypeRegistration::new(Arc::new(registration.clone())))
    }

    fn get_type_registration(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<AnyTypeRegistration, InteropError> {
        let registration = match self.get_resource_type(registration)? {
            Ok(res) => {
                return Ok(Union::new_right(Union::new_right(Union::new_left(res))));
            }
            Err(registration) => registration,
        };

        let registration = match self.get_component_type(registration)? {
            Ok(comp) => {
                return Ok(Union::new_right(Union::new_left(comp)));
            }
            Err(registration) => registration,
        };

        let registration = match self.get_bundle_type(registration)? {
            Ok(bundle) => {
                return Ok(Union::new_right(Union::new_right(Union::new_right(bundle))));
            }
            Err(registration) => registration,
        };

        Ok(Union::new_left(registration))
    }

    fn get_type_registration_by_name(
        &self,
        type_name: String,
    ) -> Result<Option<AnyTypeRegistration>, InteropError> {
        let val = self.get_type_by_name(&type_name);
        Ok(match val {
            Some(registration) => Some(self.get_type_registration(registration)?),
            None => {
                // try the script registered components
                let components = self.component_registry();
                let components = components.read();
                // by full path (i.e. `script.game.Enemy`)
                components
                    .find(&type_name)
                    .map(|c| Union::new_right(Union::new_left(c.registration.clone())))
            }
        })
    }

    fn get_resource_type(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<Result<ScriptResourceRegistration, ScriptTypeRegistration>, InteropError> {
        Ok(match self.get_resource_id(registration.type_id())? {
            // Safety: the id was looked up by this registration's type id
            Some(resource_id) => {
                Ok(unsafe { ScriptResourceRegistration::new(registration, resource_id) })
            }
            None => Err(registration),
        })
    }

    fn get_component_type(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<Result<ScriptComponentRegistration, ScriptTypeRegistration>, InteropError> {
        Ok(match self.get_component_id(registration.type_id())? {
            // Safety: the id was looked up by this registration's type id
            Some(comp_id) => Ok(unsafe { ScriptComponentRegistration::new(registration, comp_id) }),
            None => Err(registration),
        })
    }

    fn get_bundle_type(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<Result<ScriptBundleRegistration, ScriptTypeRegistration>, InteropError> {
        if registration
            .type_registration()
            .data::<ReflectBundle>()
            .is_none()
        {
            return Ok(Err(registration));
        }
        Ok(Ok(ScriptBundleRegistration::new(registration)))
    }

    fn script_function_registry(&'_ self) -> Ref<'_, AppScriptFunctionRegistry> {
        #[allow(
            clippy::unwrap_used,
            reason = "internal domain boundary, enforced at creation of the guard"
        )]
        self.get_cached_registry().unwrap()
    }

    fn script_callback_runners(&'_ self) -> Ref<'_, AppScriptCallbackRunners> {
        #[allow(
            clippy::unwrap_used,
            reason = "internal domain boundary, enforced at creation of the guard"
        )]
        self.get_cached_registry().unwrap()
    }

    fn type_catalogue(&'_ self) -> Ref<'_, AppScriptTypeCatalogue> {
        #[allow(
            clippy::unwrap_used,
            reason = "internal domain boundary, enforced at creation of the guard"
        )]
        self.get_cached_registry().unwrap()
    }

    fn component_registry(&'_ self) -> Ref<'_, AppScriptComponentRegistry> {
        #[allow(
            clippy::unwrap_used,
            reason = "internal domain boundary, enforced at creation of the guard"
        )]
        self.get_cached_registry().unwrap()
    }

    fn schedule_registry(&'_ self) -> Ref<'_, AppScheduleRegistry> {
        #[allow(
            clippy::unwrap_used,
            reason = "internal domain boundary, enforced at creation of the guard"
        )]
        self.get_cached_registry().unwrap()
    }

    fn current_attachment(&self) -> CurrentScriptAttachment {
        self.get_cached_registry::<CurrentScriptAttachment>()
            .map(|r| r.clone())
            .unwrap_or_else(CurrentScriptAttachment::empty)
    }

    fn set_current_attachment(&self, attachment: ScriptAttachment) {
        self.replace_cached_registry::<CurrentScriptAttachment>(CurrentScriptAttachment(Some(
            attachment,
        )));
    }

    fn register_script_component(
        &self,
        namespace: &str,
        component_name: &str,
        allow_existing: bool,
    ) -> Result<ScriptComponentRegistration, InteropError> {
        validate_script_namespace_and_name(namespace, component_name)?;
        let path = script_path(namespace, component_name);
        let component_registry = self.component_registry();
        let component_registry_read = component_registry.read();
        if let Some(existing) = component_registry_read.get(&path) {
            if allow_existing {
                return Ok(existing.registration.clone());
            }
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!(
                    "script registered component '{path}' already exists, pass `allow_existing = true` to get the existing registration instead"
                ),
            ));
        }
        if component_registry_read.get_export(&path).is_some() {
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!("a function named '{path}' is already exported"),
            ));
        }
        if component_registry_read.get_event(&path).is_some() {
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!("a script registered event named '{path}' already exists"),
            ));
        }
        if component_registry_read
            .get_system_set_owner(&path)
            .is_some()
        {
            return Err(InteropError::unsupported_operation(
                None,
                None,
                format!("a script registered system set named '{path}' already exists"),
            ));
        }

        let component_id = self.with_world_mut_access(|w| {
            let descriptor = unsafe {
                // Safety: same safety guarantees as ComponentDescriptor::new
                // we know the type in advance
                // we only use this method to name the component
                ComponentDescriptor::new_with_layout(
                    path.clone(),
                    DynamicComponent::STORAGE_TYPE,
                    Layout::new::<DynamicComponent>(),
                    needs_drop::<DynamicComponent>().then_some(|x| x.drop_as::<DynamicComponent>()),
                    true,
                    false,
                    ComponentCloneBehavior::Default,
                    None,
                )
            };
            w.register_component_with_descriptor(descriptor)
        })?;
        drop(component_registry_read);
        let mut component_registry = component_registry.write();

        // Safety: the component was just registered with a `DynamicComponent` layout
        let mut registration = unsafe {
            ScriptComponentRegistration::new(
                ScriptTypeRegistration::new(Arc::new(
                    <DynamicComponent as GetTypeRegistration>::get_type_registration(),
                )),
                component_id,
            )
        };
        registration.script_namespace = Some(namespace.to_owned());

        let component_info = DynamicComponentInfo {
            name: component_name.to_owned(),
            namespace: namespace.to_owned(),
            registration: registration.clone(),
        };

        component_registry.register(component_info);

        // TODO: we should probably retrieve this from the registry, but I don't see what people would want to register on this type
        // in addition to the existing registrations.
        Ok(registration)
    }

    fn setup_cache_raw(
        attachment: CurrentScriptAttachment,
        function_registry: AppScriptFunctionRegistry,
        schedule_registry: AppScheduleRegistry,
        component_registry: AppScriptComponentRegistry,
        callback_runners: AppScriptCallbackRunners,
        type_catalogue: AppScriptTypeCatalogue,
    ) -> RegistryCache {
        debug_assert_eq!(AppScriptFunctionRegistry::SLOT, 0);
        debug_assert_eq!(AppScheduleRegistry::SLOT, 1);
        debug_assert_eq!(AppScriptComponentRegistry::SLOT, 2);
        debug_assert_eq!(CurrentScriptAttachment::SLOT, 3);
        debug_assert_eq!(AppScriptCallbackRunners::SLOT, 4);
        debug_assert_eq!(AppScriptTypeCatalogue::SLOT, 5);

        [
            Rc::new(RefCell::new(function_registry)),
            Rc::new(RefCell::new(schedule_registry)),
            Rc::new(RefCell::new(component_registry)),
            Rc::new(RefCell::new(attachment)),
            Rc::new(RefCell::new(callback_runners)),
            Rc::new(RefCell::new(type_catalogue)),
        ]
    }

    fn setup_cache(world: &World, attachment: CurrentScriptAttachment) -> RegistryCache {
        debug_assert_eq!(AppScriptFunctionRegistry::SLOT, 0);
        debug_assert_eq!(AppScheduleRegistry::SLOT, 1);
        debug_assert_eq!(AppScriptComponentRegistry::SLOT, 2);
        debug_assert_eq!(CurrentScriptAttachment::SLOT, 3);
        debug_assert_eq!(AppScriptCallbackRunners::SLOT, 4);
        debug_assert_eq!(AppScriptTypeCatalogue::SLOT, 5);

        [
            Rc::new(RefCell::new(
                world
                    .get_resource::<AppScriptFunctionRegistry>()
                    .cloned()
                    .unwrap_or_default(),
            )),
            Rc::new(RefCell::new(
                world
                    .get_resource::<AppScheduleRegistry>()
                    .cloned()
                    .unwrap_or_default(),
            )),
            Rc::new(RefCell::new(
                world
                    .get_resource::<AppScriptComponentRegistry>()
                    .cloned()
                    .unwrap_or_default(),
            )),
            Rc::new(RefCell::new(attachment)),
            Rc::new(RefCell::new(
                world
                    .get_resource::<AppScriptCallbackRunners>()
                    .cloned()
                    .unwrap_or_default(),
            )),
            Rc::new(RefCell::new(
                world
                    .get_resource::<AppScriptTypeCatalogue>()
                    .cloned()
                    .unwrap_or_default(),
            )),
        ]
    }

    // /// Creates a system from a system builder and inserts it into the given schedule
    // pub fn add_system<P: IntoScriptPluginParams>(
    //     &self,
    //     schedule: &ReflectSchedule,
    //     builder: ScriptSystemBuilder,
    // ) -> Result<ReflectSystem, InteropError> {
    //     debug!(
    //         "Adding script system '{}' for script '{}' to schedule '{}'",
    //         builder.name,
    //         builder.attachment,
    //         schedule.identifier()
    //     );

    //     builder.build::<P>(self.clone(), schedule)
    // }
}

/// Function lookups used by [`WorldExtensions`] and [`crate::dispatch`], not exposed to language implementations.
pub(crate) trait FunctionLookups {
    /// Looks up a function by name across multiple type namespaces.
    fn lookup_function<'n>(
        &self,
        type_ids: impl IntoIterator<Item = TypeId>,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<DynamicScriptFunction, Cow<'n, str>>;

    /// Looks up a reserved function (see the "Reserved Functions" section of the book) on the `ReflectReference` namespace,
    /// ignoring functions registered on the types themselves.
    ///
    /// Used for functions languages rely on and which types cannot override, such as `display` and `iter`.
    fn lookup_reserved_function(
        &self,
        name: impl Into<Cow<'static, str>>,
        context: FunctionCallContext,
    ) -> Result<DynamicScriptFunction, InteropError>;
}

impl FunctionLookups for WorldAccessGuard<'_> {
    fn lookup_function<'n>(
        &self,
        type_ids: impl IntoIterator<Item = TypeId>,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<DynamicScriptFunction, Cow<'n, str>> {
        Lookups::with(self, |lookups| lookups.function(type_ids, name))
    }

    fn lookup_reserved_function(
        &self,
        name: impl Into<Cow<'static, str>>,
        context: FunctionCallContext,
    ) -> Result<DynamicScriptFunction, InteropError> {
        self.lookup_function([TypeId::of::<ReflectReference>()], name)
            .map_err(|name| {
                InteropError::missing_function(name, FunctionScope::all_references(), Some(context))
            })
    }
}

/// Delivers an event to the callback of a script observer through the callback runners.
///
/// Runs once the commands of the triggering operation are applied, see [`AppScriptCallbackRunners::run_or_queue`].
/// Errors are reported through [`AppScriptCallbackRunners::report_error`].
fn run_observer_callback(
    world: &mut DeferredWorld,
    runners: &AppScriptCallbackRunners,
    recipients: &Recipients,
    label: &str,
    arg: ScriptValue,
) {
    let runners = runners.clone();
    let recipients = recipients.clone();
    let label = label.to_owned();
    world.commands().queue(move |world: &mut World| {
        let cache = WorldAccessGuard::setup_cache(world, CurrentScriptAttachment::empty());
        WorldGuard::with_static_guard(world, cache, |guard| {
            let context = || format!("in observer callback: {label}");
            match runners.run_or_queue(guard.clone(), &recipients, &label, vec![arg]) {
                Ok(results) => {
                    for (attachment, result) in results {
                        if let Err(e) = result {
                            runners.report_error(guard.clone(), Some(&attachment), context(), e);
                        }
                    }
                }
                Err(e) => runners.report_error(guard, None, context(), e),
            }
        })
    });
}

/// The type a type registration points to, if `type_id` (the type of the value behind `reference`) is one of the registration types.
fn registered_type_id(
    guard: &WorldAccessGuard,
    reference: &ReflectReference,
    type_id: TypeId,
) -> Option<TypeId> {
    fn registered<T: Reflect>(
        guard: &WorldAccessGuard,
        reference: &ReflectReference,
        registered: fn(&T) -> TypeId,
    ) -> Option<TypeId> {
        reference
            .with_reflect(guard.clone(), |r| r.try_downcast_ref::<T>().map(registered))
            .ok()
            .flatten()
    }
    if type_id == TypeId::of::<ScriptTypeRegistration>() {
        registered(guard, reference, ScriptTypeRegistration::type_id)
    } else if type_id == TypeId::of::<ScriptComponentRegistration>() {
        registered(guard, reference, |r: &ScriptComponentRegistration| {
            r.type_registration().type_id()
        })
    } else if type_id == TypeId::of::<ScriptResourceRegistration>() {
        registered(guard, reference, |r: &ScriptResourceRegistration| {
            r.type_registration().type_id()
        })
    } else if type_id == TypeId::of::<ScriptBundleRegistration>() {
        registered(guard, reference, |r: &ScriptBundleRegistration| {
            r.type_registration().type_id()
        })
    } else {
        None
    }
}

/// Function lookups under a single read of the function registry, see [`Lookups::with`].
///
/// A lookup trying several places reads the registry once, as reading it again while it's read
/// can deadlock behind a writer waiting on another thread.
pub(crate) struct Lookups<'a> {
    world: &'a WorldAccessGuard<'a>,
    pub(crate) registry: &'a crate::function::script_function::ScriptFunctionRegistry,
}

impl Lookups<'_> {
    /// Runs `f` with the function registry read, `f` must not call script functions.
    pub(crate) fn with<O>(world: &WorldAccessGuard, f: impl FnOnce(&Lookups) -> O) -> O {
        let registry = world.script_function_registry();
        let registry = registry.read();
        f(&Lookups {
            world,
            registry: &registry,
        })
    }

    /// See [`FunctionLookups::lookup_function`]
    pub(crate) fn function<'n>(
        &self,
        type_ids: impl IntoIterator<Item = TypeId>,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<DynamicScriptFunction, Cow<'n, str>> {
        let mut name = name.into();
        for type_id in type_ids {
            name = match self.registry.get_function(type_id, name) {
                Ok(func) => return Ok(func.clone()),
                Err(name) => name,
            };
        }
        Err(name)
    }

    /// Looks up a function callable on the static reference to a type, i.e. `Type.name(..)` in a script:
    /// functions registered on the type, then the type level functions of [`StaticTypeRef`] with the type bound as their first argument
    fn type_function<'n>(
        &self,
        type_id: TypeId,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<DynamicScriptFunction, Cow<'n, str>> {
        let name = match self.function([type_id], name) {
            Ok(func) => return Ok(func),
            Err(name) => name,
        };
        // the same registry read `registered_type_info` would do, types can opt out of the shared functions
        let type_info = {
            let registry = self.world.type_registry();
            let registry = registry.read();
            registry
                .get(type_id)
                .filter(|registration| !registration.contains::<ReflectNoTypeFunctions>())
                .map(|registration| registration.type_info())
        };
        match type_info {
            // the type level functions of `StaticTypeRef` are already addressed at that type directly
            Some(type_info) if type_info.type_id() != TypeId::of::<StaticTypeRef>() => {
                self.registry.get_bound_to_type(type_info, name)
            }
            _ => Err(name),
        }
    }

    /// See [`WorldExtensions::lookup_static_member`]
    fn static_member<'n>(
        &self,
        type_id: TypeId,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<ScriptValue, Cow<'n, str>> {
        let name = match self.type_function(type_id, name) {
            Ok(func) => return Ok(ScriptValue::Function(func)),
            Err(name) => name,
        };
        let Ok(type_info) = registered_type_info(self.world, type_id) else {
            return Err(name);
        };
        match EnumVariantRef::from_name(type_info, &name) {
            Some(variant) => V(variant).into_script(self.world.clone()).map_err(|_| name),
            None => Err(name),
        }
    }

    /// See [`WorldExtensions::lookup_member`]
    pub(crate) fn member<'n>(
        &self,
        reference: &ReflectReference,
        type_id: TypeId,
        name: impl Into<Cow<'n, str>>,
    ) -> Result<ScriptValue, Cow<'n, str>> {
        if let Some(registered) = registered_type_id(self.world, reference, type_id) {
            // the static members of the type come before the functions shared by all references,
            // i.e. `PlaybackSettings.remove()` is not the generic `remove`
            let name = match self.function([type_id], name) {
                Ok(func) => return Ok(ScriptValue::Function(func)),
                Err(name) => name,
            };
            let name = match self.static_member(registered, name) {
                Ok(member) => return Ok(member),
                Err(name) => name,
            };
            return self
                .function([TypeId::of::<ReflectReference>()], name)
                .map(ScriptValue::Function);
        }
        // functions callable on the value: its type's, then the ones shared by all references
        let name = match self.function([type_id, TypeId::of::<ReflectReference>()], name) {
            Ok(func) => return Ok(ScriptValue::Function(func)),
            Err(name) => name,
        };
        if type_id == TypeId::of::<EnumVariantRef>() {
            return match reference.downcast::<EnumVariantRef>(self.world.clone()) {
                Ok(variant) => self
                    .function([variant.type_id], name)
                    .map(ScriptValue::Function),
                Err(_) => Err(name),
            };
        }
        Err(name)
    }
}

impl CachedRegistry for AppScriptFunctionRegistry {
    const SLOT: usize = 0;
}
impl CachedRegistry for AppScheduleRegistry {
    const SLOT: usize = 1;
}
impl CachedRegistry for AppScriptComponentRegistry {
    const SLOT: usize = 2;
}

/// The script whose callback is currently running, cached in each world guard.
///
/// [`None`] when no script is running, see [`Self::empty`].
#[derive(Clone, Default)]
pub struct CurrentScriptAttachment(pub Option<ScriptAttachment>);

impl CurrentScriptAttachment {
    /// No script is running.
    ///
    /// Use this when creating a guard which is not tied to one script, e.g. in a system running callbacks on many scripts.
    /// Each callback marks its own script as current for the duration of the call (see `ScriptingHandler::handle` in core).
    pub fn empty() -> Self {
        Self(None)
    }
}
impl CachedRegistry for CurrentScriptAttachment {
    const SLOT: usize = 3;
}
impl CachedRegistry for AppScriptCallbackRunners {
    const SLOT: usize = 4;
}
impl CachedRegistry for AppScriptTypeCatalogue {
    const SLOT: usize = 5;
}

/// Default constructs an instance of the given type, using its `ReflectDefault` or `ReflectFromWorld` type data.
pub(crate) fn default_instance(
    world: WorldGuard,
    registration: &TypeRegistration,
) -> Result<Box<dyn Reflect>, InteropError> {
    if let Some(default_td) = registration.data::<ReflectDefault>() {
        Ok(default_td.default())
    } else if let Some(from_world_td) = registration.data::<ReflectFromWorld>() {
        world.with_world_mut(|world| from_world_td.from_world(world))
    } else {
        Err(InteropError::missing_type_data(
            registration.type_id(),
            "ReflectDefault or ReflectFromWorld".to_owned(),
        ))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::function::from::R;
    use bevy_reflect::Reflect;
    use std::sync::Arc;
    use test_utils::test_data::{
        CompWithDefaultAndComponentData, GetTestEntityId, SimpleEnum, SimpleStruct,
        SimpleTupleStruct, TestBundle, TestNestedBundle, TestResource, UnitStruct, setup_world,
    };

    #[test]
    fn lookup_type_function_prefers_own_functions_and_binds_shared_ones() {
        use crate::function::namespace::NamespaceBuilder;

        let mut world = setup_world(|_, _| {});
        NamespaceBuilder::<StaticTypeRef>::new_unregistered(&mut world)
            .register("describe", |_: StaticTypeRef| 1usize);
        NamespaceBuilder::<SimpleStruct>::new_unregistered(&mut world)
            .register("describe", || 2usize);

        let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
        let world = WorldAccessGuard::new_exclusive(&mut world, cache);
        let lookup_type_function =
            |type_id, name| Lookups::with(&world, |lookups| lookups.type_function(type_id, name));

        // shared functions have the type bound
        let shared = lookup_type_function(TypeId::of::<SimpleTupleStruct>(), "describe").unwrap();
        assert!(shared.info.arg_info.is_empty());
        assert_eq!(
            shared.info.namespace,
            FunctionScope::OnType(TypeId::of::<SimpleTupleStruct>())
        );

        // functions on the type itself take priority
        let own = lookup_type_function(TypeId::of::<SimpleStruct>(), "describe").unwrap();
        assert_eq!(
            own.info.namespace,
            FunctionScope::OnType(TypeId::of::<SimpleStruct>())
        );

        assert!(lookup_type_function(TypeId::of::<SimpleStruct>(), "missing").is_err());
    }

    #[test]
    fn lookup_member_reaches_static_members_through_registrations_and_enum_functions_through_variants()
     {
        use crate::function::namespace::NamespaceBuilder;

        let mut world = setup_world(|_, _| {});
        NamespaceBuilder::<SimpleStruct>::new_unregistered(&mut world)
            .register("describe", || 2usize);
        NamespaceBuilder::<SimpleEnum>::new_unregistered(&mut world)
            .register("describe", |_: R<SimpleEnum>| 3usize);

        let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
        let world = WorldAccessGuard::new_exclusive(&mut world, cache);
        let registration_of = |type_id: TypeId| {
            let registration = world.type_registry().read().get(type_id).unwrap().clone();
            let registration = ScriptTypeRegistration::new(Arc::new(registration));
            ReflectReference::new_allocated(registration)
        };

        // a registration, i.e. an entry of `import_namespace`, gives access to the static functions of its type
        let registration = registration_of(TypeId::of::<SimpleStruct>());
        let registration_type = TypeId::of::<ScriptTypeRegistration>();
        let Ok(ScriptValue::Function(function)) =
            world.lookup_member(&registration, registration_type, "describe")
        else {
            panic!("expected the static function of the registered type")
        };
        assert_eq!(
            function.info.namespace,
            FunctionScope::OnType(TypeId::of::<SimpleStruct>())
        );
        // the functions of the registration itself still come first
        assert!(
            world
                .lookup_member(&registration, registration_type, "missing")
                .is_err()
        );

        // and to its enum variants
        let enum_registration = registration_of(TypeId::of::<SimpleEnum>());
        let Ok(ScriptValue::Reference(variant)) =
            world.lookup_member(&enum_registration, registration_type, "Unit")
        else {
            panic!("expected the variant of the registered enum")
        };

        // a variant gives access to the functions of its enum
        let Ok(ScriptValue::Function(function)) =
            world.lookup_member(&variant, TypeId::of::<EnumVariantRef>(), "describe")
        else {
            panic!("expected the function of the enum")
        };
        assert_eq!(
            function.info.namespace,
            FunctionScope::OnType(TypeId::of::<SimpleEnum>())
        );
    }

    #[test]
    fn function_registry_is_not_read_while_functions_run() {
        use crate::function::namespace::NamespaceBuilder;
        use std::time::Duration;

        let mut world = setup_world(|_, _| {});
        let lock = world
            .get_resource_or_init::<AppScriptFunctionRegistry>()
            .0
            .0
            .clone();
        // a writer queued on another thread blocks new reads, so a read held by the caller would deadlock this one
        NamespaceBuilder::<SimpleStruct>::new_unregistered(&mut world).register("op", move || {
            let writer = lock.clone();
            std::thread::spawn(move || drop(writer.write()));
            std::thread::sleep(Duration::from_millis(50));
            lock.try_read_for(Duration::from_secs(1)).is_some()
        });

        let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
        WorldAccessGuard::with_static_guard(&mut world, cache, |world| {
            let ctx = FunctionCallContext::new(bevy_mod_scripting_asset::Language::Unknown);
            let result = world.call_operator(TypeId::of::<SimpleStruct>(), "op", vec![], ctx);
            assert!(matches!(result, Ok(ScriptValue::Bool(true))), "{result:?}");
        });
    }

    #[test]
    fn lookup_static_member_finds_variants_after_functions() {
        use crate::function::namespace::NamespaceBuilder;

        let mut world = setup_world(|_, _| {});
        NamespaceBuilder::<SimpleEnum>::new_unregistered(&mut world).register("Struct", || 1usize);

        let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
        let world = WorldAccessGuard::new_exclusive(&mut world, cache);
        let enum_id = TypeId::of::<SimpleEnum>();

        // a variant is a reference to a variant ref value
        assert!(matches!(
            world.lookup_static_member(enum_id, "Unit"),
            Ok(ScriptValue::Reference(_))
        ));

        // functions take priority
        assert!(matches!(
            world.lookup_static_member(enum_id, "Struct"),
            Ok(ScriptValue::Function(_))
        ));

        assert!(world.lookup_static_member(enum_id, "Missing").is_err());
        // not an enum
        assert!(
            world
                .lookup_static_member(TypeId::of::<SimpleStruct>(), "Unit")
                .is_err()
        );
    }
    fn make_guard(world: &mut World) -> WorldAccessGuard<'_> {
        let cache = WorldAccessGuard::setup_cache(world, CurrentScriptAttachment::empty());
        WorldAccessGuard::new_exclusive(world, cache)
    }

    fn comp_reg<C: Component + Reflect>(
        guard: &WorldAccessGuard<'_>,
    ) -> ScriptComponentRegistration {
        guard
            .get_component_type(guard.get_type_by_name(std::any::type_name::<C>()).unwrap())
            .unwrap()
            .unwrap()
    }

    fn res_reg<R: Resource + Reflect>(guard: &WorldAccessGuard<'_>) -> ScriptResourceRegistration {
        guard
            .get_resource_type(guard.get_type_by_name(std::any::type_name::<R>()).unwrap())
            .unwrap()
            .unwrap()
    }

    // ── spawn / is_valid_entity / has_entity ──────────────────────────────────

    #[test]
    fn spawn_produces_valid_entity() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();
        assert!(guard.is_valid_entity(e).unwrap());
        assert_eq!(
            guard.is_valid_entity(e).unwrap(),
            guard.has_entity(e).unwrap()
        );
    }

    // ── despawn ───────────────────────────────────────────────────────────────

    #[test]
    fn despawn_invalidates_entity() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();
        guard.despawn(e).unwrap();
        assert!(!guard.is_valid_entity(e).unwrap());
    }

    #[test]
    fn despawn_missing_entity_errors() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();
        guard.despawn(e).unwrap();
        assert!(guard.despawn(e).is_err());
    }

    // ── despawn_recursive / despawn_descendants ───────────────────────────────

    #[test]
    fn despawn_recursive_removes_parent_and_child() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let parent = guard.spawn().unwrap();
        let child = guard.spawn().unwrap();
        guard.push_children(parent, &[child]).unwrap();
        guard.despawn_recursive(parent).unwrap();
        assert!(!guard.is_valid_entity(parent).unwrap());
        assert!(!guard.is_valid_entity(child).unwrap());
    }

    #[test]
    fn despawn_descendants_keeps_parent_removes_child() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let parent = guard.spawn().unwrap();
        let child = guard.spawn().unwrap();
        guard.push_children(parent, &[child]).unwrap();
        guard.despawn_descendants(parent).unwrap();
        assert!(guard.is_valid_entity(parent).unwrap());
        assert!(!guard.is_valid_entity(child).unwrap());
    }

    // ── component CRUD ────────────────────────────────────────────────────────

    #[test]
    fn add_default_has_get_remove_component_roundtrip() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();
        let reg = comp_reg::<CompWithDefaultAndComponentData>(&guard);

        assert!(!guard.has_component(e, reg.component_id).unwrap());
        assert!(guard.get_component(e, reg.clone()).unwrap().is_none());

        guard.add_default_component(e, reg.clone()).unwrap();

        assert!(guard.has_component(e, reg.component_id).unwrap());
        assert!(guard.get_component(e, reg.clone()).unwrap().is_some());

        guard.remove_component(e, reg.clone()).unwrap();

        assert!(!guard.has_component(e, reg.component_id).unwrap());
    }

    // ── with_component access-map: all four conflict cases ────────────────────

    #[test]
    fn with_component_read_read_succeeds() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();
        guard
            .add_default_component(e, comp_reg::<CompWithDefaultAndComponentData>(&guard))
            .unwrap();

        // two shared borrows of the same component must not conflict
        let result = guard.with_component(e, |_: Option<&CompWithDefaultAndComponentData>| {
            guard.with_component(e, |_: Option<&CompWithDefaultAndComponentData>| ())
        });
        assert!(result.unwrap().is_ok());
    }

    #[test]
    fn with_component_write_read_conflicts() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();
        guard
            .add_default_component(e, comp_reg::<CompWithDefaultAndComponentData>(&guard))
            .unwrap();

        let result =
            guard.with_component_mut(e, |_: Option<Mut<CompWithDefaultAndComponentData>>| {
                guard.with_component(e, |_: Option<&CompWithDefaultAndComponentData>| ())
            });
        assert!(result.unwrap().is_err());
    }

    #[test]
    fn with_component_read_write_conflicts() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();
        guard
            .add_default_component(e, comp_reg::<CompWithDefaultAndComponentData>(&guard))
            .unwrap();

        let result = guard.with_component(e, |_: Option<&CompWithDefaultAndComponentData>| {
            guard.with_component_mut(e, |_: Option<Mut<CompWithDefaultAndComponentData>>| ())
        });
        assert!(result.unwrap().is_err());
    }

    #[test]
    fn with_component_write_write_conflicts() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();
        guard
            .add_default_component(e, comp_reg::<CompWithDefaultAndComponentData>(&guard))
            .unwrap();

        let result =
            guard.with_component_mut(e, |_: Option<Mut<CompWithDefaultAndComponentData>>| {
                guard.with_component_mut(e, |_: Option<Mut<CompWithDefaultAndComponentData>>| ())
            });
        assert!(result.unwrap().is_err());
    }

    // ── with_or_insert_component_mut ─────────────────────────────────────────

    #[test]
    fn with_or_insert_inserts_when_absent_and_mutates_when_present() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let e = guard.spawn().unwrap();

        // absent: inserts default then applies mutation
        guard
            .with_or_insert_component_mut(e, |c: &mut UnitStruct| {
                let _ = c;
            })
            .unwrap();
        assert!(
            guard
                .has_component(e, comp_reg::<UnitStruct>(&guard).component_id)
                .unwrap()
        );

        // present: mutates existing value
        guard
            .with_or_insert_component_mut(e, |c: &mut UnitStruct| {
                let _ = c;
            })
            .unwrap();
    }

    // ── resource operations ───────────────────────────────────────────────────

    #[test]
    fn has_resource_and_get_resource_and_remove_resource() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let reg = res_reg::<TestResource>(&guard);

        assert!(guard.has_resource(reg.resource_id).unwrap());
        assert!(guard.get_resource(reg.resource_id).unwrap().is_some());

        guard.remove_resource(reg.clone()).unwrap();

        assert!(!guard.has_resource(reg.resource_id).unwrap());
        // this might be unexpected but the resource component ID persists for some reason
        // I guess it gets re-used if the resource is re-inserted, but
        // the reference will fail
        let ref_ = guard.get_resource(reg.resource_id).unwrap().unwrap();
        assert!(ref_.downcast::<TestResource>(guard).is_err());
    }

    // ── with_resource access-map: all four conflict cases ────────────────────

    #[test]
    fn with_resource_read_read_succeeds() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);

        let result =
            guard.with_resource(|_: &TestResource| guard.with_resource(|_: &TestResource| ()));
        assert!(result.unwrap().is_ok());
    }

    #[test]
    fn with_resource_write_read_conflicts() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);

        let result = guard
            .with_resource_mut(|_: Mut<TestResource>| guard.with_resource(|_: &TestResource| ()));
        assert!(result.unwrap().is_err());
    }

    #[test]
    fn with_resource_read_write_conflicts() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);

        let result = guard
            .with_resource(|_: &TestResource| guard.with_resource_mut(|_: Mut<TestResource>| ()));
        assert!(result.unwrap().is_err());
    }

    #[test]
    fn with_resource_write_write_conflicts() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);

        let result = guard.with_resource_mut(|_: Mut<TestResource>| {
            guard.with_resource_mut(|_: Mut<TestResource>| ())
        });
        assert!(result.unwrap().is_err());
    }

    // ── hierarchy ─────────────────────────────────────────────────────────────

    #[test]
    fn push_get_remove_children_and_get_parent() {
        let mut world = setup_world(|_, _| {});
        world.register_component::<ChildOf>();
        world.register_component::<Children>();
        let guard = make_guard(&mut world);
        let parent = guard.spawn().unwrap();
        let c1 = guard.spawn().unwrap();
        let c2 = guard.spawn().unwrap();

        assert_eq!(guard.get_parent(c1).unwrap(), None);

        guard.push_children(parent, &[c1, c2]).unwrap();

        assert_eq!(guard.get_children(parent).unwrap().len(), 2);
        assert_eq!(guard.get_parent(c1).unwrap(), Some(parent));

        guard.remove_children(parent, &[c1]).unwrap();
        assert_eq!(guard.get_children(parent).unwrap(), vec![c2]);
    }

    #[test]
    fn insert_children_at_index() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let parent = guard.spawn().unwrap();
        let c1 = guard.spawn().unwrap();
        let c2 = guard.spawn().unwrap();
        let c3 = guard.spawn().unwrap();
        guard.push_children(parent, &[c1, c3]).unwrap();
        guard.insert_children(parent, 1, &[c2]).unwrap();
        assert_eq!(guard.get_children(parent).unwrap()[1], c2);
    }

    #[test]
    fn hierarchy_ops_error_on_missing_entity() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let ghost = guard.spawn().unwrap();
        guard.despawn(ghost).unwrap();

        assert!(guard.get_parent(ghost).is_err());
        assert!(guard.get_children(ghost).is_err());
        assert!(guard.push_children(ghost, &[]).is_err());
        assert!(guard.insert_children(ghost, 0, &[]).is_err());
        assert!(guard.remove_children(ghost, &[]).is_err());
        assert!(guard.despawn_recursive(ghost).is_err());
        assert!(guard.despawn_descendants(ghost).is_err());
    }

    // ── type registry helpers ─────────────────────────────────────────────────

    #[test]
    fn get_type_by_name_known_and_unknown() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        assert!(
            guard
                .get_type_by_name("test_utils::test_data::SimpleStruct")
                .is_some()
        );
        assert!(guard.get_type_by_name("NoSuchType_XYZ").is_none());
    }

    #[test]
    fn get_type_registration_classifies_correctly() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);

        let plain = guard
            .get_type_registration(guard.get_type_by_name("usize").unwrap())
            .unwrap();
        assert!(plain.is_left());

        // component → Right(Left(_))
        let comp = guard
            .get_type_registration(
                guard
                    .get_type_by_name("test_utils::test_data::CompWithDefaultAndComponentData")
                    .unwrap(),
            )
            .unwrap();
        assert!(comp.into_right().unwrap().is_left());

        // resource → Right(Right(_))
        let res = guard
            .get_type_registration(
                guard
                    .get_type_by_name("test_utils::test_data::TestResource")
                    .unwrap(),
            )
            .unwrap();
        assert!(res.into_right().unwrap().is_right());
    }

    #[test]
    fn get_type_registration_by_name_unknown_returns_none() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        assert!(
            guard
                .get_type_registration_by_name("NoSuchType_XYZ".to_owned())
                .unwrap()
                .is_none()
        );
    }

    // ── dynamic component registration ────────────────────────────────────────

    #[test]
    fn register_script_component_and_duplicate_errors() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        guard
            .register_script_component("script.test", "MyDynComp", false)
            .unwrap();
        assert!(
            guard
                .register_script_component("script.test", "MyDynComp", false)
                .is_err()
        );
        assert!(
            guard
                .component_registry()
                .read()
                .get("script.test.MyDynComp")
                .is_some()
        );
    }

    #[test]
    fn type_namespaces_default_to_the_crate_and_can_be_overridden() {
        use crate::{AppScriptTypeCatalogue, ScriptNamespace};

        #[derive(Reflect)]
        struct DefaultNs;
        #[derive(Reflect)]
        struct OverriddenNs;

        let mut world = setup_world(|_, registry| {
            registry.register::<DefaultNs>();
            registry.register::<OverriddenNs>();
            registry.register_type_data_with::<OverriddenNs, ScriptNamespace, _>("custom");
        });
        let guard = make_guard(&mut world);
        let catalogue = AppScriptTypeCatalogue::default()
            .get(guard.clone())
            .unwrap();

        // defined in this crate's test module
        let default = catalogue.get_by_short_name("DefaultNs").unwrap();
        assert_eq!(&*default.namespace, "bevy_mod_scripting_bindings");
        let overridden = catalogue.get_by_short_name("OverriddenNs").unwrap();
        assert_eq!(&*overridden.namespace, "custom");

        assert!(catalogue.namespaces().any(|n| n == "custom"));
        let in_custom: Vec<_> = catalogue.iter_namespace("custom").collect();
        assert_eq!(in_custom.len(), 1);
        assert_eq!(&*in_custom[0].short_name, "OverriddenNs");
        assert_eq!(catalogue.iter_namespace("does_not_exist").count(), 0);
    }

    #[test]
    fn namespace_views_and_suggestions() {
        use crate::{AppScriptTypeCatalogue, ScriptNamespace};

        #[derive(Reflect)]
        struct InTransform;
        #[derive(Reflect)]
        struct InEcs;

        let mut world = setup_world(|_, registry| {
            registry.register::<InTransform>();
            registry.register::<InEcs>();
            registry.register_type_data_with::<InTransform, ScriptNamespace, _>("bevy_transform");
            registry.register_type_data_with::<InEcs, ScriptNamespace, _>("bevy_ecs");
        });
        let guard = make_guard(&mut world);
        let catalogue = AppScriptTypeCatalogue::default().get(guard).unwrap();

        let view = catalogue.namespace_view("bevy_transform").unwrap();
        assert!(view.contains_key("InTransform"));
        assert!(!view.contains_key("InEcs"));
        assert!(catalogue.namespace_view("nope").is_none());

        assert_eq!(
            catalogue.similar_namespaces("bevy_transfrom"),
            vec!["bevy_transform"]
        );
        // substrings count as similar
        assert_eq!(
            catalogue.similar_namespaces("transform"),
            vec!["bevy_transform"]
        );
        assert!(catalogue.similar_namespaces("zzzzzzzzzzzz").is_empty());
    }

    #[test]
    fn first_script_namespace_wins() {
        use crate::{ScriptNamespace, set_script_namespace_if_unset};

        #[derive(Reflect)]
        struct Contested;

        let mut world = setup_world(|_, registry| {
            registry.register::<Contested>();
            set_script_namespace_if_unset::<Contested>(registry, "first");
            set_script_namespace_if_unset::<Contested>(registry, "second");
            // the same namespace again is fine
            set_script_namespace_if_unset::<Contested>(registry, "first");
        });
        let guard = make_guard(&mut world);
        let registry = guard.type_registry();
        let registry = registry.read();
        let namespace = registry
            .get(TypeId::of::<Contested>())
            .and_then(|r| r.data::<ScriptNamespace>())
            .unwrap();
        assert_eq!(namespace.0, "first");
    }

    #[test]
    fn type_catalogue_is_shared_and_refreshes_on_new_types() {
        use crate::AppScriptTypeCatalogue;

        #[derive(Reflect)]
        struct LateType;

        let mut world = setup_world(|_, _| {});
        let registry = world
            .resource::<bevy_ecs::reflect::AppTypeRegistry>()
            .clone();
        let catalogue = AppScriptTypeCatalogue::default();
        let guard = make_guard(&mut world);

        let first = catalogue.get(guard.clone()).unwrap();
        let again = catalogue.get(guard.clone()).unwrap();
        assert!(
            Arc::ptr_eq(&first, &again),
            "unchanged world must reuse the catalogue"
        );
        assert!(first.get_by_short_name("LateType").is_none());

        registry.write().register::<LateType>();
        let refreshed = catalogue.get(guard).unwrap();
        assert!(!Arc::ptr_eq(&first, &refreshed));
        assert!(refreshed.get_by_short_name("LateType").is_some());
    }

    #[test]
    fn script_registrations_enter_catalogue_and_bump_generation_once() {
        use crate::AppScriptTypeCatalogue;

        let mut world = setup_world(|_, _| {});
        let catalogue = AppScriptTypeCatalogue::default();
        let guard = make_guard(&mut world);
        let generation = || guard.component_registry().read().generation();

        let start = generation();
        guard
            .register_script_component("script.test", "CatalogueComp", false)
            .unwrap();
        assert_eq!(generation(), start + 1);

        // returning an existing registration must not look like a change
        guard
            .register_script_component("script.test", "CatalogueComp", true)
            .unwrap();
        assert_eq!(generation(), start + 1);

        let built = catalogue.get(guard.clone()).unwrap();
        let comp = built.get_by_short_name("CatalogueComp").unwrap();
        assert_eq!(comp.namespace.as_ref(), "script.test");
    }

    #[test]
    fn script_event_observers_run_right_away_or_queue_when_context_is_busy() {
        use bevy_mod_scripting_asset::Language;

        let mut world = setup_world(|_, _| {});
        let runners = AppScriptCallbackRunners::default();
        let ran = Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
        let r = ran.clone();
        let attachment = ScriptAttachment::StaticScript(Handle::default());
        let a = attachment.clone();
        runners.register(
            Language::Lua,
            Arc::new(move |_, _, label, _| {
                r.lock().push(label.to_owned());
                // pretend the context is busy for one of the callbacks
                Ok(vec![(
                    a.clone(),
                    if label == "busy_cb" {
                        Err(InteropError::context_busy("busy".to_owned()))
                    } else {
                        Ok(ScriptValue::Unit)
                    },
                )])
            }),
        );
        world.insert_resource(runners.clone());

        let guard = make_guard(&mut world);
        let event = guard
            .register_script_event("script.test", "E", false)
            .unwrap();
        for label in ["free_cb", "busy_cb"] {
            guard
                .add_script_event_observer(event.clone(), label.into(), attachment.clone())
                .unwrap();
        }
        guard
            .trigger_script_event(event, ScriptValue::Unit)
            .unwrap();

        // both were attempted right away (in unspecified order), only the busy one was queued
        let mut attempted = ran.lock().clone();
        attempted.sort();
        assert_eq!(attempted, vec!["busy_cb", "free_cb"]);
        assert_eq!(runners.pop_queued().unwrap().label, "busy_cb");
        assert!(!runners.has_queued());
    }

    #[test]
    fn script_registrations_need_valid_script_namespaces() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);

        for bad in [
            "game",
            "bevy_transform",
            "script",
            "script.",
            "script..a",
            "script.a b",
            "",
        ] {
            for result in [
                guard.register_script_component(bad, "C", false).map(|_| ()),
                guard.register_script_event(bad, "E", false).map(|_| ()),
            ] {
                let err = result.unwrap_err().to_string();
                assert!(err.contains("script"), "{bad}: {err}");
            }
        }
        let err = guard
            .register_script_component("game", "C", false)
            .unwrap_err()
            .to_string();
        assert!(err.contains("must start with `script.`"), "{err}");

        // names cannot be empty or contain dots
        assert!(
            guard
                .register_script_component("script.a", "", false)
                .is_err()
        );
        assert!(
            guard
                .register_script_component("script.a", "x.y", false)
                .is_err()
        );
        assert!(
            guard
                .register_script_component("script.a.b_c", "X", false)
                .is_ok()
        );
    }

    #[test]
    fn script_registrations_are_unique_by_full_path() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);

        let a = guard
            .register_script_component("script.one", "Same", false)
            .unwrap();
        let b = guard
            .register_script_component("script.two", "Same", false)
            .unwrap();
        assert_ne!(
            a.component_id, b.component_id,
            "different namespaces, different components"
        );
        assert!(
            guard
                .register_script_component("script.one", "Same", false)
                .is_err()
        );

        // lookups work by full path only
        let by_path = guard
            .get_type_registration_by_name("script.two.Same".to_owned())
            .unwrap();
        assert!(by_path.is_some());
        let by_name = guard
            .get_type_registration_by_name("Same".to_owned())
            .unwrap();
        assert!(by_name.is_none());
        let registry = guard.component_registry();
        let registry = registry.read();
        assert!(registry.find("Same").is_none());
        assert_eq!(
            registry.find("script.two.Same").unwrap().namespace,
            "script.two"
        );
    }

    #[test]
    fn script_events_share_paths_with_components_and_exports() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let owner = ScriptAttachment::StaticScript(Handle::default());

        guard
            .register_script_component("script.game", "Enemy", false)
            .unwrap();
        guard
            .register_script_event("script.game", "Hit", false)
            .unwrap();
        guard
            .register_script_export("script.game", "spawn", "spawn_impl".into(), owner.clone())
            .unwrap();

        // every kind is rejected on the paths of the other kinds
        assert!(
            guard
                .register_script_event("script.game", "Enemy", false)
                .is_err()
        );
        assert!(
            guard
                .register_script_event("script.game", "spawn", false)
                .is_err()
        );
        assert!(
            guard
                .register_script_component("script.game", "Hit", false)
                .is_err()
        );
        assert!(
            guard
                .register_script_export("script.game", "Hit", "hit_impl".into(), owner)
                .is_err()
        );

        let registry = guard.component_registry();
        let registry = registry.read();
        let events = registry.iter_events_in("script.game").collect::<Vec<_>>();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].0, "Hit");
        assert!(registry.iter_events_in("script").next().is_none());
    }

    #[test]
    fn register_script_event_duplicates_need_allow_existing() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let first = guard
            .register_script_event("script.test", "Ev", false)
            .unwrap();
        let err = guard
            .register_script_event("script.test", "Ev", false)
            .unwrap_err();
        assert!(err.to_string().contains("allow_existing"), "{err}");
        let again = guard
            .register_script_event("script.test", "Ev", true)
            .unwrap();
        assert_eq!(first.name, again.name);
        // events do not take part in the type catalogue generation
        assert!(guard.trigger_script_event(first, ScriptValue::Unit).is_ok());
    }

    #[test]
    fn script_exports_are_unique_per_path_and_owned_by_one_script() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let (a, b) = (guard.spawn().unwrap(), guard.spawn().unwrap());
        let owner_a = ScriptAttachment::EntityScript(a, Handle::default());
        let owner_b = ScriptAttachment::EntityScript(b, Handle::default());

        guard
            .register_script_export("script.game", "spawn", "spawn_impl".into(), owner_a.clone())
            .unwrap();
        // the same script exporting again replaces the export
        guard
            .register_script_export("script.game", "spawn", "other_impl".into(), owner_a)
            .unwrap();
        assert_eq!(
            guard
                .component_registry()
                .read()
                .get_export("script.game.spawn")
                .unwrap()
                .label,
            "other_impl"
        );

        // another script can't take it
        let err = guard
            .register_script_export("script.game", "spawn", "x".into(), owner_b.clone())
            .unwrap_err()
            .to_string();
        assert!(err.contains("already exported by script"), "{err}");

        // namespaces are validated like for components
        assert!(
            guard
                .register_script_export("game", "spawn", "x".into(), owner_b.clone())
                .is_err()
        );

        // exports and components cannot share a path, in both directions
        assert!(
            guard
                .register_script_component("script.game", "spawn", false)
                .is_err()
        );
        guard
            .register_script_component("script.game", "Enemy", false)
            .unwrap();
        assert!(
            guard
                .register_script_export("script.game", "Enemy", "x".into(), owner_b)
                .is_err()
        );

        // calling something which is not exported fails clearly
        let err = guard
            .call_script_export("script.game.nope", vec![])
            .unwrap_err()
            .to_string();
        assert!(err.contains("does not exist"), "{err}");
    }

    #[test]
    fn unloading_a_script_removes_its_exports_and_observers_only() {
        let mut world = setup_world(|_, _| {});
        world.insert_resource(AppScriptComponentRegistry::default());
        let (a, b, observers) = {
            let guard = make_guard(&mut world);
            let (a, b) = (guard.spawn().unwrap(), guard.spawn().unwrap());
            let owner_a = ScriptAttachment::EntityScript(a, Handle::default());
            let owner_b = ScriptAttachment::EntityScript(b, Handle::default());

            guard
                .register_script_export("script.game", "one", "f".into(), owner_a.clone())
                .unwrap();
            guard
                .register_script_export("script.game", "two", "f".into(), owner_b.clone())
                .unwrap();
            let event = guard
                .register_script_event("script.game", "Ev", false)
                .unwrap();
            let observers = [
                guard
                    .add_script_event_observer(event.clone(), "f".into(), owner_a)
                    .unwrap(),
                guard
                    .add_script_event_observer(event, "f".into(), owner_b)
                    .unwrap(),
            ];
            (a, b, observers)
        };

        crate::remove_script_registrations(
            &mut world,
            &ScriptAttachment::EntityScript(a, Handle::default()),
        );

        let registry = world.resource::<AppScriptComponentRegistry>().read();
        assert!(registry.get_export("script.game.one").is_none());
        assert!(registry.get_export("script.game.two").is_some());
        drop(registry);
        assert!(
            world.get_entity(observers[0]).is_err(),
            "the observer of the unloaded script is removed"
        );
        assert!(
            world.get_entity(observers[1]).is_ok(),
            "other scripts' observers stay"
        );
        let _ = b;
    }

    #[test]
    fn register_script_component_allow_existing_returns_existing() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let first = guard
            .register_script_component("script.test", "MyDynComp", false)
            .unwrap();
        let err = guard
            .register_script_component("script.test", "MyDynComp", false)
            .unwrap_err();
        assert!(err.to_string().contains("allow_existing"), "{err}");

        let second = guard
            .register_script_component("script.test", "MyDynComp", true)
            .unwrap();
        assert_eq!(first.component_id, second.component_id);

        // a fresh name is still registered normally with the flag set
        let other = guard
            .register_script_component("script.test", "OtherDynComp", true)
            .unwrap();
        assert_ne!(first.component_id, other.component_id);
    }

    #[test]
    fn script_component_insert_moves_value_into_entity() {
        use bevy_reflect::structs::Struct;

        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let registration = guard
            .register_script_component("script.test", "MyDynComp", false)
            .unwrap();
        let entity = guard.spawn().unwrap();

        let mut component = DynamicComponent::default();
        *component
            .field_mut("data")
            .and_then(|f| f.try_downcast_mut::<ScriptValue>())
            .unwrap() = ScriptValue::String("hello".into());
        registration
            .insert_into_entity(guard.clone(), entity, Box::new(component))
            .unwrap();

        let data = guard
            .with_world_mut(|world| {
                let ptr = world.get_by_id(entity, registration.component_id).unwrap();
                // Safety: script components are always backed by `DynamicComponent`
                let component = unsafe { ptr.deref::<DynamicComponent>() };
                component
                    .field("data")
                    .and_then(|f| f.try_downcast_ref::<ScriptValue>())
                    .cloned()
            })
            .unwrap();
        assert!(matches!(data, Some(ScriptValue::String(s)) if s == "hello"));

        guard.despawn(entity).unwrap();
    }

    // ── bundles ───────────────────────────────────────────────────────────────

    fn native_bundle_reg(guard: &WorldAccessGuard<'_>) -> ScriptBundleRegistration {
        guard
            .get_bundle_type(
                guard
                    .get_type_by_name("test_utils::test_data::TestBundle")
                    .unwrap(),
            )
            .unwrap()
            .unwrap()
    }

    fn allocate<T: Reflect>(_guard: &WorldAccessGuard<'_>, value: T) -> ReflectReference {
        ReflectReference::new_allocated(value)
    }

    #[test]
    fn native_bundle_is_classified_as_bundle() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let registration = guard
            .get_type_registration(
                guard
                    .get_type_by_name("test_utils::test_data::TestBundle")
                    .unwrap(),
            )
            .unwrap();
        assert!(
            registration
                .into_right()
                .unwrap()
                .into_right()
                .unwrap()
                .is_right()
        );
    }

    #[test]
    fn native_bundle_insert_and_spawn() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let registration = native_bundle_reg(&guard);
        let simple = comp_reg::<SimpleStruct>(&guard).component_id;

        let entity = guard.spawn().unwrap();
        let value = allocate(
            &guard,
            TestBundle {
                comp: CompWithDefaultAndComponentData("bundled".to_owned()),
                nested: TestNestedBundle::default(),
            },
        );
        guard
            .insert_bundle(entity, registration.clone(), value)
            .unwrap();
        let comp = guard
            .with_component::<CompWithDefaultAndComponentData, _, _>(entity, |c| {
                c.unwrap().0.clone()
            })
            .unwrap();
        assert_eq!(comp, "bundled");
        // nested bundles are inserted too
        assert!(guard.has_component(entity, simple).unwrap());

        let value = allocate(&guard, TestBundle::default());
        let spawned = guard.spawn_bundle(registration, value).unwrap();
        assert!(guard.has_component(spawned, simple).unwrap());
    }

    #[test]
    fn native_bundle_insert_rejects_other_types() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let registration = native_bundle_reg(&guard);
        let entity = guard.spawn().unwrap();
        let value = allocate(&guard, SimpleStruct::default());
        assert!(guard.insert_bundle(entity, registration, value).is_err());
    }

    // ── query ─────────────────────────────────────────────────────────────────

    #[test]
    fn query_returns_only_matching_entities() {
        let mut world = setup_world(|_, _| {});
        let guard = make_guard(&mut world);
        let _without = guard.spawn().unwrap();
        let reg = comp_reg::<CompWithDefaultAndComponentData>(&guard);
        let mut builder = ScriptQueryBuilder::new();
        builder.with_components(vec![reg]);

        let results = guard.query(builder).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0].entity,
            CompWithDefaultAndComponentData::test_entity_id()
        );
    }

    // ── setup_cache_raw ───────────────────────────────────────────────────────

    #[test]
    fn setup_cache_raw_produces_functional_guard() {
        let mut world = setup_world(|_, _| {});
        let cache = WorldAccessGuard::setup_cache_raw(
            CurrentScriptAttachment::empty(),
            world
                .get_resource::<AppScriptFunctionRegistry>()
                .cloned()
                .unwrap_or_default(),
            world
                .get_resource::<AppScheduleRegistry>()
                .cloned()
                .unwrap_or_default(),
            world
                .get_resource::<AppScriptComponentRegistry>()
                .cloned()
                .unwrap_or_default(),
            AppScriptCallbackRunners::default(),
            AppScriptTypeCatalogue::default(),
        );
        let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
        assert!(guard.spawn().is_ok());
    }

    /// Script observers deliver their callbacks through queued commands, so every operation
    /// which can trigger observers has to flush before it returns.
    mod observer_flushing {
        use super::*;
        use bevy_ecs::{
            component::Component,
            event::Event,
            lifecycle::{AddEvent, DespawnEvent, InsertEvent, RemoveEvent},
            reflect::{ReflectComponent, ReflectEvent},
        };
        use bevy_mod_scripting_asset::Language;
        use bevy_reflect::prelude::ReflectDefault;

        #[derive(Component, Reflect, Default)]
        #[reflect(Component, Default)]
        struct ObsComp;

        #[derive(Event, Reflect, Clone)]
        #[reflect(Event)]
        struct ObsEvent;

        struct Fixture {
            world: World,
            counts: Arc<parking_lot::Mutex<std::collections::HashMap<String, usize>>>,
            runners: AppScriptCallbackRunners,
        }

        fn fixture() -> Fixture {
            let mut world = setup_world(|world, registry| {
                world.register_component::<ObsComp>();
                registry.register::<ObsComp>();
                registry.register::<ObsEvent>();
                registry.register::<AddEvent>();
                registry.register_type_data::<AddEvent, ReflectEvent>();
                registry.register::<InsertEvent>();
                registry.register_type_data::<InsertEvent, ReflectEvent>();
                registry.register::<RemoveEvent>();
                registry.register_type_data::<RemoveEvent, ReflectEvent>();
                registry.register::<DespawnEvent>();
                registry.register_type_data::<DespawnEvent, ReflectEvent>();
            });
            let runners = AppScriptCallbackRunners::default();
            let counts = Arc::new(parking_lot::Mutex::new(std::collections::HashMap::<
                String,
                usize,
            >::new()));
            let (c, attachment) = (
                counts.clone(),
                ScriptAttachment::StaticScript(Handle::default()),
            );
            runners.register(
                Language::Lua,
                Arc::new(move |_, _, label, _| {
                    *c.lock().entry(label.to_owned()).or_insert(0) += 1;
                    Ok(vec![(attachment.clone(), Ok(ScriptValue::Unit))])
                }),
            );
            world.insert_resource(runners.clone());
            Fixture {
                world,
                counts,
                runners,
            }
        }

        impl Fixture {
            fn count(&self, label: &str) -> usize {
                self.counts.lock().get(label).copied().unwrap_or(0)
            }
        }

        fn observe<T: 'static>(
            guard: &WorldGuard,
            label: &str,
            comp: &ScriptComponentRegistration,
        ) {
            let registry = guard.type_registry();
            let registration = ScriptTypeRegistration::new(Arc::new(
                registry.read().get(TypeId::of::<T>()).unwrap().clone(),
            ));
            guard
                .add_script_observer(
                    registration,
                    vec![comp.clone()],
                    vec![],
                    label.to_owned(),
                    ScriptAttachment::StaticScript(Handle::default()),
                )
                .unwrap();
        }

        #[test]
        fn operations_flush_script_observer_callbacks() {
            let mut f = fixture();
            let counts = f.counts.clone();
            let count = move |l: &str| counts.lock().get(l).copied().unwrap_or(0);
            let guard = make_guard(&mut f.world);
            let comp = comp_reg::<ObsComp>(&guard);
            observe::<AddEvent>(&guard, "add", &comp);
            observe::<InsertEvent>(&guard, "insert", &comp);
            observe::<RemoveEvent>(&guard, "remove", &comp);
            observe::<DespawnEvent>(&guard, "despawn", &comp);

            let entity = guard.spawn().unwrap();
            guard.add_default_component(entity, comp.clone()).unwrap();
            assert_eq!(count("add"), 1, "add_default_component");
            assert_eq!(count("insert"), 1, "add_default_component insert");

            guard.remove_component(entity, comp.clone()).unwrap();
            assert_eq!(count("remove"), 1, "remove_component");

            guard.add_default_component(entity, comp.clone()).unwrap();
            guard.despawn(entity).unwrap();
            assert_eq!(count("despawn"), 1, "despawn");

            let parent = guard.spawn().unwrap();
            let child = guard.spawn().unwrap();
            guard.add_default_component(child, comp.clone()).unwrap();
            guard.insert_children(parent, 0, &[child]).unwrap();
            guard.despawn_recursive(parent).unwrap();
            assert_eq!(count("despawn"), 2, "despawn_recursive");
            assert!(!f.runners.has_queued());
        }

        #[test]
        fn trigger_event_flushes_script_observer_callbacks() {
            let mut f = fixture();
            let guard = make_guard(&mut f.world);
            let registry = guard.type_registry();
            let registration = ScriptTypeRegistration::new(Arc::new(
                registry
                    .read()
                    .get(TypeId::of::<ObsEvent>())
                    .unwrap()
                    .clone(),
            ));
            guard
                .add_script_observer(
                    registration.clone(),
                    vec![],
                    vec![],
                    "event".to_owned(),
                    ScriptAttachment::StaticScript(Handle::default()),
                )
                .unwrap();
            let reference = ReflectReference::new_allocated(ObsEvent);
            guard.trigger_event(registration, &reference).unwrap();
            drop(guard);
            assert_eq!(f.count("event"), 1, "trigger_event");
        }
    }

    mod reflected_dispatch {
        use super::*;
        use bevy_ecs::{
            event::Event,
            message::{Message, MessageCursor, Messages},
            observer::On,
            reflect::{ReflectEvent, ReflectMessage},
            system::ResMut,
        };
        use bevy_mod_scripting_world::WorldGuard;

        #[derive(Event, Reflect, Clone)]
        #[reflect(Event)]
        struct TestEvent {
            value: usize,
        }

        #[derive(Message, Reflect, Clone)]
        #[reflect(Message)]
        struct TestMessage {
            value: usize,
        }

        /// A reflected type with neither `ReflectEvent` nor `ReflectMessage` data
        #[derive(Reflect)]
        struct Plain {
            value: usize,
        }

        #[derive(bevy_ecs::resource::Resource, Default)]
        struct Seen(Vec<usize>);

        fn setup() -> World {
            let mut world = setup_world(|_, registry| {
                registry.register::<TestEvent>();
                registry.register::<TestMessage>();
                registry.register::<Plain>();
            });
            world.init_resource::<Seen>();
            world.init_resource::<Messages<TestMessage>>();
            world.add_observer(|e: On<TestEvent>, mut seen: ResMut<Seen>| {
                seen.0.push(e.value);
            });
            world
        }

        fn registration<T: 'static>(guard: &WorldGuard) -> ScriptTypeRegistration {
            let registry = guard.type_registry();
            let registry = registry.read();
            ScriptTypeRegistration::new(Arc::new(registry.get(TypeId::of::<T>()).unwrap().clone()))
        }

        fn allocate<T: Reflect>(_guard: &WorldGuard, value: T) -> ReflectReference {
            ReflectReference::new_allocated(value)
        }

        #[test]
        fn trigger_event_runs_observers_before_returning() {
            let mut world = setup();
            let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
            {
                let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
                let reference = allocate(&guard, TestEvent { value: 7 });
                guard
                    .trigger_event(registration::<TestEvent>(&guard), &reference)
                    .unwrap();
                // the script's value is untouched, it can be triggered again
                guard
                    .trigger_event(registration::<TestEvent>(&guard), &reference)
                    .unwrap();
            }
            assert_eq!(world.resource::<Seen>().0, vec![7, 7]);
        }

        #[test]
        fn write_message_is_readable_by_message_readers() {
            let mut world = setup();
            let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
            {
                let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
                let reference = allocate(&guard, TestMessage { value: 3 });
                guard
                    .write_message(registration::<TestMessage>(&guard), &reference)
                    .unwrap();
            }
            let messages = world.resource::<Messages<TestMessage>>();
            let mut cursor = MessageCursor::<TestMessage>::default();
            let read: Vec<_> = cursor.read(messages).map(|m| m.value).collect();
            assert_eq!(read, vec![3]);
        }

        #[test]
        fn missing_type_data_is_an_error() {
            let mut world = setup();
            let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
            let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
            let reference = allocate(&guard, Plain { value: 1 });
            let registration = registration::<Plain>(&guard);

            assert!(matches!(
                guard.trigger_event(registration.clone(), &reference),
                Err(InteropError::MissingTypeData { .. })
            ));
            assert!(matches!(
                guard.write_message(registration, &reference),
                Err(InteropError::MissingTypeData { .. })
            ));
        }

        #[test]
        fn value_of_wrong_type_is_rejected() {
            let mut world = setup();
            let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
            let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
            let reference = allocate(&guard, TestMessage { value: 1 });

            assert!(matches!(
                guard.trigger_event(registration::<TestEvent>(&guard), &reference),
                Err(InteropError::TypeMismatch { .. })
            ));
        }

        #[test]
        fn cannot_trigger_while_other_access_is_held() {
            let mut world = setup();
            let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
            let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
            let reference = allocate(&guard, TestEvent { value: 1 });
            let registration = registration::<TestEvent>(&guard);

            let nested = guard
                .with_read_access(bevy_mod_scripting_world::WorldAccessRange::Global, || {
                    guard.trigger_event(registration.clone(), &reference)
                });
            assert!(matches!(nested, Ok(Err(_))));
            // the failed attempt must not leak any claim
            assert!(guard.trigger_event(registration, &reference).is_ok());
        }

        #[test]
        fn commands_queued_by_observers_are_applied_before_trigger_event_returns() {
            let mut world = setup();
            world.add_observer(
                |e: On<TestEvent>, mut commands: bevy_ecs::system::Commands| {
                    let value = e.value;
                    commands.queue(move |world: &mut World| {
                        world.resource_mut::<Seen>().0.push(value + 100);
                    });
                },
            );
            // like the structural operations (which flush as bevy does for them), triggering flushes,
            // so that script observers (which deliver their callbacks via commands) run before it returns
            {
                let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
                let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
                let reference = allocate(&guard, TestEvent { value: 1 });
                guard
                    .trigger_event(registration::<TestEvent>(&guard), &reference)
                    .unwrap();
            }
            assert_eq!(world.resource::<Seen>().0, vec![1, 101]);
        }

        #[test]
        fn custom_type_data_is_exposed() {
            // sanity check the bevy side of the contract these bindings rely on
            let world = setup();
            let registry = world
                .resource::<bevy_ecs::reflect::AppTypeRegistry>()
                .read();
            let reg = registry.get(TypeId::of::<TestEvent>()).unwrap();
            assert!(reg.data::<ReflectEvent>().is_some());
            assert!(reg.data::<ReflectMessage>().is_none());
        }
    }
}