cobble-lang 0.6.2

A modern, Python-like language for creating Minecraft Data Packs
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
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::TempDir;

/// Helper function to compile a Cobble source and return the generated functions
fn compile_source(source: &str) -> Result<(TempDir, PathBuf), String> {
    let temp_dir = TempDir::new().unwrap();
    let input_file = temp_dir.path().join("test.cbl");
    let output_dir = temp_dir.path().join("output");

    fs::write(&input_file, source).unwrap();

    // Use the build command
    cobble::commands::build::build(cobble::commands::build::BuildOptions {
        input: Some(input_file),
        output: Some(output_dir.clone()),
        namespace: None,
        pack_format: None,
        description: None,
        verbose: false,
        quiet: false,
        zip: false,
        validate: false,
        dry_run: false,
        commands_json: PathBuf::from("data/commands.json"),
    })?;

    Ok((temp_dir, output_dir))
}

/// Helper to read a function file
fn read_function(output_dir: &Path, function_name: &str) -> String {
    let function_path = output_dir
        .join("data/cobble/function")
        .join(format!("{}.mcfunction", function_name));
    fs::read_to_string(function_path).unwrap()
}

fn read_all_functions(output_dir: &Path) -> String {
    let function_dir = output_dir.join("data/cobble/function");
    let mut content = String::new();
    for entry in fs::read_dir(function_dir)
        .unwrap()
        .filter_map(|entry| entry.ok())
    {
        if entry.path().extension().and_then(|ext| ext.to_str()) == Some("mcfunction") {
            content.push_str(&fs::read_to_string(entry.path()).unwrap());
            content.push('\n');
        }
    }
    content
}

#[test]
fn test_boolean_comparison_assignment_sets_true_value() {
    let source = r#"
def test():
    x = 1
    flag = x == 1
    if flag:
        /say true
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("scoreboard players set flag temp 0"));
    assert!(content
        .contains("execute if score x temp matches 1 run scoreboard players set flag temp 1"));
    assert!(content.contains("execute if score flag temp matches 1.. run say true"));
}

#[test]
fn test_storage_variable_reassignment_rejected_by_type_check() {
    let source = r#"
def test():
    items = ["sword"]
    items = 3
    x = items[0]
"#;

    let error = compile_source(source).expect_err("list to integer reassignment should fail");
    assert!(error.contains("Type mismatch for variable 'items'"));
}

#[test]
fn test_raw_command_inline_comment_stripped_without_breaking_command() {
    let source = r#"
def test():
    /give @s minecraft:diamond 1 # starter item
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("give @s minecraft:diamond 1"));
    assert!(!content.contains("starter item"));
}

#[test]
fn test_snbt_map_keys_with_spaces_are_quoted() {
    let source = r#"
def test():
    storage.set("bad", {"foo bar": 1})
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("data modify storage cobble:global bad set value {\"foo bar\":1}"));
}

#[test]
fn test_match_macro_case_uses_storage_backed_helper() {
    let source = r#"
def test(player):
    x = 0
    match x:
        case 0:
            /tellraw {player} {"text":"hit"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let all_functions = read_all_functions(&output_dir);
    let test_content = read_function(&output_dir, "test");

    assert!(!all_functions.contains("run $tellraw"));
    assert!(test_content.contains("with storage cobble:global args"));
    assert!(all_functions.contains("$tellraw $(player) {\"text\":\"hit\"}"));
}

#[test]
fn test_directory_build_does_not_duplicate_module_initializers() {
    let temp_dir = TempDir::new().unwrap();
    let source_dir = temp_dir.path().join("src");
    let output_dir = temp_dir.path().join("out");
    fs::create_dir_all(&source_dir).unwrap();
    fs::write(source_dir.join("a.cbl"), "score = 1\n").unwrap();
    fs::write(source_dir.join("b.cbl"), "energy = 2\n").unwrap();

    cobble::commands::build::build(cobble::commands::build::BuildOptions {
        input: Some(source_dir),
        output: Some(output_dir.clone()),
        namespace: None,
        pack_format: None,
        description: None,
        verbose: false,
        quiet: false,
        zip: false,
        validate: false,
        dry_run: false,
        commands_json: PathBuf::from("data/commands.json"),
    })
    .unwrap();

    let init_content = read_function(&output_dir, "_cobble_init");
    assert_eq!(
        init_content
            .matches("scoreboard players set score temp 1")
            .count(),
        1
    );
    assert_eq!(
        init_content
            .matches("scoreboard players set energy temp 2")
            .count(),
        1
    );
}

#[test]
fn test_simple_assignment() {
    let source = r#"
def test():
    x = 10
    y = 20
    z = x + y
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("scoreboard players set x temp 10"));
    assert!(content.contains("scoreboard players set y temp 20"));
    assert!(content.contains("scoreboard players operation z temp = x temp"));
    assert!(content.contains("scoreboard players operation z temp += y temp"));
}

#[test]
fn test_if_statement() {
    let source = r#"
def test():
    x = 5
    if x == 5:
        /say equal
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("scoreboard players set x temp 5"));
    assert!(content.contains("execute if score x temp matches 5 run say equal"));
}

#[test]
fn test_while_loop() {
    let source = r#"
def test():
    i = 0
    while i < 5:
        /say counting
        i = i + 1
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check main function
    let main_content = read_function(&output_dir, "test");
    assert!(main_content.contains("scoreboard players set i temp 0"));
    assert!(main_content.contains("function cobble:while_temp_0"));

    // Check that while_body function exists (new behavior)
    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("while_body_"))
        .collect();

    assert!(!body_files.is_empty(), "No while_body function generated");

    let body_content = fs::read_to_string(body_files[0].path()).unwrap();
    assert!(body_content.contains("say counting"));
    assert!(body_content.contains("scoreboard players add i temp 1"));

    // Check while loop function calls body conditionally
    let while_content = read_function(&output_dir, "while_temp_0");
    assert!(while_content
        .contains("execute if score i temp matches ..4 run function cobble:while_body"));
    assert!(while_content
        .contains("execute if score i temp matches ..4 run function cobble:while_temp_0"));
}

#[test]
fn test_for_loop() {
    let source = r#"
def test():
    for i in range(3):
        /say hello
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check main function
    let main_content = read_function(&output_dir, "test");
    assert!(main_content.contains("scoreboard players set i loop_counter 0"));
    assert!(main_content.contains("function cobble:loop_temp_"));

    // Check for loop body function (contains the actual command)
    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_body_"))
        .collect();

    assert!(!body_files.is_empty(), "No loop_body function generated");

    let body_content = fs::read_to_string(body_files[0].path()).unwrap();
    assert!(body_content.contains("say hello"));

    // Check loop control function
    let loop_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_temp_"))
        .collect();

    assert!(!loop_files.is_empty(), "No loop control function generated");

    let loop_content = fs::read_to_string(loop_files[0].path()).unwrap();
    assert!(loop_content.contains("scoreboard players add i loop_counter 1"));
    assert!(loop_content
        .contains("execute if score i loop_counter matches ..2 run function cobble:loop_temp_"));
}

#[test]
fn test_function_parameters() {
    let source = r#"
def greet(player, message):
    /tellraw {player} {"text":"{message}"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "greet");

    // Parameters should be converted to macro syntax
    assert!(content.contains("$tellraw $(player)"));
    assert!(content.contains("$(message)"));
}

#[test]
fn test_nested_json_variables() {
    let source = r#"
def give_item(player, item_name):
    /give {player} minecraft:stone{display:{Name:'{"text":"{item_name}"}'}}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "give_item");

    // Both variables should be converted to macro syntax
    assert!(content.contains("$give $(player)"));
    assert!(content.contains("$(item_name)"));
}

#[test]
fn test_variable_comparison() {
    let source = r#"
def test():
    x = 10
    y = 20
    if x < y:
        /say x is less than y
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should use variable-to-variable comparison
    assert!(content.contains("execute if score x temp < y temp run say x is less than y"));
}

#[test]
fn test_literal_left_comparison() {
    let source = r#"
def test():
    value = 7
    if 5 < value:
        /say greater
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("execute if score value temp matches 6.. run say greater"));
}

#[test]
fn test_not_equal_operator() {
    let source = r#"
def test():
    x = 5
    if x != 10:
        /say not equal
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should use unless instead of if with negation
    assert!(content.contains("execute unless score x temp matches 10 run say not equal"));
}

#[test]
fn test_scoreboard_objectives() {
    let source = r#"
def test():
    x = 10
    y = 20
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that objectives are created in init function
    let init_content = read_function(&output_dir, "_cobble_init");
    assert!(init_content.contains("scoreboard objectives add temp dummy"));
}

#[test]
fn test_minecraft_command() {
    let source = r#"
def test():
    /say Hello World
    /tellraw @a {"text":"Test"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("say Hello World"));
    assert!(content.contains("tellraw @a {\"text\":\"Test\"}"));
}

#[test]
fn test_user_function_call() {
    let source = r#"
def helper():
    /say from helper

def main():
    helper()
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that main calls helper
    let main_content = read_function(&output_dir, "main");
    assert!(main_content.contains("function cobble:helper"));

    // Check that helper exists
    let helper_content = read_function(&output_dir, "helper");
    assert!(helper_content.contains("say from helper"));
}

#[test]
fn test_single_line_docstring() {
    let source = r#"
def test():
    """This is a single-line docstring"""
    /say Hello
    /say World
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Both commands should be present
    assert!(content.contains("say Hello"));
    assert!(content.contains("say World"));
}

#[test]
fn test_multi_line_docstring() {
    let source = r#"
def test():
    """This is a multi-line
    docstring that spans
    multiple lines"""
    /say After docstring
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("say After docstring"));
}

#[test]
fn test_execute_as_at() {
    let source = r#"
def test():
    as @a at @s:
        /particle minecraft:flame ~ ~ ~ 0 0 0 0 1
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("execute as @a at @s run particle minecraft:flame"));
}

#[test]
fn test_execute_asat() {
    let source = r#"
def test():
    asat @s:
        /say Hello
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(content.contains("execute as @s at @s run say Hello"));
}

#[test]
fn test_for_loop_with_arithmetic() {
    let source = r#"
def test():
    total = 0
    for i in range(5):
        total = total + i
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Find the loop body function (contains the arithmetic)
    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_body_"))
        .collect();

    assert!(!body_files.is_empty(), "No loop_body function generated");

    let body_content = fs::read_to_string(body_files[0].path()).unwrap();

    // Loop variable is now a macro parameter, but arithmetic still uses scoreboard
    // The body should have scoreboard operations with the loop variable from parameter
    assert!(body_content.contains("scoreboard players operation total temp"));
    assert!(body_content.contains("i")); // Variable i should appear somewhere
}

#[test]
fn test_global_keyword() {
    let source = r#"
def test():
    global score
    score = 10
    /say Test
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should compile without error
    assert!(content.contains("scoreboard players set score temp 10"));
    assert!(content.contains("say Test"));
}

#[test]
fn test_module_level_variable_initialization() {
    let source = r#"
score = 10
counter = 5

def test():
    /say test
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let init = read_function(&output_dir, "_cobble_init");

    // Objective MUST be created first (after gamerule)
    let lines: Vec<&str> = init.lines().collect();

    // Find first objective add command (skip gamerule line)
    let obj_idx = lines
        .iter()
        .position(|l| l.contains("scoreboard objectives add"))
        .unwrap();
    let var_idx = lines
        .iter()
        .position(|l| l.contains("scoreboard players set score"))
        .unwrap();

    assert!(
        obj_idx < var_idx,
        "Objective must be created before variable initialization"
    );
    assert!(init.contains("gamerule max_command_sequence_length"));
    assert!(init.contains("scoreboard objectives add temp dummy"));
    assert!(init.contains("scoreboard players set score temp 10"));
    assert!(init.contains("scoreboard players set counter temp 5"));
}

#[test]
fn test_macro_with_execute_block() {
    let source = r#"
def give_item(player, item):
    as {player}:
        /give @s {item}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "give_item");

    // Macro parameters should work within execute blocks
    // The $ prefix must be at the START of the entire command (Minecraft macro system rule)
    assert!(content.contains("$execute as $(player) run give @s $(item)"));
}

#[test]
fn test_complex_expressions_with_precedence() {
    let source = r#"
def test():
    a = 10
    b = 20
    c = 30
    result = a + b * c
    result2 = a * b + c
    result3 = a - b + c * a
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should handle operator precedence correctly
    assert!(content.contains("scoreboard players set a temp 10"));
    assert!(content.contains("scoreboard players set b temp 20"));
    assert!(content.contains("scoreboard players set c temp 30"));

    // Verify arithmetic operations with proper precedence
    // result = a + (b * c) due to precedence
    assert!(content.contains("scoreboard players operation result temp = a temp"));
    assert!(content.contains("scoreboard players operation"));

    // Multiple complex expressions should all compile
    assert!(content.contains("result2"));
    assert!(content.contains("result3"));
}

#[test]
fn test_string_variable_error_in_say() {
    let source = r#"
def test():
    message = "Hello"
    /say {message}
"#;

    // String variables in /say are now auto-converted to /tellraw with nbt component
    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // String is stored in data storage
    assert!(
        content.contains("data modify storage"),
        "String should be stored in data storage: {}",
        content
    );
    // say is auto-converted to tellraw with nbt component
    assert!(
        content.contains("tellraw @a"),
        "say should be auto-converted to tellraw: {}",
        content
    );
    assert!(
        content.contains("nbt") && content.contains("storage"),
        "Should use nbt storage component: {}",
        content
    );
}

#[test]
fn test_string_variable_in_tellraw_works() {
    let source = r#"
def test():
    message = "Hello"
    /tellraw @a {"text": "{message}"}
"#;

    // String variables in tellraw are converted to nbt storage components
    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // String is stored in data storage and referenced via nbt component
    assert!(
        content.contains("data modify storage"),
        "String should be stored in data storage: {}",
        content
    );
    assert!(
        content.contains("tellraw @a"),
        "Should generate tellraw command: {}",
        content
    );
    assert!(
        content.contains("nbt") && content.contains("vars.message"),
        "Should reference string via nbt storage path: {}",
        content
    );
}

#[test]
fn test_boolean_and_operator() {
    let source = r#"
def test():
    x = 5
    y = 10
    if x > 0 and y < 15:
        /say Both conditions true!
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should chain conditions with "if ... if ..."
    assert!(content.contains("execute if score x temp matches 1.. if score y temp matches ..14 run say Both conditions true!"));
}

#[test]
fn test_boolean_not_operator() {
    let source = r#"
def test():
    x = 5
    if not x == 10:
        /say Not equal to 10!
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should use "unless" for negation
    assert!(content.contains("execute unless score x temp matches 10 run say Not equal to 10!"));
}

#[test]
fn test_complex_boolean_expression() {
    let source = r#"
def test():
    a = 10
    b = 20
    c = 30
    if a > 5 and b < 25 and not c == 40:
        /say Complex condition works!
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should chain multiple conditions
    assert!(content.contains("execute if score a temp matches 6.. if score b temp matches ..24 unless score c temp matches 40 run say Complex condition works!"));
}

#[test]
fn test_nested_or_operators() {
    let source = r#"
def test():
    a = 10
    b = 20
    c = 30
    if a == 10 or b == 30 or c > 25:
        /say Triple OR works!
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Must NOT contain "OR("
    assert!(
        !content.contains("OR("),
        "Generated code contains invalid OR(...) syntax"
    );

    // Should use unique or_temp variable (not hardcoded or_result)
    assert!(content.contains("or_temp_"), "Missing or_temp variable");
    assert!(content.contains("temp 0"), "Missing or_temp initialization");

    // Should have three separate condition checks
    assert!(
        content.contains("execute if score a temp matches 10 run scoreboard players set or_temp_")
    );
    assert!(
        content.contains("execute if score b temp matches 30 run scoreboard players set or_temp_")
    );
    assert!(content
        .contains("execute if score c temp matches 26.. run scoreboard players set or_temp_"));
}

#[test]
fn test_or_with_and_combination() {
    let source = r#"
def test():
    a = 5
    b = 10
    if (a == 5 or a == 10) and b == 10:
        /say Combined works!
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Must NOT contain "OR("
    assert!(
        !content.contains("OR("),
        "Generated code contains invalid OR(...) syntax"
    );

    // Should use unique or_temp variable (not hardcoded or_result)
    assert!(content.contains("or_temp_"));
}

#[test]
fn test_elif_after_complex_if_and_or_condition() {
    let source = r#"
def test():
    score = 7
    energy = 5
    if score > 20 and not energy == 0:
        /say high
    elif score == 10 or energy == 0:
        /say threshold
    else:
        /say fallback
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(
        !content.contains("execute unless if"),
        "elif chain generated invalid execute syntax: {}",
        content
    );
    assert!(
        !content.contains("OR("),
        "elif OR condition was not lowered: {}",
        content
    );
    assert!(content.contains("if_branch_"));
    assert!(content.contains("or_temp_"));
    assert!(content.contains("say threshold"));
    assert!(content.contains("say fallback"));
}

#[test]
fn test_match_wildcard_single_statement() {
    let source = r#"
def test():
    x = 75
    match x:
        case 0 to 50:
            /say Low
        case 51 to 100:
            /say High
        case _:
            /say Other
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Wildcard must have unless conditions
    assert!(
        content.contains("unless"),
        "Wildcard case missing unless condition"
    );

    // Should have chained unless for both ranges
    assert!(
        content.contains("execute unless score match_temp_")
            && content.contains("temp matches 0..50 unless score match_temp_")
            && content.contains("temp matches 51..100 run say Other"),
        "Wildcard case not properly conditioned"
    );

    // Must NOT have bare "say Other"
    let lines: Vec<&str> = content.lines().map(|l| l.trim()).collect();
    assert!(
        !lines.contains(&"say Other"),
        "Wildcard case executed unconditionally"
    );
}

#[test]
fn test_match_wildcard_multi_statement() {
    let source = r#"
def test():
    x = 25
    match x:
        case 0 to 10:
            /say A
        case 50 to 100:
            /say B
        case _:
            /say Line1
            /say Line2
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should have single chained unless command
    assert!(
        content.contains("execute unless score match_temp_")
            && content.contains("temp matches 0..10 unless score match_temp_")
            && content.contains("temp matches 50..100 run function cobble:match_default_"),
        "Wildcard function not properly conditioned"
    );

    // Should only call the function once
    let unless_count = content.matches("execute unless").count();
    assert_eq!(
        unless_count, 1,
        "Wildcard function called multiple times (expected 1, got {})",
        unless_count
    );
}

#[test]
fn test_boolean_and_in_while_loop() {
    let source = r#"
def test():
    x = 0
    y = 0
    while x < 5 and y < 10:
        /say Loop running
        x = x + 1
        y = y + 1
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that while_body function exists (new behavior)
    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("while_body_"))
        .collect();

    assert!(!body_files.is_empty(), "No while_body function generated");

    let body_content = fs::read_to_string(body_files[0].path()).unwrap();
    assert!(body_content.contains("say Loop running"));

    // Check while loop function - should have chained conditions
    let while_content = read_function(&output_dir, "while_temp_0");
    assert!(while_content.contains("execute if score x temp matches ..4 if score y temp matches ..9 run function cobble:while_body"));
}

#[test]
fn test_raw_minecraft_in_execute_block() {
    let source = r#"
def test():
    # Execute blocks use raw Minecraft syntax, not Python expressions
    as @a if entity @s[tag=special]:
        /say Special player!
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should use raw Minecraft syntax
    assert!(content.contains("execute as @a if entity @s[tag=special] run say Special player!"));
}

#[test]
fn test_execute_or_condition_keeps_per_executor_state() {
    let source = r#"
def test():
    as @a if entity @s[tag=red] or entity @s[tag=blue]:
        /say selected
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    assert!(!content.contains("execute execute"), "{}", content);
    assert!(
        content.contains("execute as @a run scoreboard players set @s temp 0"),
        "OR flag should reset per executor: {}",
        content
    );
    assert!(
        content
            .contains("execute as @a if entity @s[tag=red] run scoreboard players set @s temp 1"),
        "OR red branch should set per executor flag: {}",
        content
    );
    assert!(
        content.contains("execute as @a if score @s temp matches 1 run say selected"),
        "body should be gated by per executor flag: {}",
        content
    );
}

#[test]
fn test_boolean_and_with_different_comparisons() {
    let source = r#"
def test():
    a = 5
    b = 15
    c = 25
    if a >= 5 and b <= 20 and c != 30:
        /say All conditions met!
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should handle >=, <=, and != correctly
    assert!(content.contains("execute if score a temp matches 5.. if score b temp matches ..20 unless score c temp matches 30 run say All conditions met!"));
}

#[test]
fn test_double_negative_not_not() {
    let source = r#"
def test():
    x = 5
    if not not x == 5:
        /say Double negative!
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Double negative should cancel out (unless unless -> if)
    assert!(content.contains("execute if score x temp matches 5 run say Double negative!"));
}

#[test]
fn test_for_loop_variable_in_tellraw() {
    let source = r#"
def test():
    for i in range(3):
        /tellraw @a {"text":"Value: {i}"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Find the loop body function (contains the tellraw)
    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_body_"))
        .collect();

    assert!(!body_files.is_empty(), "No loop_body function generated");

    let body_content = fs::read_to_string(body_files[0].path()).unwrap();

    // Loop variable is now passed as macro parameter
    // So {i} should be converted to $(i) in the macro function
    assert!(body_content.contains("$tellraw"));
    assert!(body_content.contains("$(i)"));
    // Should NOT contain literal {i}
    assert!(!body_content.contains("Value: {i}"));
}

#[test]
fn test_scoreboard_variable_in_tellraw() {
    let source = r#"
def test():
    score = 100
    /tellraw @a {"text":"Score: {score}"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should generate JSON array with score component
    assert!(content.contains("tellraw @a ["));
    assert!(content.contains("\"score\""));
    assert!(content.contains("\"name\":\"score\""));
    assert!(content.contains("\"objective\":\"temp\""));
    // Should NOT have malformed JSON with escaped quotes
    assert!(!content.contains("{\\\"text\\\""));
}

#[test]
fn test_event_listener_tick_creates_tag() {
    let source = r#"
import stdlib
from stdlib import event

def my_tick():
    /say Every tick

stdlib.addEventListener(event.TICK, my_tick)
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that tick.json was created
    let tick_tag = output_dir.join("data/minecraft/tags/function/tick.json");
    assert!(
        tick_tag.exists(),
        "tick.json must be created when addEventListener(event.TICK) is called"
    );

    let content = fs::read_to_string(tick_tag).unwrap();
    assert!(
        content.contains("cobble:my_tick"),
        "tick.json must contain the tick handler function"
    );
}

#[test]
fn test_event_listener_load_creates_tag() {
    let source = r#"
import stdlib
from stdlib import event

def my_init():
    /say Load called

stdlib.addEventListener(event.LOAD, my_init)
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that load.json was created
    let load_tag = output_dir.join("data/minecraft/tags/function/load.json");
    assert!(
        load_tag.exists(),
        "load.json must be created when addEventListener(event.LOAD) is called"
    );

    let content = fs::read_to_string(load_tag).unwrap();
    assert!(
        content.contains("cobble:my_init"),
        "load.json must contain the load handler function"
    );
}

#[test]
fn test_event_listener_both_load_and_tick() {
    let source = r#"
import stdlib
from stdlib import event

counter = 0

def init():
    /say Init called

def tick():
    counter = counter + 1

stdlib.addEventListener(event.LOAD, init)
stdlib.addEventListener(event.TICK, tick)
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that both tags were created
    let load_tag = output_dir.join("data/minecraft/tags/function/load.json");
    let tick_tag = output_dir.join("data/minecraft/tags/function/tick.json");

    assert!(load_tag.exists(), "load.json must be created");
    assert!(tick_tag.exists(), "tick.json must be created");

    let load_content = fs::read_to_string(load_tag).unwrap();
    let tick_content = fs::read_to_string(tick_tag).unwrap();

    // Init should also initialize the _cobble_init
    assert!(load_content.contains("_cobble_init") || load_content.contains("init"));
    assert!(tick_content.contains("cobble:tick"));
}

#[test]
fn test_if_modifies_condition_variable() {
    // Regression test for bug where if statements with multiple statements
    // that modify the condition variable would not execute all statements
    let source = r#"
def test():
    x = 20
    if x >= 20:
        x = 0
        /say Should execute
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should use a function, not inline
    assert!(content.contains("function cobble:if_temp"));

    // Check the if function
    let if_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("if_temp_"))
        .collect();

    assert!(!if_files.is_empty(), "No if function generated");

    let if_content = fs::read_to_string(if_files[0].path()).unwrap();
    assert!(if_content.contains("scoreboard players set x temp 0"));
    assert!(if_content.contains("say Should execute"));
}

#[test]
fn test_elif_modifies_condition_variable() {
    let source = r#"
def test():
    x = 15
    if x < 10:
        x = 0
        /say Less than 10
    elif x < 20:
        x = 100
        /say Between 10 and 20
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should use functions
    assert!(content.contains("function cobble:elif_temp"));
    assert!(content.contains("scoreboard players set elif_taken_"));
    assert!(content.contains("run scoreboard players set elif_taken_"));
    assert!(content.contains("run scoreboard players set if_branch_"));
    assert!(content.contains("execute if score elif_taken_"));
    assert!(content.contains("run function cobble:elif_temp"));

    let elif_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("elif_temp_"))
        .collect();

    assert!(!elif_files.is_empty(), "No elif function generated");

    let elif_content = fs::read_to_string(elif_files[0].path()).unwrap();
    assert!(elif_content.contains("scoreboard players set x temp 100"));
    assert!(elif_content.contains("say Between 10 and 20"));
}

#[test]
fn test_else_modifies_condition_variable() {
    let source = r#"
def test():
    x = 5
    if x > 10:
        /say Greater
    else:
        x = 100
        /say Not greater
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should use a function for else
    assert!(content.contains("function cobble:else_temp"));

    let else_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("else_temp_"))
        .collect();

    assert!(!else_files.is_empty(), "No else function generated");

    let else_content = fs::read_to_string(else_files[0].path()).unwrap();
    assert!(else_content.contains("scoreboard players set x temp 100"));
    assert!(else_content.contains("say Not greater"));
}

#[test]
fn test_while_modifies_condition_variable() {
    // Regression test for bug where while loops would evaluate condition
    // after each statement, causing issues when body modifies condition
    let source = r#"
def test():
    i = 0
    while i < 3:
        i = i + 1
        /say Iteration
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that while_body function exists
    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("while_body_"))
        .collect();

    assert!(!body_files.is_empty(), "No while_body function generated");

    let body_content = fs::read_to_string(body_files[0].path()).unwrap();
    // Body should execute unconditionally (no execute if)
    assert!(body_content.contains("scoreboard players add i temp 1"));
    assert!(body_content.contains("say Iteration"));
    assert!(!body_content.contains("execute if"));

    // Check while_temp function
    let while_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("while_temp_"))
        .collect();

    assert!(!while_files.is_empty(), "No while function generated");

    let while_content = fs::read_to_string(while_files[0].path()).unwrap();
    // Should check condition and call body
    assert!(while_content
        .contains("execute if score i temp matches ..2 run function cobble:while_body"));
    // Should recursively call itself
    assert!(while_content
        .contains("execute if score i temp matches ..2 run function cobble:while_temp"));
}

#[test]
fn test_while_recomputes_complex_condition_each_iteration() {
    let source = r#"
def test():
    x = 0
    while x + 1 < 3:
        x = x + 1
        /say tick
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let main_content = read_function(&output_dir, "test");
    assert!(
        !main_content.contains("expr_cond_temp_"),
        "complex while condition should be evaluated inside the loop function"
    );

    let while_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("while_temp_"))
        .collect();
    let while_content = fs::read_to_string(while_files[0].path()).unwrap();
    assert!(
        while_content.matches("expr_cond_temp_").count() >= 4,
        "while condition should be computed before body and before recursion: {}",
        while_content
    );
    assert!(!while_content.contains("OR("));
}

#[test]
fn test_while_lowers_or_condition_inside_loop_function() {
    let source = r#"
def test():
    x = 1
    y = 0
    while x == 1 or y == 1:
        x = 0
        /say any
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let while_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("while_temp_"))
        .collect();
    let while_content = fs::read_to_string(while_files[0].path()).unwrap();
    assert!(!while_content.contains("OR("));
    assert!(while_content.contains("scoreboard players set or_temp_"));
    assert!(while_content.contains("execute if score or_temp_"));
}

#[test]
fn test_match_snapshots_identifier_before_running_cases() {
    let source = r#"
def test():
    x = 0
    match x:
        case 0:
            x = 1
            /say zero
        case 1:
            /say one
        case _:
            /say default
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");
    assert!(
        content.contains("scoreboard players operation match_temp_"),
        "match should snapshot identifier input: {}",
        content
    );
    assert!(
        content.contains("matches 0 run") && content.contains("match_temp_"),
        "match cases should test the snapshot temp: {}",
        content
    );
    assert!(
        !content.contains("if score x temp matches 1 run say one"),
        "later cases must not observe case body mutations: {}",
        content
    );
}

#[test]
fn test_control_flow_helper_calls_preserve_macro_storage_args() {
    let source = r#"
def greet(player):
    x = 1
    if x == 1:
        /tellraw {player} {"text":"a"}
        /tellraw {player} {"text":"b"}
    while x == 1:
        /tellraw {player} {"text":"loop"}
        x = 0
    match x:
        case 0:
            /tellraw {player} {"text":"match"}
            /say done
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "greet");
    assert!(
        content.contains("function cobble:if_temp_")
            && content.contains("with storage cobble:global args"),
        "if helper macro function should be called with storage: {}",
        content
    );

    let while_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("while_temp_"))
        .collect();
    let while_content = fs::read_to_string(while_files[0].path()).unwrap();
    assert!(
        while_content.contains("function cobble:while_body_")
            && while_content.contains("with storage cobble:global args"),
        "while body macro function should be called with storage: {}",
        while_content
    );
    assert!(
        content.contains("function cobble:match_case_")
            && content.contains("with storage cobble:global args"),
        "match case macro function should be called with storage: {}",
        content
    );
}

#[test]
fn test_for_loop_body_keeps_outer_function_params() {
    let source = r#"
def repeat(player):
    for i in range(2):
        /tellraw {player} {"text":"loop {i}"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_body_"))
        .collect();
    let body_content = fs::read_to_string(body_files[0].path()).unwrap();
    assert!(body_content.contains("$(player)"), "{}", body_content);
    assert!(body_content.contains("$(i)"), "{}", body_content);
}

#[test]
fn test_tick_counter_example() {
    // Test the README example that was broken
    let source = r#"
import stdlib
from stdlib import event

counter = 0

def tick():
    global counter
    counter = counter + 1
    if counter >= 20:
        counter = 0
        /tellraw @a {"text":"One second passed"}

stdlib.addEventListener(event.TICK, tick)
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "tick");

    // Should use a function for the if block
    assert!(content.contains("function cobble:if_temp"));

    // Find and check the if function
    let if_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("if_temp_"))
        .collect();

    assert!(!if_files.is_empty(), "No if function generated");

    let if_content = fs::read_to_string(if_files[0].path()).unwrap();
    assert!(if_content.contains("scoreboard players set counter temp 0"));
    assert!(if_content.contains("tellraw @a"));
}

#[test]
fn test_const_variable() {
    let source = r#"
def test():
    const PI = 3.14159
    const RADIUS = 5
    area = PI * RADIUS * RADIUS
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Constants should be inlined at compile time
    assert!(content.contains("scoreboard players set area temp 78"));
    assert!(!content.contains("PI temp"));
}

#[test]
fn test_const_declaration() {
    let source = r#"
def test():
    const MAX_HEALTH = 100
    health = MAX_HEALTH
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Constant should be inlined at compile time
    assert!(content.contains("scoreboard players set health temp 100"));
    assert!(!content.contains("MAX_HEALTH temp"));
}

#[test]
fn test_match_literal() {
    let source = r#"
def test():
    x = 5
    match x:
        case 0:
            /say Zero
        case 5:
            /say Five
        case 10:
            /say Ten
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should have match condition for each case
    assert!(content.contains("if score"));
    assert!(content.contains("matches"));
}

#[test]
fn test_match_range() {
    let source = r#"
def test():
    score = 75
    match score:
        case 0 to 59:
            /say Fail
        case 60 to 79:
            /say Pass
        case 80 to 100:
            /say Excellent
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should have range matches
    assert!(content.contains("if score"));
    assert!(content.contains("matches"));
}

#[test]
fn test_match_wildcard() {
    let source = r#"
def test():
    value = 42
    match value:
        case 0:
            /say Zero
        case 1:
            /say One
        case _:
            /say Other
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should handle wildcard case
    assert!(content.contains("if score") || content.contains("function"));
}

#[test]
fn test_match_with_multiple_statements() {
    let source = r#"
def test():
    x = 5
    match x:
        case 5:
            /say First
            /say Second
            /say Third
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let _content = read_function(&output_dir, "test");

    // Should create a function for multi-statement case
    let match_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("match_"))
        .collect();

    // Should have generated at least one match function
    assert!(!match_files.is_empty(), "No match function generated");
}

#[test]
fn test_selector_definition() {
    let source = r#"
@Player = @a[type=player,gamemode=survival]
@Boss = @e[type=zombie,tag=boss]

def test():
    as @Player:
        /give @s diamond

    as @Boss:
        /effect give @s strength 10 2
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Selector aliases should be expanded
    assert!(content.contains("@a[type=player,gamemode=survival]"));
    assert!(content.contains("@e[type=zombie,tag=boss]"));
    assert!(!content.contains("@Player"));
    assert!(!content.contains("@Boss"));
}

#[test]
fn test_selector_in_commands() {
    let source = r#"
@AllPlayers = @a[gamemode=!spectator]

def broadcast():
    /tellraw @AllPlayers {"text":"Hello!"}
    /title @AllPlayers title {"text":"Welcome"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "broadcast");

    // Selector alias should be replaced in all commands
    assert!(content.contains("@a[gamemode=!spectator]"));
    assert!(!content.contains("@AllPlayers"));
}

#[test]
fn test_file_import() {
    use std::fs;

    // Create temp directory with multiple files
    let temp_dir = TempDir::new().unwrap();
    let utils_file = temp_dir.path().join("utils.cbl");
    let main_file = temp_dir.path().join("main.cbl");
    let output_dir = temp_dir.path().join("output");

    // Write utils.cbl
    fs::write(
        &utils_file,
        r#"
def helper():
    /say Helper function

@Admin = @a[tag=admin]
"#,
    )
    .unwrap();

    // Write main.cbl
    fs::write(
        &main_file,
        r#"
import utils

def test():
    helper()
    as @Admin:
        /say Test
"#,
    )
    .unwrap();

    // Compile
    cobble::commands::build::build(cobble::commands::build::BuildOptions {
        input: Some(main_file),
        output: Some(output_dir.clone()),
        namespace: None,
        pack_format: None,
        description: None,
        verbose: false,
        quiet: false,
        zip: false,
        validate: false,
        dry_run: false,
        commands_json: PathBuf::from("data/commands.json"),
    })
    .unwrap();

    // Check that functions from imported file exist
    let helper_content = read_function(&output_dir, "helper");
    assert!(helper_content.contains("say Helper function"));

    let test_content = read_function(&output_dir, "test");
    assert!(test_content.contains("function cobble:helper"));
    // Should NOT have "with storage" for parameterless function
    assert!(!test_content.contains("with storage"));
    assert!(test_content.contains("@a[tag=admin]"));
}

#[test]
fn test_loop_variable_in_commands() {
    let source = r#"
def test():
    for i in range(3):
        /say Count: {i}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that loop body is a macro function
    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_body_"))
        .collect();

    assert!(!body_files.is_empty(), "No loop_body function generated");

    let body_content = fs::read_to_string(body_files[0].path()).unwrap();
    // Should use macro variable syntax
    assert!(body_content.contains("$say Count: $(i)"));

    // Check loop control function stores variable to storage
    let loop_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_temp_"))
        .collect();

    assert!(!loop_files.is_empty(), "No loop control function generated");

    let loop_content = fs::read_to_string(loop_files[0].path()).unwrap();
    // After Bug 1 fix, loop_temp no longer stores - wrapper does that
    // Just verify it calls wrapper and recurses
    assert!(
        loop_content.contains("function cobble:loop_wrapper_")
            || loop_content.contains("function cobble:loop_body_")
    );

    // Check wrapper function exists (contains storage operations)
    let wrapper_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_wrapper_"))
        .collect();

    if !wrapper_files.is_empty() {
        let wrapper_content = fs::read_to_string(wrapper_files[0].path()).unwrap();
        assert!(wrapper_content.contains("execute store result storage"));
        assert!(wrapper_content.contains("function cobble:loop_body_"));
        assert!(wrapper_content.contains("with storage"));
    }
}

#[test]
fn test_loop_variable_with_step() {
    let source = r#"
def test():
    for i in range(10) by 2:
        /say Even: {i}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    let body_files: Vec<_> = fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_body_"))
        .collect();

    assert!(!body_files.is_empty());

    let body_content = fs::read_to_string(body_files[0].path()).unwrap();
    assert!(body_content.contains("$say Even: $(i)"));
}

#[test]
fn test_parameterless_function_call() {
    let source = r#"
def helper():
    /say Helper called

def main():
    helper()
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    let main_content = read_function(&output_dir, "main");
    // Should NOT have "with storage" for parameterless function
    assert!(main_content.contains("function cobble:helper"));
    assert!(!main_content.contains("with storage"));
}

#[test]
fn test_multiple_if_in_execute_block() {
    let source = r#"
def test():
    as @a at @s if entity @s[tag=one] if entity @s[tag=two] if entity @s[tag=three]:
        /say multiple conditions
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Must be all lowercase
    assert!(content.contains("execute as @a at @s if entity @s[tag=one] if entity @s[tag=two] if entity @s[tag=three] run say multiple conditions"));
    // Ensure no capitalized keywords (regression test for Display trait bug)
    assert!(
        !content.contains(" If "),
        "Found uppercase 'If' in generated command"
    );
    assert!(
        !content.contains(" Unless "),
        "Found uppercase 'Unless' in generated command"
    );
    assert!(
        !content.contains(" Entity "),
        "Found uppercase 'Entity' in generated command"
    );
}

#[test]
fn test_if_unless_combination_in_execute() {
    let source = r#"
def test():
    as @a if entity @s[tag=ready] unless entity @s[tag=done]:
        /say execute this
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // All keywords must be lowercase
    assert!(content.contains("if entity @s[tag=ready] unless entity @s[tag=done]"));
    assert!(!content.contains(" If "), "Found uppercase 'If'");
    assert!(!content.contains(" Unless "), "Found uppercase 'Unless'");
}

#[test]
fn test_complex_execute_chain() {
    let source = r#"
def test():
    as @e[type=armor_stand] at @s if entity @s[tag=marker] if entity @a[distance=..5] unless entity @s[tag=triggered]:
        /say complex chain
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Verify all lowercase
    let lines: Vec<&str> = content.lines().collect();
    for line in &lines {
        // Check that no Minecraft keywords are capitalized
        assert!(
            !line.contains(" If "),
            "Line contains capitalized 'If': {}",
            line
        );
        assert!(
            !line.contains(" Unless "),
            "Line contains capitalized 'Unless': {}",
            line
        );
        assert!(
            !line.contains(" Entity "),
            "Line contains capitalized 'Entity': {}",
            line
        );
        assert!(
            !line.contains(" As "),
            "Line contains capitalized 'As': {}",
            line
        );
        assert!(
            !line.contains(" At "),
            "Line contains capitalized 'At': {}",
            line
        );
    }
}

#[test]
fn test_power_operator_simple() {
    // Test that basic power operator works
    let source = r#"
def test():
    x = 2
    result = x ^ 3
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should have #power_base and multiplications (# prefix for internal fake players)
    assert!(content.contains("#power_base"));

    // For x^3, we need 2 multiplications (x * x * x = x * (x * x))
    let mult_count = content
        .matches("scoreboard players operation result temp *= #power_base temp")
        .count();
    assert_eq!(
        mult_count, 2,
        "Expected 2 multiplications for x^3, found {}",
        mult_count
    );
}

#[test]
fn test_asat_with_multi_entity_selector() {
    // Regression test for asat bug: should use @s not the selector
    let source = r#"
def test():
    asat @e[type=armor_stand]:
        /say Hello
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should use "at @s" not "at @e[type=armor_stand]"
    assert!(
        content.contains("execute as @e[type=armor_stand] at @s run say Hello"),
        "asat should generate 'at @s', not 'at @e[type=armor_stand]'"
    );

    // Make sure it doesn't use the wrong pattern
    assert!(
        !content.contains("at @e[type=armor_stand]"),
        "asat incorrectly generated 'at @e[type=armor_stand]' instead of 'at @s'"
    );
}

#[test]
fn test_power_operator_zero_exponent() {
    // Test that x^0 = 1
    let source = r#"
def test():
    x = 5
    result = x ^ 0
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // x^0 should set result to 1
    assert!(content.contains("scoreboard players set x temp 5"));
    assert!(
        content.contains("scoreboard players set result temp 1"),
        "x^0 should set result to 1, but command not found in: {}",
        content
    );

    // Should NOT have any multiplication operations for x^0
    assert!(
        !content.contains("power_base"),
        "x^0 should not use power_base"
    );
    assert!(
        !content.contains("*="),
        "x^0 should not have any multiplication"
    );
}

#[test]
fn test_power_operator_assignment_zero_exponent() {
    // Test that x^0 = 1 works in assignment form
    let source = r#"
def test():
    base = 10
    result = base ^ 0
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // base^0 should set result to 1
    assert!(content.contains("scoreboard players set base temp 10"));
    assert!(
        content.contains("scoreboard players set result temp 1"),
        "base^0 should set result to 1"
    );
}

// Regression test for title command action token preservation
// Bug fix: Title commands with scoreboard variables should preserve the action token
// (title/subtitle/actionbar) between selector and JSON text array
#[test]
fn test_title_command_preserves_action() {
    let source = r#"
score = 100

def show_title():
    /title @a title Score: {score}

def show_subtitle():
    /title @a subtitle Level: {score}

def show_actionbar():
    /title @a actionbar HP: {score}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    let title_content = read_function(&output_dir, "show_title");
    let subtitle_content = read_function(&output_dir, "show_subtitle");
    let actionbar_content = read_function(&output_dir, "show_actionbar");

    // Verify action token is preserved in correct position (after selector, before JSON array)
    assert!(
        title_content.contains("title @a title ["),
        "title action should be preserved: got '{}'",
        title_content
    );
    assert!(
        subtitle_content.contains("title @a subtitle ["),
        "subtitle action should be preserved: got '{}'",
        subtitle_content
    );
    assert!(
        actionbar_content.contains("title @a actionbar ["),
        "actionbar action should be preserved: got '{}'",
        actionbar_content
    );

    // Verify action is NOT part of the JSON text
    assert!(
        !title_content.contains(r#"{"text":"title Score:"#),
        "action should not be inside JSON text: got '{}'",
        title_content
    );
    assert!(
        !subtitle_content.contains(r#"{"text":"subtitle Level:"#),
        "action should not be inside JSON text: got '{}'",
        subtitle_content
    );
    assert!(
        !actionbar_content.contains(r#"{"text":"actionbar HP:"#),
        "action should not be inside JSON text: got '{}'",
        actionbar_content
    );

    // Verify scoreboard variables are still correctly converted to JSON score components
    assert!(
        title_content.contains(r#"{"score":{"name":"score","objective":"temp"}}"#),
        "scoreboard variable should be converted to JSON score component"
    );
}

#[test]
fn test_macro_title_plain_text_becomes_json_component() {
    let source = r#"
def notify(player, count, message):
    /title {player} actionbar Kit count: {count}
    /tellraw {player} Notice: {message}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "notify");

    assert!(
        content.contains(r#"$title $(player) actionbar {"text":"Kit count: $(count)"}"#),
        "title macro text should be emitted as a JSON text component: {}",
        content
    );
    assert!(
        content.contains(r#"$tellraw $(player) {"text":"Notice: $(message)"}"#),
        "tellraw macro text should be emitted as a JSON text component: {}",
        content
    );
}

// Regression test for all title command actions
#[test]
fn test_title_all_actions_with_scoreboard_vars() {
    let source = r#"
value = 42

def test():
    /title @a title Value: {value}
    /title @a subtitle Status: {value}
    /title @a actionbar Count: {value}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // All three actions should be preserved
    let lines: Vec<&str> = content.lines().collect();

    let title_line = lines
        .iter()
        .find(|l| l.contains("title @a title"))
        .expect("title command not found");
    let subtitle_line = lines
        .iter()
        .find(|l| l.contains("title @a subtitle"))
        .expect("subtitle command not found");
    let actionbar_line = lines
        .iter()
        .find(|l| l.contains("title @a actionbar"))
        .expect("actionbar command not found");

    // Verify format: title @a <action> [JSON]
    assert!(
        title_line.starts_with("title @a title ["),
        "title format incorrect: {}",
        title_line
    );
    assert!(
        subtitle_line.starts_with("title @a subtitle ["),
        "subtitle format incorrect: {}",
        subtitle_line
    );
    assert!(
        actionbar_line.starts_with("title @a actionbar ["),
        "actionbar format incorrect: {}",
        actionbar_line
    );
}

// REGRESSION TESTS FOR BUG FIXES

#[test]
fn test_boolean_literal_only() {
    // Regression test for Bug #2: Boolean literals without variables
    // should still generate __internal__ objective
    let source = r#"
def test():
    if True:
        /say true branch
    if False:
        /say false branch
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that __internal__ objective is initialized
    let init_content = read_function(&output_dir, "_cobble_init");
    assert!(init_content.contains("scoreboard objectives add __internal__ dummy"));
    assert!(init_content.contains("scoreboard players set #true_const __internal__ 1"));
    assert!(init_content.contains("scoreboard players set #false_const __internal__ 0"));

    // Check that conditions use __internal__ with exact match
    let test_content = read_function(&output_dir, "test");
    assert!(test_content.contains("score #true_const __internal__ matches 1"));
    assert!(test_content.contains("score #false_const __internal__ matches 1"));
}

#[test]
fn test_loop_variable_scope_isolation() {
    // Regression test for Bug #3: Loop variables should not pollute outer scope
    let source = r#"
def func1():
    for i in range(5):
        /say loop

def func2():
    i = 10
    /tellraw @a {"text":"i is 10"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let func2_content = read_function(&output_dir, "func2");

    // In func2, 'i' should be a regular temp variable, not loop_counter
    assert!(func2_content.contains("scoreboard players set i temp 10"));

    // It should NOT reference loop_counter
    assert!(!func2_content.contains("loop_counter"));
}

#[test]
fn test_internal_objective_only_when_needed() {
    // Test that __internal__ objective is only initialized when Boolean literals are used

    // Test 1: With Boolean literals - should have __internal__ init
    let source_with_bool = r#"
def test():
    if True:
        /say works
"#;
    let (_temp1, output1) = compile_source(source_with_bool).unwrap();
    let init1 = read_function(&output1, "_cobble_init");
    assert!(init1.contains("scoreboard objectives add __internal__ dummy"));
    assert!(init1.contains("scoreboard players set #true_const __internal__ 1"));
    assert!(init1.contains("scoreboard players set #false_const __internal__ 0"));

    // Test 2: Without Boolean literals - should NOT have __internal__ init
    let source_without_bool = r#"
def test():
    x = 10
"#;
    let (_temp2, output2) = compile_source(source_without_bool).unwrap();
    let init2 = read_function(&output2, "_cobble_init");
    assert!(!init2.contains("#true_const"));
    assert!(!init2.contains("#false_const"));
}

#[test]
fn test_for_loop_type_checking() {
    // Regression test for Bug #4: Type checking should work correctly
    // with variable types isolated between loop body and outer scope
    let source = r#"
def test():
    x = 10
    for i in range(5):
        x = i
    # x is still Integer type after loop, this should work
    x = 20
"#;

    let result = compile_source(source);

    // This should succeed - x remains Integer throughout
    assert!(result.is_ok());
}

#[test]
fn test_invalid_number_literal() {
    // Regression test for Bug #1: Invalid number literals should be rejected
    let source = r#"
def test():
    x = 1.2.3.4
"#;

    let result = compile_source(source);

    // This should fail during tokenization
    assert!(result.is_err());
}

#[test]
fn test_const_modulo_consistency() {
    // Regression test for Bug #6: const modulo should match runtime modulo
    let source = r#"
const x = -5 % 3

def test():
    y = -5 % 3
    # Both x and y should have the same value (-2)
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Both should produce the same result
    // In Rust/integer arithmetic: -5 % 3 = -2
    let test_content = read_function(&output_dir, "test");

    // y = -5 % 3 should use modulo operation
    // In integer arithmetic: -5 % 3 = -2
    assert!(test_content.contains("modulus") || test_content.contains("-2"));
}

#[test]
fn test_nested_loops_no_infinite_loop() {
    // Regression test for nested loop wrapper naming bug
    // Bug: wrapper functions had duplicate names causing infinite loops
    let source = r#"
def test():
    for i in range(2):
        for j in range(2):
            result = i + j
            /say done
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that we have TWO distinct wrapper functions, not one
    let wrapper_files: Vec<_> = std::fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_wrapper_"))
        .collect();

    assert_eq!(
        wrapper_files.len(),
        2,
        "Should have exactly 2 wrapper functions for nested loops, found {}",
        wrapper_files.len()
    );

    // Verify outer loop calls the correct (outer) wrapper
    let loop_temp_0 = read_function(&output_dir, "loop_temp_0");
    assert!(
        loop_temp_0.contains("loop_wrapper_3") || loop_temp_0.contains("loop_wrapper_"),
        "Outer loop should call a wrapper function"
    );

    // Verify inner loop calls a different wrapper
    let loop_temp_1 = read_function(&output_dir, "loop_temp_1");
    assert!(
        loop_temp_1.contains("loop_wrapper_2") || loop_temp_1.contains("loop_wrapper_"),
        "Inner loop should call a wrapper function"
    );

    // Most importantly: verify the two wrappers are DIFFERENT
    let outer_wrapper_call = loop_temp_0
        .lines()
        .find(|l| l.contains("loop_wrapper_"))
        .unwrap();
    let inner_wrapper_call = loop_temp_1
        .lines()
        .find(|l| l.contains("loop_wrapper_"))
        .unwrap();

    assert_ne!(
        outer_wrapper_call, inner_wrapper_call,
        "Outer and inner loops must call DIFFERENT wrapper functions to avoid infinite loop"
    );
}

#[test]
fn test_nested_loops_with_arithmetic() {
    // Test that nested loop variables work correctly in arithmetic expressions
    let source = r#"
def test():
    for i in range(2):
        for j in range(2):
            result = i + j
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let loop_body_1 = read_function(&output_dir, "loop_body_1");

    // Both i and j should be accessible from loop_counter
    assert!(
        loop_body_1.contains("i loop_counter"),
        "Inner loop body should access outer loop variable i from loop_counter"
    );
    assert!(
        loop_body_1.contains("j loop_counter"),
        "Inner loop body should access inner loop variable j from loop_counter"
    );

    // Should perform the addition
    assert!(
        loop_body_1.contains("result temp =") && loop_body_1.contains("+="),
        "Should perform addition: result = i + j"
    );
}

#[test]
fn test_triple_nested_loops() {
    // Test that triple nested loops work correctly
    let source = r#"
def test():
    for i in range(2):
        for j in range(2):
            for k in range(2):
                /say Triple loop works
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Should have 3 wrapper functions
    let wrapper_files: Vec<_> = std::fs::read_dir(output_dir.join("data/cobble/function"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("loop_wrapper_"))
        .collect();

    assert_eq!(
        wrapper_files.len(),
        3,
        "Should have exactly 3 wrapper functions for triple nested loops"
    );
}

// ============================================================================
// REGRESSION TESTS FOR BUG FIXES
// ============================================================================

#[test]
fn test_regression_minus_operator_context_aware() {
    // Regression test for BUG #1: Context-aware tokenization for minus operator
    // Previously: 10-5 was tokenized as [10, -5] instead of [10, -, 5]
    let source = r#"
def test():
    a = 10-5
    b = (5-3)*2
    c = -10+5
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // 10-5 should compile-time evaluate to 5
    assert!(content.contains("scoreboard players set a temp 5"));
    // (5-3)*2 should compile-time evaluate to 4
    assert!(content.contains("scoreboard players set b temp 4"));
    // -10+5 should compile-time evaluate to -5
    assert!(content.contains("scoreboard players set c temp -5"));
}

#[test]
fn test_regression_power_operator_context_aware() {
    // Regression test for BUG #1: Context-aware tokenization for power operator
    // Previously: 2^3 was incorrectly tokenized (^ treated as coordinate marker)
    let source = r#"
def test():
    a = 2^3
    b = (2+3)^2
    c = 10^2
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // 2^3 should compile-time evaluate to 8
    assert!(content.contains("scoreboard players set a temp 8"));
    // (2+3)^2 should compile-time evaluate to 25
    assert!(content.contains("scoreboard players set b temp 25"));
    // 10^2 should compile-time evaluate to 100
    assert!(content.contains("scoreboard players set c temp 100"));
}

#[test]
fn test_regression_decimal_pack_format() {
    // Regression test: Pack format validation now requires exactly 101.1 (MC Java 26.1.2)
    // Old pack formats should be rejected
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let input_file = temp_dir.path().join("test.cbl");
    let output_dir = temp_dir.path().join("output");

    fs::write(&input_file, "def test():\n    x = 1").unwrap();

    // Build with pack format 101.1 (required for MC Java 26.1.2)
    let result = cobble::commands::build::build(cobble::commands::build::BuildOptions {
        input: Some(input_file.clone()),
        output: Some(output_dir.clone()),
        namespace: None,
        pack_format: Some("101.1".to_string()),
        description: None,
        verbose: false,
        quiet: false,
        zip: false,
        validate: false,
        dry_run: false,
        commands_json: PathBuf::from("data/commands.json"),
    });

    assert!(
        result.is_ok(),
        "Pack format 101.1 should be accepted: {:?}",
        result.err()
    );

    // Check pack.mcmeta contains correct min_format/max_format array format
    let pack_meta = fs::read_to_string(output_dir.join("pack.mcmeta")).unwrap();
    assert!(
        pack_meta.contains("min_format"),
        "pack.mcmeta should use min_format for decimal pack formats"
    );
    assert!(
        pack_meta.contains("max_format"),
        "pack.mcmeta should use max_format for decimal pack formats"
    );
    assert!(
        pack_meta.contains("101"),
        "pack.mcmeta should contain major version 101"
    );

    // Old pack formats should be rejected
    let temp_dir2 = TempDir::new().unwrap();
    let input_file2 = temp_dir2.path().join("test.cbl");
    let output_dir2 = temp_dir2.path().join("output");
    fs::write(&input_file2, "def test():\n    x = 1").unwrap();

    let result2 = cobble::commands::build::build(cobble::commands::build::BuildOptions {
        input: Some(input_file2),
        output: Some(output_dir2),
        namespace: None,
        pack_format: Some("18".to_string()),
        description: None,
        verbose: false,
        quiet: false,
        zip: false,
        validate: false,
        dry_run: false,
        commands_json: PathBuf::from("data/commands.json"),
    });

    assert!(result2.is_err(), "Old pack format 18 should be rejected");

    // Same major version with the wrong minor version should also be rejected.
    let temp_dir3 = TempDir::new().unwrap();
    let input_file3 = temp_dir3.path().join("test.cbl");
    let output_dir3 = temp_dir3.path().join("output");
    fs::write(&input_file3, "def test():\n    x = 1").unwrap();

    let result3 = cobble::commands::build::build(cobble::commands::build::BuildOptions {
        input: Some(input_file3),
        output: Some(output_dir3),
        namespace: None,
        pack_format: Some("101.0".to_string()),
        description: None,
        verbose: false,
        quiet: false,
        zip: false,
        validate: false,
        dry_run: false,
        commands_json: PathBuf::from("data/commands.json"),
    });

    assert!(result3.is_err(), "Pack format 101.0 should be rejected");
}

#[test]
fn test_regression_division_by_zero_error() {
    // Regression test for BUG #3: Division by zero should error, not warn
    // Previously: Division by zero only warned, now it errors
    let source = r#"
def test():
    const divisor = 0
    result = 10 / divisor
"#;

    let result = compile_source(source);

    // Should fail with division by zero error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.contains("Division by zero"));
}

#[test]
fn test_regression_modulo_by_zero_error() {
    // Regression test for BUG #3: Modulo by zero should error, not warn
    let source = r#"
def test():
    const divisor = 0
    result = 10 % divisor
"#;

    let result = compile_source(source);

    // Should fail with modulo by zero error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.contains("Modulo by zero"));
}

#[test]
fn test_regression_power_exponent_limit() {
    // Regression test for BUG #4: Power exponent should be limited
    // Previously: base^500 generated 499 multiplication commands
    let source = r#"
def test():
    base = 2
    result = base ^ 500
"#;

    let result = compile_source(source);

    // Should fail with "Power exponent too large" error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.contains("Power exponent too large"));
    assert!(err.contains("500 > 100"));
}

#[test]
fn test_regression_power_exponent_within_limit() {
    // Verify that power exponents within the limit (<=100) still work
    let source = r#"
def test():
    base = 2
    result = base ^ 10
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should generate multiplication commands
    assert!(content.contains("power_base"));
    assert!(content.contains("*="));
}

#[test]
fn test_regression_boundary_condition_gt_max() {
    // Regression test for BUG #5: x > i32::MAX should be always false
    // Previously: Used saturating_add which caused incorrect condition
    let source = r#"
def test():
    max_val = 2147483647
    if max_val > 2147483647:
        x = 1
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should generate an always-false condition
    // Uses "matches 0 unless matches 0" pattern
    assert!(content.contains("if score max_val temp matches 0 unless score max_val temp matches 0"));
}

#[test]
fn test_regression_boundary_condition_lt_min() {
    // Regression test for BUG #5: x < i32::MIN should be always false
    let source = r#"
def test():
    min_val = -2147483648
    if min_val < -2147483648:
        x = 1
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should generate an always-false condition
    assert!(content.contains("if score min_val temp matches 0 unless score min_val temp matches 0"));
}

#[test]
fn test_regression_boundary_condition_gte_max() {
    // Regression test for BUG #5: x >= i32::MAX should work correctly
    let source = r#"
def test():
    max_val = 2147483647
    if max_val >= 2147483647:
        x = 1
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should generate correct condition (matches 2147483647..)
    assert!(content.contains("if score max_val temp matches 2147483647.."));
}

#[test]
fn test_regression_boundary_condition_lte_min() {
    // Regression test for BUG #5: x <= i32::MIN should work correctly
    let source = r#"
def test():
    min_val = -2147483648
    if min_val <= -2147483648:
        x = 1
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Should generate correct condition (matches ..-2147483648)
    assert!(content.contains("if score min_val temp matches ..-2147483648"));
}

#[test]
fn test_regression_normal_comparisons_still_work() {
    // Ensure normal comparisons (not at boundaries) still work correctly
    let source = r#"
def test():
    a = 10
    if a > 5:
        b = 1
    if a < 20:
        c = 1
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // a > 5 should be "matches 6.."
    assert!(content.contains("if score a temp matches 6.."));
    // a < 20 should be "matches ..19"
    assert!(content.contains("if score a temp matches ..19"));
}

#[test]
fn test_const_initialization_in_scoreboard() {
    // Test that const variables are compile-time only and NOT written to scoreboard
    let source = r#"
const MY_CONST = 42
const OTHER = 100

def test():
    x = MY_CONST
    match MY_CONST:
        case 42:
            /say correct
        case _:
            /say wrong
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Constants should be compile-time substituted, not initialized at runtime
    let content = read_function(&output_dir, "test");

    // x = MY_CONST should be folded to x = 42
    assert!(
        content.contains("scoreboard players set x temp 42"),
        "Const should be substituted at compile time"
    );

    // MY_CONST should NOT appear as a scoreboard variable
    assert!(
        !content.contains("scoreboard players set MY_CONST"),
        "Const should not generate runtime scoreboard set"
    );
}

#[test]
fn test_power_overflow_handling() {
    // Test that power overflow is handled (should clamp to i32::MAX)
    let source = r#"
const BIG = 50000
def test():
    result = BIG ^ 2
"#;

    let result = compile_source(source);
    assert!(result.is_ok(), "Should compile even with overflow");

    let (_temp, output_dir) = result.unwrap();
    let content = read_function(&output_dir, "test");

    // Should contain i32::MAX (2147483647) instead of overflowed value
    assert!(
        content.contains("2147483647") || content.contains("temp"),
        "Should handle overflow properly"
    );
}

#[test]
fn test_tellraw_styling_preserved() {
    // Test that tellraw styling is preserved when using variables
    let source = r#"
def test():
    score = 100
    /tellraw @a {"text":"Score: {score}","color":"gold","bold":true,"clickEvent":{"action":"run_command","value":"/say clicked"}}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Check that the output contains styled JSON components
    assert!(
        content.contains(r#""color":"gold""#) || content.contains("score"),
        "Styling should be preserved in tellraw with variables"
    );
}

#[test]
fn test_stale_tag_cleanup() {
    // This test would need to create files and rebuild to test cleanup
    // For now, we just verify the basic functionality compiles
    let source = r#"
import stdlib
from stdlib import event

def on_load():
    /say test

stdlib.addEventListener(event.LOAD, on_load)
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();

    // Check that load.json was created
    let load_tag = output_dir.join("data/minecraft/tags/function/load.json");
    assert!(load_tag.exists(), "Load tag should be created");
}

// ============================================================================
// REGRESSION TESTS FOR v0.5.17 BUG FIXES
// ============================================================================

#[test]
fn test_return_statement_error() {
    // Regression test: Return statements should now error instead of being no-op
    // Bug: Return statements were silently ignored, allowing code after return to execute
    let source = r#"
def test():
    x = 1
    /say Before return
    return x
    /say After return should not execute
"#;

    let result = compile_source(source);

    // Should fail with return not supported error
    assert!(result.is_err(), "Return statement should cause an error");
    let error = result.unwrap_err();
    assert!(
        error.contains("Return statements are not supported"),
        "Error should mention return statements are not supported"
    );
    assert!(
        error.contains("Minecraft functions cannot return early"),
        "Error should explain Minecraft limitation"
    );
}

#[test]
fn test_return_no_value_error() {
    // Test that bare return (no value) also errors
    let source = r#"
def test():
    /say Hello
    return
    /say Unreachable
"#;

    let result = compile_source(source);
    assert!(
        result.is_err(),
        "Return statement (no value) should cause an error"
    );
    let error = result.unwrap_err();
    assert!(error.contains("Return statements are not supported"));
}

#[test]
fn test_function_call_assignment_error() {
    // Regression test: Function call results cannot be assigned to variables
    // Bug: x = func() silently failed, x was never assigned
    let source = r#"
def helper():
    /say Helper called

def test():
    x = helper()
    /say Done
"#;

    let result = compile_source(source);

    // Should fail with function call assignment error
    assert!(
        result.is_err(),
        "Function call assignment should cause an error"
    );
    let error = result.unwrap_err();
    assert!(
        error.contains("Function calls in expressions are not supported"),
        "Error should mention function call issue: {}",
        error
    );
}

#[test]
fn test_attribute_assignment_error() {
    // Test that attribute access in assignments errors properly
    let source = r#"
def test():
    x = obj.field
"#;

    let result = compile_source(source);
    assert!(
        result.is_err(),
        "Attribute access assignment should cause an error"
    );
    let error = result.unwrap_err();
    assert!(
        error.contains("Attribute base must resolve to a storage path"),
        "Error should mention storage path resolution: {}",
        error
    );
}

#[test]
fn test_subscript_assignment_error() {
    // Test that subscript/array syntax is not supported (parse error)
    // Note: Subscript syntax is not yet implemented in the parser
    let source = r#"
def test():
    x = arr[0]
"#;

    let result = compile_source(source);
    assert!(result.is_err(), "Subscript syntax should cause an error");
    // Subscript is now parsed, but fails at transpile time if base is not a storage variable
    let error = result.unwrap_err();
    assert!(
        error.contains("Subscript base must resolve to a storage path"),
        "Should get storage path error for subscript on non-storage variable: {}",
        error
    );
}

#[test]
fn test_string_assignment_still_works() {
    // Regression test: String assignments should still work (used in command substitution)
    let source = r#"
def test():
    message = "Hello World"
    /tellraw @a {"text":"{message}"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // String is stored in data storage and referenced via nbt component in tellraw
    assert!(
        content.contains("data modify storage"),
        "String should be stored in data storage: {}",
        content
    );
    assert!(
        content.contains("tellraw @a"),
        "Should generate tellraw command: {}",
        content
    );
    assert!(
        content.contains("nbt") && content.contains("vars.message"),
        "Should reference string via nbt storage path: {}",
        content
    );
}

#[test]
fn test_boolean_assignment_still_works() {
    // Regression test: Boolean assignments should still work (used in command substitution)
    let source = r#"
def test():
    enabled = True
    disabled = False
    /tellraw @a {"text":"Enabled: {enabled}, Disabled: {disabled}"}
"#;

    let (_temp, output_dir) = compile_source(source).unwrap();
    let content = read_function(&output_dir, "test");

    // Booleans are stored as scoreboard values and displayed via score components
    assert!(
        content.contains("scoreboard players set enabled temp 1"),
        "Boolean true should be set to 1: {}",
        content
    );
    assert!(
        content.contains("scoreboard players set disabled temp 0"),
        "Boolean false should be set to 0: {}",
        content
    );
    // Tellraw should use score components for boolean variables
    assert!(
        content.contains("tellraw @a"),
        "Should generate tellraw command: {}",
        content
    );
    assert!(
        content.contains("score") && content.contains("enabled"),
        "Should use score component for boolean: {}",
        content
    );
}