alef-e2e 0.15.10

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

use crate::config::E2eConfig;
use crate::escape::{go_string_literal, sanitize_filename};
use crate::field_access::FieldResolver;
use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, ValidationErrorExpectation};
use alef_codegen::naming::{go_param_name, to_go_name};
use alef_core::backend::GeneratedFile;
use alef_core::config::Language;
use alef_core::config::ResolvedCrateConfig;
use alef_core::hash::{self, CommentStyle};
use anyhow::Result;
use heck::ToUpperCamelCase;
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

use super::E2eCodegen;
use super::client;

/// Go e2e code generator.
pub struct GoCodegen;

impl E2eCodegen for GoCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
    ) -> Result<Vec<GeneratedFile>> {
        let lang = self.language_name();
        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);

        let mut files = Vec::new();

        // Resolve call config with overrides (for module path and import alias).
        let call = &e2e_config.call;
        let overrides = call.overrides.get(lang);
        let configured_go_module_path = config.go.as_ref().and_then(|go| go.module.as_ref()).cloned();
        let module_path = overrides
            .and_then(|o| o.module.as_ref())
            .cloned()
            .or_else(|| configured_go_module_path.clone())
            .unwrap_or_else(|| call.module.clone());
        let import_alias = overrides
            .and_then(|o| o.alias.as_ref())
            .cloned()
            .unwrap_or_else(|| "pkg".to_string());

        // Resolve package config.
        let go_pkg = e2e_config.resolve_package("go");
        let go_module_path = go_pkg
            .as_ref()
            .and_then(|p| p.module.as_ref())
            .cloned()
            .or_else(|| configured_go_module_path.clone())
            .unwrap_or_else(|| module_path.clone());
        let replace_path = go_pkg
            .as_ref()
            .and_then(|p| p.path.as_ref())
            .cloned()
            .or_else(|| Some(format!("../../{}", config.package_dir(Language::Go))));
        let go_version = go_pkg
            .as_ref()
            .and_then(|p| p.version.as_ref())
            .cloned()
            .unwrap_or_else(|| {
                config
                    .resolved_version()
                    .map(|v| format!("v{v}"))
                    .unwrap_or_else(|| "v0.0.0".to_string())
            });
        let field_resolver = FieldResolver::new(
            &e2e_config.fields,
            &e2e_config.fields_optional,
            &e2e_config.result_fields,
            &e2e_config.fields_array,
            &std::collections::HashSet::new(),
        );

        // Generate go.mod. In registry mode, omit the `replace` directive so the
        // module is fetched from the Go module proxy.
        let effective_replace = match e2e_config.dep_mode {
            crate::config::DependencyMode::Registry => None,
            crate::config::DependencyMode::Local => replace_path.as_deref().map(String::from),
        };
        // In local mode with a `replace` directive the version in `require` is a
        // placeholder.  Go requires that for a major-version module path (`/vN`, N ≥ 2)
        // the placeholder version must start with `vN.`, e.g. `v3.0.0`.  A version like
        // `v0.0.0` is rejected with "should be v3, not v0".  Fix the placeholder when the
        // module path ends with `/vN` and the configured version doesn't match.
        let effective_go_version = if effective_replace.is_some() {
            fix_go_major_version(&go_module_path, &go_version)
        } else {
            go_version.clone()
        };
        files.push(GeneratedFile {
            path: output_base.join("go.mod"),
            content: render_go_mod(&go_module_path, effective_replace.as_deref(), &effective_go_version),
            generated_header: false,
        });

        // Determine if any fixture needs jsonString helper across all groups.
        let emits_executable_test =
            |fixture: &Fixture| fixture.is_http_test() || fixture_has_go_callable(fixture, e2e_config);
        let needs_json_stringify = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
            emits_executable_test(f)
                && f.assertions.iter().any(|a| {
                    matches!(
                        a.assertion_type.as_str(),
                        "contains" | "contains_all" | "contains_any" | "not_contains"
                    ) && {
                        if a.field.as_ref().is_none_or(|f| f.is_empty()) {
                            e2e_config.resolve_call(f.call.as_deref()).result_is_array
                        } else {
                            let resolved_name = field_resolver.resolve(a.field.as_deref().unwrap_or(""));
                            field_resolver.is_array(resolved_name)
                        }
                    }
                })
        });

        // Generate helpers_test.go with jsonString if needed, emitted exactly once.
        if needs_json_stringify {
            files.push(GeneratedFile {
                path: output_base.join("helpers_test.go"),
                content: render_helpers_test_go(),
                generated_header: true,
            });
        }

        // Generate main_test.go with TestMain when:
        // 1. Any fixture needs the mock server (has mock_response), or
        // 2. Any fixture is client_factory-based (reads MOCK_SERVER_URL), or
        // 3. Any fixture is file-based (requires test_documents directory setup).
        //
        // TestMain runs before all tests and changes to the test_documents directory,
        // ensuring that relative file paths like "pdf/fake_memo.pdf" resolve correctly.
        let has_file_fixtures = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .any(|f| f.http.is_none() && !f.needs_mock_server());

        let needs_main_test = has_file_fixtures
            || groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
                if f.needs_mock_server() {
                    return true;
                }
                let cc = e2e_config.resolve_call(f.call.as_deref());
                let go_override = cc.overrides.get("go").or_else(|| e2e_config.call.overrides.get("go"));
                go_override.and_then(|o| o.client_factory.as_deref()).is_some()
            });

        if needs_main_test {
            files.push(GeneratedFile {
                path: output_base.join("main_test.go"),
                content: render_main_test_go(),
                generated_header: true,
            });
        }

        // Generate test files per category.
        for group in groups {
            let active: Vec<&Fixture> = group
                .fixtures
                .iter()
                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
                .collect();

            if active.is_empty() {
                continue;
            }

            let filename = format!("{}_test.go", sanitize_filename(&group.category));
            let content = render_test_file(
                &group.category,
                &active,
                &module_path,
                &import_alias,
                &field_resolver,
                e2e_config,
            );
            files.push(GeneratedFile {
                path: output_base.join(filename),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

    fn language_name(&self) -> &'static str {
        "go"
    }
}

/// Fix a Go module version so it is valid for a major-version module path.
///
/// Go requires that a module path ending in `/vN` (N ≥ 2) uses a version
/// whose major component matches N.  In local-replace mode we use a synthetic
/// placeholder version; if that placeholder (e.g. `v0.0.0`) doesn't match the
/// major suffix, fix it to `vN.0.0` so `go mod` accepts the go.mod.
fn fix_go_major_version(module_path: &str, version: &str) -> String {
    // Extract `/vN` suffix from the module path (N must be ≥ 2).
    let major = module_path
        .rsplit('/')
        .next()
        .and_then(|seg| seg.strip_prefix('v'))
        .and_then(|n| n.parse::<u64>().ok())
        .filter(|&n| n >= 2);

    let Some(n) = major else {
        return version.to_string();
    };

    // If the version already starts with `vN.`, it is valid — leave it alone.
    let expected_prefix = format!("v{n}.");
    if version.starts_with(&expected_prefix) {
        return version.to_string();
    }

    format!("v{n}.0.0")
}

fn render_go_mod(go_module_path: &str, replace_path: Option<&str>, version: &str) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "module e2e_go");
    let _ = writeln!(out);
    let _ = writeln!(out, "go 1.26");
    let _ = writeln!(out);
    let _ = writeln!(out, "require (");
    let _ = writeln!(out, "\t{go_module_path} {version}");
    let _ = writeln!(out, "\tgithub.com/stretchr/testify v1.11.1");
    let _ = writeln!(out, ")");

    if let Some(path) = replace_path {
        let _ = writeln!(out);
        let _ = writeln!(out, "replace {go_module_path} => {path}");
    }

    out
}

/// Generate `main_test.go` that starts the mock HTTP server before all tests run.
///
/// The binary is expected at `../rust/target/release/mock-server` relative to the Go e2e
/// directory.  The server prints `MOCK_SERVER_URL=http://...` on stdout; we read that line
/// and export the variable so all test files can call `os.Getenv("MOCK_SERVER_URL")`.
fn render_main_test_go() -> String {
    // NOTE: the generated-file header is injected by the caller (generated_header: true).
    let mut out = String::new();
    let _ = writeln!(out, "package e2e_test");
    let _ = writeln!(out);
    let _ = writeln!(out, "import (");
    let _ = writeln!(out, "\t\"bufio\"");
    let _ = writeln!(out, "\t\"io\"");
    let _ = writeln!(out, "\t\"os\"");
    let _ = writeln!(out, "\t\"os/exec\"");
    let _ = writeln!(out, "\t\"path/filepath\"");
    let _ = writeln!(out, "\t\"runtime\"");
    let _ = writeln!(out, "\t\"strings\"");
    let _ = writeln!(out, "\t\"testing\"");
    let _ = writeln!(out, ")");
    let _ = writeln!(out);
    let _ = writeln!(out, "func TestMain(m *testing.M) {{");
    let _ = writeln!(out, "\t_, filename, _, _ := runtime.Caller(0)");
    let _ = writeln!(out, "\tdir := filepath.Dir(filename)");
    let _ = writeln!(out);
    let _ = writeln!(
        out,
        "\t// Change to the test_documents directory so that fixture file paths like"
    );
    let _ = writeln!(
        out,
        "\t// \"pdf/fake_memo.pdf\" resolve correctly when running go test from e2e/go/."
    );
    let _ = writeln!(
        out,
        "\ttestDocumentsDir := filepath.Join(dir, \"..\", \"..\", \"test_documents\")"
    );
    let _ = writeln!(out, "\tif err := os.Chdir(testDocumentsDir); err != nil {{");
    let _ = writeln!(out, "\t\tpanic(err)");
    let _ = writeln!(out, "\t}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "\t// Start the mock HTTP server if it exists.");
    let _ = writeln!(
        out,
        "\tmockServerBin := filepath.Join(dir, \"..\", \"rust\", \"target\", \"release\", \"mock-server\")"
    );
    let _ = writeln!(out, "\tif _, err := os.Stat(mockServerBin); err == nil {{");
    let _ = writeln!(
        out,
        "\t\tfixturesDir := filepath.Join(dir, \"..\", \"..\", \"fixtures\")"
    );
    let _ = writeln!(out, "\t\tcmd := exec.Command(mockServerBin, fixturesDir)");
    let _ = writeln!(out, "\t\tcmd.Stderr = os.Stderr");
    let _ = writeln!(out, "\t\tstdout, err := cmd.StdoutPipe()");
    let _ = writeln!(out, "\t\tif err != nil {{");
    let _ = writeln!(out, "\t\t\tpanic(err)");
    let _ = writeln!(out, "\t\t}}");
    let _ = writeln!(out, "\t\t// Keep a writable pipe to the mock-server's stdin so the");
    let _ = writeln!(
        out,
        "\t\t// server does not see EOF and exit immediately. The mock-server"
    );
    let _ = writeln!(out, "\t\t// blocks reading stdin until the parent closes the pipe.");
    let _ = writeln!(out, "\t\tstdin, err := cmd.StdinPipe()");
    let _ = writeln!(out, "\t\tif err != nil {{");
    let _ = writeln!(out, "\t\t\tpanic(err)");
    let _ = writeln!(out, "\t\t}}");
    let _ = writeln!(out, "\t\tif err := cmd.Start(); err != nil {{");
    let _ = writeln!(out, "\t\t\tpanic(err)");
    let _ = writeln!(out, "\t\t}}");
    let _ = writeln!(out, "\t\tscanner := bufio.NewScanner(stdout)");
    let _ = writeln!(out, "\t\tfor scanner.Scan() {{");
    let _ = writeln!(out, "\t\t\tline := scanner.Text()");
    let _ = writeln!(out, "\t\t\tif strings.HasPrefix(line, \"MOCK_SERVER_URL=\") {{");
    let _ = writeln!(
        out,
        "\t\t\t\t_ = os.Setenv(\"MOCK_SERVER_URL\", strings.TrimPrefix(line, \"MOCK_SERVER_URL=\"))"
    );
    let _ = writeln!(out, "\t\t\t\tbreak");
    let _ = writeln!(out, "\t\t\t}}");
    let _ = writeln!(out, "\t\t}}");
    let _ = writeln!(out, "\t\tgo func() {{ _, _ = io.Copy(io.Discard, stdout) }}()");
    let _ = writeln!(out, "\t\tcode := m.Run()");
    let _ = writeln!(out, "\t\t_ = stdin.Close()");
    let _ = writeln!(out, "\t\t_ = cmd.Process.Signal(os.Interrupt)");
    let _ = writeln!(out, "\t\t_ = cmd.Wait()");
    let _ = writeln!(out, "\t\tos.Exit(code)");
    let _ = writeln!(out, "\t}} else {{");
    let _ = writeln!(out, "\t\tcode := m.Run()");
    let _ = writeln!(out, "\t\tos.Exit(code)");
    let _ = writeln!(out, "\t}}");
    let _ = writeln!(out, "}}");
    out
}

/// Generate `helpers_test.go` with the jsonString helper function.
/// This is emitted once per package to avoid duplicate function definitions.
fn render_helpers_test_go() -> String {
    let mut out = String::new();
    let _ = writeln!(out, "package e2e_test");
    let _ = writeln!(out);
    let _ = writeln!(out, "import \"encoding/json\"");
    let _ = writeln!(out);
    let _ = writeln!(out, "// jsonString converts a value to its JSON string representation.");
    let _ = writeln!(
        out,
        "// Array fields use jsonString instead of fmt.Sprint to preserve structure."
    );
    let _ = writeln!(out, "func jsonString(value any) string {{");
    let _ = writeln!(out, "\tencoded, err := json.Marshal(value)");
    let _ = writeln!(out, "\tif err != nil {{");
    let _ = writeln!(out, "\t\treturn \"\"");
    let _ = writeln!(out, "\t}}");
    let _ = writeln!(out, "\treturn string(encoded)");
    let _ = writeln!(out, "}}");
    out
}

fn render_test_file(
    category: &str,
    fixtures: &[&Fixture],
    go_module_path: &str,
    import_alias: &str,
    field_resolver: &FieldResolver,
    e2e_config: &crate::config::E2eConfig,
) -> String {
    let mut out = String::new();
    let emits_executable_test =
        |fixture: &Fixture| fixture.is_http_test() || fixture_has_go_callable(fixture, e2e_config);

    // Go convention: generated file marker must appear before the package declaration.
    out.push_str(&hash::header(CommentStyle::DoubleSlash));
    let _ = writeln!(out);

    // Determine if any fixture actually uses the pkg import.
    // Fixtures without mock_response are emitted as t.Skip() stubs and don't reference the
    // package — omit the import when no fixture needs it to avoid the Go "imported and not
    // used" compile error. Visitor fixtures reference the package types (NodeContext,
    // VisitResult, VisitResult* helpers) in struct method signatures emitted at file scope,
    // so they also require the import even when the test body itself is a Skip stub.
    // Direct-callable fixtures (non-HTTP, non-mock, with a resolved Go function) also
    // reference the package when a Go override function is configured.
    let needs_pkg = fixtures
        .iter()
        .any(|f| fixture_has_go_callable(f, e2e_config) || f.is_http_test() || f.visitor.is_some());

    // Determine if we need the "os" import (mock_url args, HTTP fixtures, or
    // client_factory fixtures that read MOCK_SERVER_URL via os.Getenv).
    let needs_os = fixtures.iter().any(|f| {
        if f.is_http_test() {
            return true;
        }
        if !emits_executable_test(f) {
            return false;
        }
        let call_config = e2e_config.resolve_call(f.call.as_deref());
        let go_override = call_config
            .overrides
            .get("go")
            .or_else(|| e2e_config.call.overrides.get("go"));
        if go_override.and_then(|o| o.client_factory.as_deref()).is_some() {
            return true;
        }
        let call_args = &call_config.args;
        // Need "os" for mock_url args, or for bytes args with a string fixture value
        // (fixture-relative path loaded via os.ReadFile at test-run time).
        if call_args.iter().any(|a| a.arg_type == "mock_url") {
            return true;
        }
        call_args.iter().any(|a| {
            if a.arg_type != "bytes" {
                return false;
            }
            // alef.toml field paths are dotted (e.g. "input.data"). The fixture's `input`
            // field already strips the "input." prefix, so we walk the remaining segments.
            let mut current = &f.input;
            let path = a.field.strip_prefix("input.").unwrap_or(&a.field);
            for segment in path.split('.') {
                match current.get(segment) {
                    Some(next) => current = next,
                    None => return false,
                }
            }
            current.is_string()
        })
    });

    // Note: file_path args are passed directly as relative strings — the e2e/go
    // TestMain in main_test.go already chdir's into the repo-root test_documents/.
    let needs_filepath = false;

    let _needs_json_stringify = fixtures.iter().any(|f| {
        emits_executable_test(f)
            && f.assertions.iter().any(|a| {
                matches!(
                    a.assertion_type.as_str(),
                    "contains" | "contains_all" | "contains_any" | "not_contains"
                ) && {
                    // Check if this assertion operates on an array field.
                    // If no field is specified, check if the result itself is an array.
                    if a.field.as_ref().is_none_or(|f| f.is_empty()) {
                        // No field specified: check if result is an array
                        e2e_config.resolve_call(f.call.as_deref()).result_is_array
                    } else {
                        // Field specified: check if that field is an array
                        let resolved_name = field_resolver.resolve(a.field.as_deref().unwrap_or(""));
                        field_resolver.is_array(resolved_name)
                    }
                }
            })
    });

    // Determine if we need "encoding/json" (handle args with non-null config,
    // json_object args that will be unmarshalled into a typed struct, or HTTP
    // body/partial/validation-error assertions that use json.Unmarshal).
    let needs_json = fixtures.iter().any(|f| {
        // HTTP body assertions use json.Unmarshal for Object/Array bodies;
        // partial body and validation-error assertions always use json.Unmarshal.
        if let Some(http) = &f.http {
            let body_needs_json = http
                .expected_response
                .body
                .as_ref()
                .is_some_and(|b| matches!(b, serde_json::Value::Object(_) | serde_json::Value::Array(_)));
            let partial_needs_json = http.expected_response.body_partial.is_some();
            let ve_needs_json = http
                .expected_response
                .validation_errors
                .as_ref()
                .is_some_and(|v| !v.is_empty());
            if body_needs_json || partial_needs_json || ve_needs_json {
                return true;
            }
        }
        if !emits_executable_test(f) {
            return false;
        }

        let call = e2e_config.resolve_call(f.call.as_deref());
        let call_args = &call.args;
        // handle args with non-null config value
        let has_handle = call_args.iter().any(|a| a.arg_type == "handle") && {
            call_args.iter().filter(|a| a.arg_type == "handle").any(|a| {
                let field = a.field.strip_prefix("input.").unwrap_or(&a.field);
                let v = f.input.get(field).unwrap_or(&serde_json::Value::Null);
                !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
            })
        };
        // json_object args with options_type or array values (will use JSON unmarshal)
        let go_override = call.overrides.get("go");
        let opts_type = go_override.and_then(|o| o.options_type.as_deref()).or_else(|| {
            e2e_config
                .call
                .overrides
                .get("go")
                .and_then(|o| o.options_type.as_deref())
        });
        let has_json_obj = call_args.iter().any(|a| {
            if a.arg_type != "json_object" {
                return false;
            }
            let v = if a.field == "input" {
                &f.input
            } else {
                let field = a.field.strip_prefix("input.").unwrap_or(&a.field);
                f.input.get(field).unwrap_or(&serde_json::Value::Null)
            };
            if v.is_array() {
                return true;
            } // array → []string unmarshal
            opts_type.is_some() && v.is_object() && !v.as_object().is_some_and(|o| o.is_empty())
        });
        has_handle || has_json_obj
    });

    // No runtime base64 calls remain in generated Go code. Bytes args with string values
    // are now loaded via os.ReadFile (see needs_os) and HTTP body byte arrays are
    // base64-encoded at codegen time and embedded as literal strings in the json.Unmarshal
    // call, which doesn't require the `encoding/base64` import in the test file.
    let needs_base64 = false;

    // Determine if we need the "fmt" import (CustomTemplate visitor actions
    // with placeholders or string assertions rendered through fmt.Sprint).
    // Note: jsonString is now in helpers_test.go (uses encoding/json, not fmt),
    // so individual test files do NOT need fmt just for calling jsonString.
    let needs_fmt = fixtures.iter().any(|f| {
        f.visitor.as_ref().is_some_and(|v| {
            v.callbacks.values().any(|action| {
                if let CallbackAction::CustomTemplate { template } = action {
                    template.contains('{')
                } else {
                    false
                }
            })
        }) || (emits_executable_test(f)
            && f.assertions.iter().any(|a| {
                matches!(
                    a.assertion_type.as_str(),
                    "contains" | "contains_all" | "contains_any" | "not_contains"
                ) && {
                    // Check if this assertion uses fmt.Sprint (non-array fields).
                    // Array fields use jsonString instead, which also needs fmt.
                    // Also verify the field is valid for the result type — assertions
                    // on invalid fields are skipped without emitting any fmt.Sprint call.
                    if a.field.as_ref().is_none_or(|f| f.is_empty()) {
                        // No field: fmt.Sprint only if result is not an array
                        !e2e_config.resolve_call(f.call.as_deref()).result_is_array
                    } else {
                        // Field specified: fmt.Sprint only if that field is not an array
                        // and the field is actually valid for the result type (otherwise
                        // the assertion is skipped and fmt.Sprint is never emitted).
                        let field = a.field.as_deref().unwrap_or("");
                        let resolved_name = field_resolver.resolve(field);
                        !field_resolver.is_array(resolved_name) && field_resolver.is_valid_for_result(field)
                    }
                }
            }))
    });

    // Determine if we need the "strings" import.
    // Only count assertions whose fields are actually valid for the result type.
    let needs_strings = fixtures.iter().any(|f| {
        if !emits_executable_test(f) {
            return false;
        }
        f.assertions.iter().any(|a| {
            let type_needs_strings = if a.assertion_type == "equals" {
                // equals with string values needs strings.TrimSpace
                a.value.as_ref().is_some_and(|v| v.is_string())
            } else {
                matches!(
                    a.assertion_type.as_str(),
                    "contains" | "contains_all" | "contains_any" | "not_contains" | "starts_with" | "ends_with"
                )
            };
            let field_valid = a
                .field
                .as_ref()
                .map(|f| f.is_empty() || field_resolver.is_valid_for_result(f))
                .unwrap_or(true);
            type_needs_strings && field_valid
        })
    });

    // Determine if we need the testify assert import.
    let needs_assert = fixtures.iter().any(|f| {
        if !emits_executable_test(f) {
            return false;
        }
        f.assertions.iter().any(|a| {
            let field_valid = a
                .field
                .as_ref()
                .map(|f| f.is_empty() || field_resolver.is_valid_for_result(f))
                .unwrap_or(true);
            let synthetic_field_needs_assert = match a.field.as_deref() {
                Some("chunks_have_content" | "chunks_have_embeddings") => {
                    matches!(a.assertion_type.as_str(), "is_true" | "is_false")
                }
                Some("embeddings") => {
                    matches!(
                        a.assertion_type.as_str(),
                        "count_equals" | "count_min" | "not_empty" | "is_empty"
                    )
                }
                _ => false,
            };
            let type_needs_assert = matches!(
                a.assertion_type.as_str(),
                "count_equals"
                    | "count_min"
                    | "count_max"
                    | "is_true"
                    | "is_false"
                    | "method_result"
                    | "min_length"
                    | "max_length"
                    | "matches_regex"
            );
            synthetic_field_needs_assert || type_needs_assert && field_valid
        })
    });

    // Determine if we need "net/http" and "io" (HTTP server tests via HTTP client).
    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
    let needs_http = has_http_fixtures;
    // io.ReadAll is emitted for every HTTP fixture (render_call always reads the body).
    let needs_io = has_http_fixtures;

    // Determine if we need "reflect" (for HTTP response body JSON comparison
    // and partial-body assertions, both of which use reflect.DeepEqual).
    let needs_reflect = fixtures.iter().any(|f| {
        if let Some(http) = &f.http {
            let body_needs_reflect = http
                .expected_response
                .body
                .as_ref()
                .is_some_and(|b| matches!(b, serde_json::Value::Object(_) | serde_json::Value::Array(_)));
            let partial_needs_reflect = http.expected_response.body_partial.is_some();
            body_needs_reflect || partial_needs_reflect
        } else {
            false
        }
    });

    let _ = writeln!(out, "// E2e tests for category: {category}");
    let _ = writeln!(out, "package e2e_test");
    let _ = writeln!(out);
    let _ = writeln!(out, "import (");
    if needs_base64 {
        let _ = writeln!(out, "\t\"encoding/base64\"");
    }
    if needs_json || needs_reflect {
        let _ = writeln!(out, "\t\"encoding/json\"");
    }
    if needs_fmt {
        let _ = writeln!(out, "\t\"fmt\"");
    }
    if needs_io {
        let _ = writeln!(out, "\t\"io\"");
    }
    if needs_http {
        let _ = writeln!(out, "\t\"net/http\"");
    }
    if needs_os {
        let _ = writeln!(out, "\t\"os\"");
    }
    let _ = needs_filepath; // reserved for future use; currently always false
    if needs_reflect {
        let _ = writeln!(out, "\t\"reflect\"");
    }
    if needs_strings {
        let _ = writeln!(out, "\t\"strings\"");
    }
    let _ = writeln!(out, "\t\"testing\"");
    if needs_assert {
        let _ = writeln!(out);
        let _ = writeln!(out, "\t\"github.com/stretchr/testify/assert\"");
    }
    if needs_pkg {
        let _ = writeln!(out);
        let _ = writeln!(out, "\t{import_alias} \"{go_module_path}\"");
    }
    let _ = writeln!(out, ")");
    let _ = writeln!(out);

    // Emit package-level visitor structs (must be outside any function in Go).
    for fixture in fixtures.iter() {
        if let Some(visitor_spec) = &fixture.visitor {
            let struct_name = visitor_struct_name(&fixture.id);
            emit_go_visitor_struct(&mut out, &struct_name, visitor_spec, import_alias);
            let _ = writeln!(out);
        }
    }

    for (i, fixture) in fixtures.iter().enumerate() {
        render_test_function(&mut out, fixture, import_alias, field_resolver, e2e_config);
        if i + 1 < fixtures.len() {
            let _ = writeln!(out);
        }
    }

    // Clean up trailing newlines.
    while out.ends_with("\n\n") {
        out.pop();
    }
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

/// Return `true` when a non-HTTP fixture can be exercised by calling the Go
/// binding directly.
///
/// A fixture is Go-callable when the resolved call config provides a non-empty
/// function name — either via a Go-specific override (`[e2e.call.overrides.go]
/// function`) or via the base call `function` field.  The Go binding exposes all
/// public functions from the Rust core as PascalCase exports, so any non-empty
/// function name can be resolved to a valid Go symbol via `to_go_name`.
fn fixture_has_go_callable(fixture: &Fixture, e2e_config: &crate::config::E2eConfig) -> bool {
    // HTTP fixtures are handled by render_http_test_function — not our concern here.
    if fixture.is_http_test() {
        return false;
    }
    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
    // Honor per-call `skip_languages`: when the resolved call's `skip_languages`
    // contains `"go"`, the Go binding doesn't expose this function.
    if call_config.skip_languages.iter().any(|l| l == "go") {
        return false;
    }
    let go_override = call_config
        .overrides
        .get("go")
        .or_else(|| e2e_config.call.overrides.get("go"));
    // When a client_factory is configured, the fixture is callable via the
    // client-method pattern even when the base function name is empty.
    if go_override.and_then(|o| o.client_factory.as_deref()).is_some() {
        return true;
    }
    // Prefer a Go-specific override function name; fall back to the base function name.
    // Any non-empty function name is callable: the Go binding exports all public
    // Rust functions as PascalCase symbols (snake_case → PascalCase via to_go_name).
    let fn_name = go_override
        .and_then(|o| o.function.as_deref())
        .filter(|s| !s.is_empty())
        .unwrap_or(call_config.function.as_str());
    !fn_name.is_empty()
}

fn render_test_function(
    out: &mut String,
    fixture: &Fixture,
    import_alias: &str,
    field_resolver: &FieldResolver,
    e2e_config: &crate::config::E2eConfig,
) {
    let fn_name = fixture.id.to_upper_camel_case();
    let description = &fixture.description;

    // Delegate HTTP fixtures to the shared driver via GoTestClientRenderer.
    if fixture.http.is_some() {
        render_http_test_function(out, fixture);
        return;
    }

    // Non-HTTP fixtures are tested directly when the call config provides a
    // callable Go function.  Emit a t.Skip() stub when:
    //   - No mock response and no callable (non-HTTP, non-mock, unreachable), or
    //   - The call's skip_languages includes "go" (e.g. streaming not supported).
    if !fixture_has_go_callable(fixture, e2e_config) {
        let _ = writeln!(out, "func Test_{fn_name}(t *testing.T) {{");
        let _ = writeln!(out, "\t// {description}");
        let _ = writeln!(
            out,
            "\tt.Skip(\"non-HTTP fixture: Go binding does not expose a callable for the configured `[e2e.call]` function\")"
        );
        let _ = writeln!(out, "}}");
        return;
    }

    // Resolve call config per-fixture (supports named calls via fixture.call).
    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
    let lang = "go";
    let overrides = call_config.overrides.get(lang);

    // Select the function name: Go bindings now integrate visitor support into
    // the main Convert() function via ConversionOptions.Visitor field.
    // (In other languages, there may be separate visitor_function overrides, but Go uses a single function.)
    let base_function_name = overrides
        .and_then(|o| o.function.as_deref())
        .unwrap_or(&call_config.function);
    let function_name = to_go_name(base_function_name);
    let result_var = &call_config.result_var;
    let args = &call_config.args;

    // Whether the function returns (value, error) or just (error) or just (value).
    // Check Go override first, fall back to call-level returns_result.
    let returns_result = overrides
        .and_then(|o| o.returns_result)
        .unwrap_or(call_config.returns_result);

    // Whether the function returns only error (no value component), i.e. Result<(), E>.
    // When returns_result=true and returns_void=true, Go emits `err :=` not `_, err :=`.
    let returns_void = call_config.returns_void;

    // result_is_simple: result is a scalar (*string, *bool, etc.) not a struct.
    // Priority: Go override > call-level (canonical source) > Rust override (legacy compat).
    let result_is_simple = overrides.map(|o| o.result_is_simple).unwrap_or_else(|| {
        if call_config.result_is_simple {
            return true;
        }
        call_config
            .overrides
            .get("rust")
            .map(|o| o.result_is_simple)
            .unwrap_or(false)
    });

    // result_is_array: the simple result is a slice/array type (e.g., []string).
    // Priority: Go override > call-level (canonical source).
    let result_is_array = overrides
        .map(|o| o.result_is_array)
        .unwrap_or(call_config.result_is_array);

    // Per-call Go options_type, falling back to the default call's Go override.
    let call_options_type = overrides.and_then(|o| o.options_type.as_deref()).or_else(|| {
        e2e_config
            .call
            .overrides
            .get("go")
            .and_then(|o| o.options_type.as_deref())
    });

    // Whether json_object options are passed as a pointer (*OptionsType).
    let call_options_ptr = overrides.map(|o| o.options_ptr).unwrap_or_else(|| {
        e2e_config
            .call
            .overrides
            .get("go")
            .map(|o| o.options_ptr)
            .unwrap_or(false)
    });

    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");

    // Client factory: when set, the test creates a client via `pkg.Factory("test-key", baseURL)`
    // and calls methods on the instance rather than top-level package functions.
    let client_factory = overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
        e2e_config
            .call
            .overrides
            .get(lang)
            .and_then(|o| o.client_factory.as_deref())
    });

    let (mut setup_lines, args_str) = build_args_and_setup(
        &fixture.input,
        args,
        import_alias,
        call_options_type,
        &fixture.id,
        call_options_ptr,
    );

    // Build visitor if present — integrate into options instead of separate parameter.
    // Go binding's Convert() checks options.Visitor and delegates to convertWithVisitorHelper when set.
    let mut visitor_opts_var: Option<String> = None;
    if fixture.visitor.is_some() {
        let struct_name = visitor_struct_name(&fixture.id);
        setup_lines.push(format!("visitor := &{struct_name}{{}}"));
        // Create a fresh opts variable with the visitor attached.
        let opts_type = call_options_type.unwrap_or("ConversionOptions");
        let opts_var = "opts".to_string();
        setup_lines.push(format!("opts := &{import_alias}.{opts_type}{{}}"));
        setup_lines.push("opts.Visitor = visitor".to_string());
        visitor_opts_var = Some(opts_var);
    }

    let go_extra_args = overrides.map(|o| o.extra_args.as_slice()).unwrap_or(&[]).to_vec();
    let final_args = {
        let mut parts: Vec<String> = Vec::new();
        if !args_str.is_empty() {
            // When visitor is present, replace trailing ", nil" with ", opts"
            let processed_args = if let Some(ref opts_var) = visitor_opts_var {
                args_str.trim_end_matches(", nil").to_string() + ", " + opts_var
            } else {
                args_str
            };
            parts.push(processed_args);
        }
        parts.extend(go_extra_args);
        parts.join(", ")
    };

    let _ = writeln!(out, "func Test_{fn_name}(t *testing.T) {{");
    let _ = writeln!(out, "\t// {description}");

    // Live-API fixtures use `env.api_key_var` to mark the env var that
    // supplies the real API key. Skip the test when the env var is unset
    // (mirrors Python's pytest.skip and Node's early-return pattern).
    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
    if let Some(var) = api_key_var {
        let _ = writeln!(out, "\tapiKey := os.Getenv(\"{var}\")");
        let _ = writeln!(out, "\tif apiKey == \"\" {{");
        let _ = writeln!(out, "\t\tt.Skipf(\"{var} not set\")");
        let _ = writeln!(out, "\t}}");
    }

    for line in &setup_lines {
        let _ = writeln!(out, "\t{line}");
    }

    // Client factory: emit client creation before the call.
    // Each test creates a fresh client pointed at MOCK_SERVER_URL/fixtures/<id>
    // so the mock server can serve the fixture response via prefix routing.
    let call_prefix = if let Some(factory) = client_factory {
        let factory_name = to_go_name(factory);
        let fixture_id = &fixture.id;
        // Live-API tests bypass the mock server: pass apiKey + nil baseURL so
        // the binding hits the real provider. Mock-driven tests pass a
        // mock-server fixture URL and a fixed "test-key" instead.
        let (api_key_expr, base_url_expr) = if api_key_var.is_some() {
            ("apiKey".to_string(), "nil".to_string())
        } else {
            let _ = writeln!(
                out,
                "\tmockURL := os.Getenv(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\""
            );
            ("\"test-key\"".to_string(), "&mockURL".to_string())
        };
        let _ = writeln!(
            out,
            "\tclient, clientErr := {import_alias}.{factory_name}({api_key_expr}, {base_url_expr}, nil, nil, nil)"
        );
        let _ = writeln!(out, "\tif clientErr != nil {{");
        let _ = writeln!(out, "\t\tt.Fatalf(\"create client failed: %v\", clientErr)");
        let _ = writeln!(out, "\t}}");
        "client".to_string()
    } else {
        import_alias.to_string()
    };

    // The Go binding generator wraps the FFI call in `(T, error)` whenever any
    // param requires JSON marshalling, even when the underlying Rust function
    // does not return Result. Detect that so error-expecting tests emit `_, err :=`
    // instead of `err :=` when the binding has a value component.
    let binding_returns_error_pre = args
        .iter()
        .any(|a| matches!(a.arg_type.as_str(), "json_object" | "bytes"));
    let effective_returns_result_pre = returns_result || binding_returns_error_pre || client_factory.is_some();

    if expects_error {
        if effective_returns_result_pre && !returns_void {
            let _ = writeln!(out, "\t_, err := {call_prefix}.{function_name}({final_args})");
        } else {
            let _ = writeln!(out, "\terr := {call_prefix}.{function_name}({final_args})");
        }
        let _ = writeln!(out, "\tif err == nil {{");
        let _ = writeln!(out, "\t\tt.Errorf(\"expected an error, but call succeeded\")");
        let _ = writeln!(out, "\t}}");
        let _ = writeln!(out, "}}");
        return;
    }

    // Check if any assertion actually uses the result variable.
    // If all assertions are skipped (field not on result type), use `_` to avoid
    // Go's "declared and not used" compile error.
    let has_usable_assertion = fixture.assertions.iter().any(|a| {
        if a.assertion_type == "not_error" || a.assertion_type == "error" {
            return false;
        }
        // method_result assertions always use the result variable.
        if a.assertion_type == "method_result" {
            return true;
        }
        match &a.field {
            Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
            _ => true,
        }
    });

    // The Go binding generator (alef-backend-go) wraps the FFI call in `(T, error)`
    // whenever any param requires JSON marshalling (Vec, Map, Named struct), even when
    // the underlying Rust function does not return Result. So a result_is_simple call
    // like `generate_cache_key(parts: &[(String, String)]) -> String` still surfaces in
    // Go as `func GenerateCacheKey(parts [][]string) (*string, error)`. Detect that
    // here so the test emits `_, err :=` / `result, err :=` instead of `result :=`.
    let binding_returns_error = args
        .iter()
        .any(|a| matches!(a.arg_type.as_str(), "json_object" | "bytes"));
    // Client-factory methods always return (value, error) in the Go binding.
    let effective_returns_result = returns_result || binding_returns_error || client_factory.is_some();

    // For result_is_simple functions, the result variable IS the value (e.g. *string, *bool).
    // We create a local `value` that dereferences it so assertions can use a plain type.
    // For functions that return (value, error): emit `result, err :=`
    // For functions that return only error: emit `err :=`
    // For functions that return only a value (result_is_simple, no error): emit `result :=`
    if !effective_returns_result && result_is_simple {
        // Function returns a single value, no error (e.g. *string, *bool).
        let result_binding = if has_usable_assertion {
            result_var.to_string()
        } else {
            "_".to_string()
        };
        // In Go, `_ :=` is invalid — must use `_ =` for the blank identifier.
        let assign_op = if result_binding == "_" { "=" } else { ":=" };
        let _ = writeln!(
            out,
            "\t{result_binding} {assign_op} {call_prefix}.{function_name}({final_args})"
        );
        if has_usable_assertion && result_binding != "_" {
            if result_is_array {
                // Array results are slices (not pointers); assign directly without dereference.
                let _ = writeln!(out, "\tvalue := {result_var}");
            } else {
                // Check if ALL simple-result assertions are is_empty/is_null with no field.
                // If so, skip dereference — we'll use the pointer directly.
                let only_nil_assertions = fixture
                    .assertions
                    .iter()
                    .filter(|a| a.field.as_ref().is_none_or(|f| f.is_empty()))
                    .filter(|a| !matches!(a.assertion_type.as_str(), "not_error" | "error"))
                    .all(|a| matches!(a.assertion_type.as_str(), "is_empty" | "is_null"));

                if !only_nil_assertions {
                    // Emit nil check and dereference for simple pointer results.
                    let _ = writeln!(out, "\tif {result_var} == nil {{");
                    let _ = writeln!(out, "\t\tt.Fatalf(\"expected non-nil result\")");
                    let _ = writeln!(out, "\t}}");
                    let _ = writeln!(out, "\tvalue := *{result_var}");
                }
            }
        }
    } else if !effective_returns_result || returns_void {
        // Function returns only error (either returns_result=false, or returns_result=true
        // with returns_void=true meaning the Go function signature is `func(...) error`).
        let _ = writeln!(out, "\terr := {call_prefix}.{function_name}({final_args})");
        let _ = writeln!(out, "\tif err != nil {{");
        let _ = writeln!(out, "\t\tt.Fatalf(\"call failed: %v\", err)");
        let _ = writeln!(out, "\t}}");
        // No result variable to use in assertions.
        let _ = writeln!(out, "}}");
        return;
    } else {
        // returns_result = true, returns_void = false: function returns (value, error).
        let result_binding = if has_usable_assertion {
            result_var.to_string()
        } else {
            "_".to_string()
        };
        let _ = writeln!(
            out,
            "\t{result_binding}, err := {call_prefix}.{function_name}({final_args})"
        );
        let _ = writeln!(out, "\tif err != nil {{");
        let _ = writeln!(out, "\t\tt.Fatalf(\"call failed: %v\", err)");
        let _ = writeln!(out, "\t}}");
        if result_is_simple && has_usable_assertion && result_binding != "_" {
            if result_is_array {
                // Array results are slices (not pointers); assign directly without dereference.
                let _ = writeln!(out, "\tvalue := {}", result_var);
            } else {
                // Check if ALL simple-result assertions are is_empty/is_null with no field.
                // If so, skip dereference — we'll use the pointer directly.
                let only_nil_assertions = fixture
                    .assertions
                    .iter()
                    .filter(|a| a.field.as_ref().is_none_or(|f| f.is_empty()))
                    .filter(|a| !matches!(a.assertion_type.as_str(), "not_error" | "error"))
                    .all(|a| matches!(a.assertion_type.as_str(), "is_empty" | "is_null"));

                if !only_nil_assertions {
                    // Emit nil check and dereference for simple pointer results.
                    let _ = writeln!(out, "\tif {} == nil {{", result_var);
                    let _ = writeln!(out, "\t\tt.Fatalf(\"expected non-nil result\")");
                    let _ = writeln!(out, "\t}}");
                    let _ = writeln!(out, "\tvalue := *{}", result_var);
                }
            }
        }
    }

    // For result_is_simple functions, determine if we created a dereferenced `value` variable.
    // We skip dereferencing if all simple-result assertions are is_empty/is_null with no field.
    let has_deref_value = if result_is_simple && has_usable_assertion && !result_is_array {
        let only_nil_assertions = fixture
            .assertions
            .iter()
            .filter(|a| a.field.as_ref().is_none_or(|f| f.is_empty()))
            .filter(|a| !matches!(a.assertion_type.as_str(), "not_error" | "error"))
            .all(|a| matches!(a.assertion_type.as_str(), "is_empty" | "is_null"));
        !only_nil_assertions
    } else {
        result_is_simple && has_usable_assertion
    };

    let effective_result_var = if has_deref_value {
        "value".to_string()
    } else {
        result_var.to_string()
    };

    // Collect optional fields referenced by assertions and emit nil-safe
    // dereference blocks so that assertions can use plain string locals.
    // Only dereference fields whose assertion values are strings (or that are
    // used in string-oriented assertions like equals/contains with string values).
    let mut optional_locals: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for assertion in &fixture.assertions {
        if let Some(f) = &assertion.field {
            if !f.is_empty() {
                let resolved = field_resolver.resolve(f);
                if field_resolver.is_optional(resolved) && !optional_locals.contains_key(f.as_str()) {
                    // Only create deref locals for string-valued fields that are NOT arrays.
                    // Array fields (e.g., *[]string) must keep their pointer form so
                    // render_assertion can emit strings.Join(*field, " ") rather than
                    // treating them as plain strings.
                    let is_string_field = assertion.value.as_ref().is_some_and(|v| v.is_string());
                    let is_array_field = field_resolver.is_array(resolved);
                    if !is_string_field || is_array_field {
                        // Non-string optional fields (e.g., *uint64) and array optional
                        // fields (e.g., *[]string) are handled by nil guards in render_assertion.
                        continue;
                    }
                    let field_expr = field_resolver.accessor(f, "go", &effective_result_var);
                    let local_var = go_param_name(&resolved.replace(['.', '[', ']'], "_"));
                    if field_resolver.has_map_access(f) {
                        // Go map access returns a value type (string), not a pointer.
                        // Use the value directly — empty string means not present.
                        let _ = writeln!(out, "\t{local_var} := {field_expr}");
                    } else {
                        let _ = writeln!(out, "\tvar {local_var} string");
                        let _ = writeln!(out, "\tif {field_expr} != nil {{");
                        // Use string() cast to handle named string types (e.g. *FinishReason) in
                        // addition to plain *string fields — string(*ptr) is a no-op for *string
                        // and a safe coercion for any named type whose underlying type is string.
                        let _ = writeln!(out, "\t\t{local_var} = string(*{field_expr})");
                        let _ = writeln!(out, "\t}}");
                    }
                    optional_locals.insert(f.clone(), local_var);
                }
            }
        }
    }

    // Emit assertions, wrapping in nil guards when an intermediate path segment is optional.
    for assertion in &fixture.assertions {
        if let Some(f) = &assertion.field {
            if !f.is_empty() && !optional_locals.contains_key(f.as_str()) {
                // Check if any prefix of the dotted path is optional (pointer in Go).
                // e.g., "document.nodes" — if "document" is optional, guard the whole block.
                let parts: Vec<&str> = f.split('.').collect();
                let mut guard_expr: Option<String> = None;
                for i in 1..parts.len() {
                    let prefix = parts[..i].join(".");
                    let resolved_prefix = field_resolver.resolve(&prefix);
                    if field_resolver.is_optional(resolved_prefix) {
                        let accessor = field_resolver.accessor(&prefix, "go", &effective_result_var);
                        guard_expr = Some(accessor);
                        break;
                    }
                }
                if let Some(guard) = guard_expr {
                    // Only emit nil guard if the assertion will actually produce code
                    // (not just a skip comment), to avoid empty branches (SA9003).
                    if field_resolver.is_valid_for_result(f) {
                        let _ = writeln!(out, "\tif {guard} != nil {{");
                        // Render into a temporary buffer so we can re-indent by one
                        // tab level to sit inside the nil-guard block.
                        let mut nil_buf = String::new();
                        render_assertion(
                            &mut nil_buf,
                            assertion,
                            &effective_result_var,
                            import_alias,
                            field_resolver,
                            &optional_locals,
                            result_is_simple,
                            result_is_array,
                        );
                        for line in nil_buf.lines() {
                            let _ = writeln!(out, "\t{line}");
                        }
                        let _ = writeln!(out, "\t}}");
                    } else {
                        render_assertion(
                            out,
                            assertion,
                            &effective_result_var,
                            import_alias,
                            field_resolver,
                            &optional_locals,
                            result_is_simple,
                            result_is_array,
                        );
                    }
                    continue;
                }
            }
        }
        render_assertion(
            out,
            assertion,
            &effective_result_var,
            import_alias,
            field_resolver,
            &optional_locals,
            result_is_simple,
            result_is_array,
        );
    }

    let _ = writeln!(out, "}}");
}

/// Render an HTTP server test function using net/http against MOCK_SERVER_URL.
///
/// Delegates to the shared driver [`client::http_call::render_http_test`] via
/// [`GoTestClientRenderer`]. The emitted test shape is unchanged: `func Test_<Name>(t *testing.T)`
/// with a `net/http` client that hits `$MOCK_SERVER_URL/fixtures/<id>`.
fn render_http_test_function(out: &mut String, fixture: &Fixture) {
    client::http_call::render_http_test(out, &GoTestClientRenderer, fixture);
}

// ---------------------------------------------------------------------------
// HTTP test rendering — GoTestClientRenderer
// ---------------------------------------------------------------------------

/// Go `net/http` test renderer.
///
/// Go HTTP e2e tests send a request to `$MOCK_SERVER_URL/fixtures/<id>` using
/// the standard library `net/http` client. The trait primitives emit the
/// request-build, response-capture, and assertion code that the previous
/// monolithic renderer produced, so generated output is unchanged after the
/// migration.
struct GoTestClientRenderer;

impl client::TestClientRenderer for GoTestClientRenderer {
    fn language_name(&self) -> &'static str {
        "go"
    }

    /// Go test names use `UpperCamelCase` so they form valid exported identifiers
    /// (e.g. `Test_MyFixtureId`). Override the default `sanitize_ident` which
    /// produces `lower_snake_case`.
    fn sanitize_test_name(&self, id: &str) -> String {
        id.to_upper_camel_case()
    }

    /// Emit `func Test_<fn_name>(t *testing.T) {`, a description comment, and the
    /// `baseURL` / request scaffolding. Skipped fixtures get `t.Skip(...)` inline.
    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
        let _ = writeln!(out, "func Test_{fn_name}(t *testing.T) {{");
        let _ = writeln!(out, "\t// {description}");
        if let Some(reason) = skip_reason {
            let escaped = go_string_literal(reason);
            let _ = writeln!(out, "\tt.Skip({escaped})");
        }
    }

    fn render_test_close(&self, out: &mut String) {
        let _ = writeln!(out, "}}");
    }

    /// Emit the full `net/http` request scaffolding: URL construction, body,
    /// headers, cookies, a no-redirect client, and `io.ReadAll` for the body.
    ///
    /// `bodyBytes` is always declared (with `_ = bodyBytes` to avoid the Go
    /// "declared and not used" compile error on tests with no body assertion).
    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
        let method = ctx.method.to_uppercase();
        let path = ctx.path;

        let _ = writeln!(out, "\tbaseURL := os.Getenv(\"MOCK_SERVER_URL\")");
        let _ = writeln!(out, "\tif baseURL == \"\" {{");
        let _ = writeln!(out, "\t\tbaseURL = \"http://localhost:8080\"");
        let _ = writeln!(out, "\t}}");

        // Build request body expression.
        let body_expr = if let Some(body) = ctx.body {
            let json = serde_json::to_string(body).unwrap_or_default();
            let escaped = go_string_literal(&json);
            format!("strings.NewReader({})", escaped)
        } else {
            "strings.NewReader(\"\")".to_string()
        };

        let _ = writeln!(out, "\tbody := {body_expr}");
        let _ = writeln!(
            out,
            "\treq, err := http.NewRequest(\"{method}\", baseURL+\"{path}\", body)"
        );
        let _ = writeln!(out, "\tif err != nil {{");
        let _ = writeln!(out, "\t\tt.Fatalf(\"new request failed: %v\", err)");
        let _ = writeln!(out, "\t}}");

        // Content-Type header (only when a body is present).
        if ctx.body.is_some() {
            let content_type = ctx.content_type.unwrap_or("application/json");
            let _ = writeln!(out, "\treq.Header.Set(\"Content-Type\", \"{content_type}\")");
        }

        // Explicit request headers (sorted for deterministic output).
        let mut header_names: Vec<&String> = ctx.headers.keys().collect();
        header_names.sort();
        for name in header_names {
            let value = &ctx.headers[name];
            let escaped_name = go_string_literal(name);
            let escaped_value = go_string_literal(value);
            let _ = writeln!(out, "\treq.Header.Set({escaped_name}, {escaped_value})");
        }

        // Cookies.
        if !ctx.cookies.is_empty() {
            let mut cookie_names: Vec<&String> = ctx.cookies.keys().collect();
            cookie_names.sort();
            for name in cookie_names {
                let value = &ctx.cookies[name];
                let escaped_name = go_string_literal(name);
                let escaped_value = go_string_literal(value);
                let _ = writeln!(
                    out,
                    "\treq.AddCookie(&http.Cookie{{Name: {escaped_name}, Value: {escaped_value}}})"
                );
            }
        }

        // No-redirect client so 3xx fixtures assert the redirect response itself.
        let _ = writeln!(out, "\tnoRedirectClient := &http.Client{{");
        let _ = writeln!(
            out,
            "\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {{"
        );
        let _ = writeln!(out, "\t\t\treturn http.ErrUseLastResponse");
        let _ = writeln!(out, "\t\t}},");
        let _ = writeln!(out, "\t}}");
        let _ = writeln!(out, "\tresp, err := noRedirectClient.Do(req)");
        let _ = writeln!(out, "\tif err != nil {{");
        let _ = writeln!(out, "\t\tt.Fatalf(\"request failed: %v\", err)");
        let _ = writeln!(out, "\t}}");
        let _ = writeln!(out, "\tdefer resp.Body.Close()");

        // Always read the response body so body-assertion methods can reference
        // `bodyBytes`. Suppress the "declared and not used" compile error with
        // `_ = bodyBytes` for tests that have no body assertion.
        let _ = writeln!(out, "\tbodyBytes, err := io.ReadAll(resp.Body)");
        let _ = writeln!(out, "\tif err != nil {{");
        let _ = writeln!(out, "\t\tt.Fatalf(\"read body failed: %v\", err)");
        let _ = writeln!(out, "\t}}");
        let _ = writeln!(out, "\t_ = bodyBytes");
    }

    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
        let _ = writeln!(out, "\tif resp.StatusCode != {status} {{");
        let _ = writeln!(out, "\t\tt.Fatalf(\"status: got %d want {status}\", resp.StatusCode)");
        let _ = writeln!(out, "\t}}");
    }

    /// Emit a header assertion, skipping special tokens (`<<present>>`, `<<absent>>`,
    /// `<<uuid>>`) and hop-by-hop headers (`Connection`) that `net/http` strips.
    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
        // Skip special-token assertions.
        if matches!(expected, "<<absent>>" | "<<present>>" | "<<uuid>>") {
            return;
        }
        // Connection is a hop-by-hop header that Go's net/http strips.
        if name.eq_ignore_ascii_case("connection") {
            return;
        }
        let escaped_name = go_string_literal(name);
        let escaped_value = go_string_literal(expected);
        let _ = writeln!(
            out,
            "\tif !strings.Contains(resp.Header.Get({escaped_name}), {escaped_value}) {{"
        );
        let _ = writeln!(
            out,
            "\t\tt.Fatalf(\"header %s mismatch: got %q want to contain %q\", {escaped_name}, resp.Header.Get({escaped_name}), {escaped_value})"
        );
        let _ = writeln!(out, "\t}}");
    }

    /// Emit an exact-equality body assertion.
    ///
    /// JSON objects and arrays are round-tripped via `json.Unmarshal` + `reflect.DeepEqual`.
    /// Scalar values are compared as trimmed strings.
    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
        match expected {
            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
                let json_str = serde_json::to_string(expected).unwrap_or_default();
                let escaped = go_string_literal(&json_str);
                let _ = writeln!(out, "\tvar got any");
                let _ = writeln!(out, "\tvar want any");
                let _ = writeln!(out, "\tif err := json.Unmarshal(bodyBytes, &got); err != nil {{");
                let _ = writeln!(out, "\t\tt.Fatalf(\"json unmarshal got: %v\", err)");
                let _ = writeln!(out, "\t}}");
                let _ = writeln!(
                    out,
                    "\tif err := json.Unmarshal([]byte({escaped}), &want); err != nil {{"
                );
                let _ = writeln!(out, "\t\tt.Fatalf(\"json unmarshal want: %v\", err)");
                let _ = writeln!(out, "\t}}");
                let _ = writeln!(out, "\tif !reflect.DeepEqual(got, want) {{");
                let _ = writeln!(out, "\t\tt.Fatalf(\"body mismatch: got %v want %v\", got, want)");
                let _ = writeln!(out, "\t}}");
            }
            serde_json::Value::String(s) => {
                let escaped = go_string_literal(s);
                let _ = writeln!(out, "\twant := {escaped}");
                let _ = writeln!(out, "\tif strings.TrimSpace(string(bodyBytes)) != want {{");
                let _ = writeln!(out, "\t\tt.Fatalf(\"body: got %q want %q\", string(bodyBytes), want)");
                let _ = writeln!(out, "\t}}");
            }
            other => {
                let escaped = go_string_literal(&other.to_string());
                let _ = writeln!(out, "\twant := {escaped}");
                let _ = writeln!(out, "\tif strings.TrimSpace(string(bodyBytes)) != want {{");
                let _ = writeln!(out, "\t\tt.Fatalf(\"body: got %q want %q\", string(bodyBytes), want)");
                let _ = writeln!(out, "\t}}");
            }
        }
    }

    /// Emit partial-body assertions: every key in `expected` must appear in the
    /// parsed JSON response with the matching value.
    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
        if let Some(obj) = expected.as_object() {
            let _ = writeln!(out, "\tvar _partialGot map[string]any");
            let _ = writeln!(
                out,
                "\tif err := json.Unmarshal(bodyBytes, &_partialGot); err != nil {{"
            );
            let _ = writeln!(out, "\t\tt.Fatalf(\"json unmarshal partial: %v\", err)");
            let _ = writeln!(out, "\t}}");
            for (key, val) in obj {
                let escaped_key = go_string_literal(key);
                let json_val = serde_json::to_string(val).unwrap_or_default();
                let escaped_val = go_string_literal(&json_val);
                let _ = writeln!(out, "\t{{");
                let _ = writeln!(out, "\t\tvar _wantVal any");
                let _ = writeln!(
                    out,
                    "\t\tif err := json.Unmarshal([]byte({escaped_val}), &_wantVal); err != nil {{"
                );
                let _ = writeln!(out, "\t\t\tt.Fatalf(\"json unmarshal partial want: %v\", err)");
                let _ = writeln!(out, "\t\t}}");
                let _ = writeln!(
                    out,
                    "\t\tif !reflect.DeepEqual(_partialGot[{escaped_key}], _wantVal) {{"
                );
                let _ = writeln!(
                    out,
                    "\t\t\tt.Fatalf(\"partial body field {key}: got %v want %v\", _partialGot[{escaped_key}], _wantVal)"
                );
                let _ = writeln!(out, "\t\t}}");
                let _ = writeln!(out, "\t}}");
            }
        }
    }

    /// Emit validation-error assertions for 422 responses.
    ///
    /// Checks that each expected `msg` appears in at least one element of the
    /// parsed body's `"errors"` array.
    fn render_assert_validation_errors(
        &self,
        out: &mut String,
        _response_var: &str,
        errors: &[ValidationErrorExpectation],
    ) {
        let _ = writeln!(out, "\tvar _veBody map[string]any");
        let _ = writeln!(out, "\tif err := json.Unmarshal(bodyBytes, &_veBody); err != nil {{");
        let _ = writeln!(out, "\t\tt.Fatalf(\"json unmarshal validation errors: %v\", err)");
        let _ = writeln!(out, "\t}}");
        let _ = writeln!(out, "\t_veErrors, _ := _veBody[\"errors\"].([]any)");
        for ve in errors {
            let escaped_msg = go_string_literal(&ve.msg);
            let _ = writeln!(out, "\t{{");
            let _ = writeln!(out, "\t\t_found := false");
            let _ = writeln!(out, "\t\tfor _, _e := range _veErrors {{");
            let _ = writeln!(out, "\t\t\tif _em, ok := _e.(map[string]any); ok {{");
            let _ = writeln!(
                out,
                "\t\t\t\tif _msg, ok := _em[\"msg\"].(string); ok && strings.Contains(_msg, {escaped_msg}) {{"
            );
            let _ = writeln!(out, "\t\t\t\t\t_found = true");
            let _ = writeln!(out, "\t\t\t\t\tbreak");
            let _ = writeln!(out, "\t\t\t\t}}");
            let _ = writeln!(out, "\t\t\t}}");
            let _ = writeln!(out, "\t\t}}");
            let _ = writeln!(out, "\t\tif !_found {{");
            let _ = writeln!(
                out,
                "\t\t\tt.Fatalf(\"validation error with msg containing %q not found in errors\", {escaped_msg})"
            );
            let _ = writeln!(out, "\t\t}}");
            let _ = writeln!(out, "\t}}");
        }
    }
}

/// Build setup lines (e.g. handle creation) and the argument list for the function call.
///
/// Returns `(setup_lines, args_string)`.
///
/// `options_ptr` — when `true`, `json_object` args with an `options_type` are
/// passed as a Go pointer (`*OptionsType`): absent/empty → `nil`, present →
/// `&varName` after JSON unmarshal.
fn build_args_and_setup(
    input: &serde_json::Value,
    args: &[crate::config::ArgMapping],
    import_alias: &str,
    options_type: Option<&str>,
    fixture_id: &str,
    options_ptr: bool,
) -> (Vec<String>, String) {
    use heck::ToUpperCamelCase;

    if args.is_empty() {
        return (Vec::new(), String::new());
    }

    let mut setup_lines: Vec<String> = Vec::new();
    let mut parts: Vec<String> = Vec::new();

    for arg in args {
        if arg.arg_type == "mock_url" {
            setup_lines.push(format!(
                "{} := os.Getenv(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\"",
                arg.name,
            ));
            parts.push(arg.name.clone());
            continue;
        }

        if arg.arg_type == "handle" {
            // Generate a CreateEngine (or equivalent) call and pass the variable.
            let constructor_name = format!("Create{}", arg.name.to_upper_camel_case());
            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
            if config_value.is_null()
                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
            {
                setup_lines.push(format!(
                    "{name}, createErr := {import_alias}.{constructor_name}(nil)\n\tif createErr != nil {{\n\t\tt.Fatalf(\"create handle failed: %v\", createErr)\n\t}}",
                    name = arg.name,
                ));
            } else {
                let json_str = serde_json::to_string(config_value).unwrap_or_default();
                let go_literal = go_string_literal(&json_str);
                let name = &arg.name;
                setup_lines.push(format!(
                    "var {name}Config {import_alias}.CrawlConfig\n\tif err := json.Unmarshal([]byte({go_literal}), &{name}Config); err != nil {{\n\t\tt.Fatalf(\"config parse failed: %v\", err)\n\t}}"
                ));
                setup_lines.push(format!(
                    "{name}, createErr := {import_alias}.{constructor_name}(&{name}Config)\n\tif createErr != nil {{\n\t\tt.Fatalf(\"create handle failed: %v\", createErr)\n\t}}"
                ));
            }
            parts.push(arg.name.clone());
            continue;
        }

        let val: Option<&serde_json::Value> = if arg.field == "input" {
            Some(input)
        } else {
            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
            input.get(field)
        };

        // file_path args are fixture-relative paths under `test_documents/`. The Go test
        // runner's TestMain (in main_test.go) already does `os.Chdir(test_documents)` so
        // tests can pass these relative strings directly; no additional resolution needed.

        // Handle bytes type: fixture stores base64-encoded bytes.
        // Emit a Go base64.StdEncoding.DecodeString call to decode at runtime.
        if arg.arg_type == "bytes" {
            let var_name = format!("{}Bytes", arg.name);
            match val {
                None | Some(serde_json::Value::Null) => {
                    if arg.optional {
                        parts.push("nil".to_string());
                    } else {
                        parts.push("[]byte{}".to_string());
                    }
                }
                Some(serde_json::Value::String(s)) => {
                    // Bytes args whose fixture value is a string are fixture-relative paths into
                    // the repo-root `test_documents/` directory (matching the rust e2e codegen
                    // convention). The Go test runner's TestMain chdirs into test_documents/, so
                    // a bare relative path resolves correctly via os.ReadFile.
                    let go_path = go_string_literal(s);
                    setup_lines.push(format!(
                        "{var_name}, {var_name}Err := os.ReadFile({go_path})\n\tif {var_name}Err != nil {{\n\t\tt.Fatalf(\"read fixture {s}: %v\", {var_name}Err)\n\t}}"
                    ));
                    parts.push(var_name);
                }
                Some(other) => {
                    parts.push(format!("[]byte({})", json_to_go(other)));
                }
            }
            continue;
        }

        match val {
            None | Some(serde_json::Value::Null) if arg.optional => {
                // Optional arg absent: emit Go zero/nil for the type.
                match arg.arg_type.as_str() {
                    "string" => {
                        // Optional string in Go bindings is *string → nil.
                        parts.push("nil".to_string());
                    }
                    "json_object" => {
                        if options_ptr {
                            // Pointer options type (*OptionsType): absent → nil.
                            parts.push("nil".to_string());
                        } else if let Some(opts_type) = options_type {
                            // Value options type: zero-value struct.
                            parts.push(format!("{import_alias}.{opts_type}{{}}"));
                        } else {
                            parts.push("nil".to_string());
                        }
                    }
                    _ => {
                        parts.push("nil".to_string());
                    }
                }
            }
            None | Some(serde_json::Value::Null) => {
                // Required arg with no fixture value: pass a language-appropriate default.
                let default_val = match arg.arg_type.as_str() {
                    "string" => "\"\"".to_string(),
                    "int" | "integer" | "i64" => "0".to_string(),
                    "float" | "number" => "0.0".to_string(),
                    "bool" | "boolean" => "false".to_string(),
                    "json_object" => {
                        if options_ptr {
                            // Pointer options type (*OptionsType): absent → nil.
                            "nil".to_string()
                        } else if let Some(opts_type) = options_type {
                            format!("{import_alias}.{opts_type}{{}}")
                        } else {
                            "nil".to_string()
                        }
                    }
                    _ => "nil".to_string(),
                };
                parts.push(default_val);
            }
            Some(v) => {
                match arg.arg_type.as_str() {
                    "json_object" => {
                        // JSON arrays unmarshal into []string (Go slices).
                        // JSON objects with a known options_type unmarshal into that type.
                        let is_array = v.is_array();
                        let is_empty_obj = !is_array && v.is_object() && v.as_object().is_some_and(|o| o.is_empty());
                        if is_empty_obj {
                            if options_ptr {
                                // Pointer options type: empty object → nil.
                                parts.push("nil".to_string());
                            } else if let Some(opts_type) = options_type {
                                parts.push(format!("{import_alias}.{opts_type}{{}}"));
                            } else {
                                parts.push("nil".to_string());
                            }
                        } else if is_array {
                            // Array type — unmarshal into a Go slice. Honor `go_type` for a
                            // fully explicit Go type (e.g. `"kreuzberg.BatchBytesItem"`), fall
                            // back to deriving the slice type from `element_type`, defaulting
                            // to `[]string` for unknown types.
                            let go_slice_type = if let Some(go_t) = arg.go_type.as_deref() {
                                // go_type is the slice element type — wrap it in [].
                                // If it already starts with '[' the user specified the full
                                // slice type; use it verbatim.
                                if go_t.starts_with('[') {
                                    go_t.to_string()
                                } else {
                                    // Qualify unqualified types (e.g., "BatchBytesItem" → "kreuzberg.BatchBytesItem")
                                    let qualified = if go_t.contains('.') {
                                        go_t.to_string()
                                    } else {
                                        format!("{import_alias}.{go_t}")
                                    };
                                    format!("[]{qualified}")
                                }
                            } else {
                                element_type_to_go_slice(arg.element_type.as_deref(), import_alias)
                            };
                            // Convert JSON for Go compatibility (e.g., byte arrays → base64 strings)
                            let converted_v = convert_json_for_go(v.clone());
                            let json_str = serde_json::to_string(&converted_v).unwrap_or_default();
                            let go_literal = go_string_literal(&json_str);
                            let var_name = &arg.name;
                            setup_lines.push(format!(
                                "var {var_name} {go_slice_type}\n\tif err := json.Unmarshal([]byte({go_literal}), &{var_name}); err != nil {{\n\t\tt.Fatalf(\"config parse failed: %v\", err)\n\t}}"
                            ));
                            parts.push(var_name.to_string());
                        } else if let Some(opts_type) = options_type {
                            // Object with known type — unmarshal into typed struct.
                            // When options_ptr is set, the Go struct uses snake_case JSON
                            // field tags and lowercase/snake_case enum values.  Remap the
                            // fixture's camelCase keys and PascalCase enum string values.
                            let remapped_v = if options_ptr {
                                convert_json_for_go(v.clone())
                            } else {
                                v.clone()
                            };
                            let json_str = serde_json::to_string(&remapped_v).unwrap_or_default();
                            let go_literal = go_string_literal(&json_str);
                            let var_name = &arg.name;
                            setup_lines.push(format!(
                                "var {var_name} {import_alias}.{opts_type}\n\tif err := json.Unmarshal([]byte({go_literal}), &{var_name}); err != nil {{\n\t\tt.Fatalf(\"config parse failed: %v\", err)\n\t}}"
                            ));
                            // Pass as pointer when options_ptr is set.
                            let arg_expr = if options_ptr {
                                format!("&{var_name}")
                            } else {
                                var_name.to_string()
                            };
                            parts.push(arg_expr);
                        } else {
                            parts.push(json_to_go(v));
                        }
                    }
                    "string" if arg.optional => {
                        // Optional string in Go is *string — take address of a local.
                        let var_name = format!("{}Val", arg.name);
                        let go_val = json_to_go(v);
                        setup_lines.push(format!("{var_name} := {go_val}"));
                        parts.push(format!("&{var_name}"));
                    }
                    _ => {
                        parts.push(json_to_go(v));
                    }
                }
            }
        }
    }

    (setup_lines, parts.join(", "))
}

#[allow(clippy::too_many_arguments)]
fn render_assertion(
    out: &mut String,
    assertion: &Assertion,
    result_var: &str,
    import_alias: &str,
    field_resolver: &FieldResolver,
    optional_locals: &std::collections::HashMap<String, String>,
    result_is_simple: bool,
    result_is_array: bool,
) {
    // Handle synthetic / derived fields before the is_valid_for_result check
    // so they are never treated as struct field accesses on the result.
    if !result_is_simple {
        if let Some(f) = &assertion.field {
            // embed_texts returns *[][]float32; the embedding matrix is *result_var.
            // We emit inline func() expressions so we don't need additional variables.
            let embed_deref = format!("(*{result_var})");
            match f.as_str() {
                "chunks_have_content" => {
                    let pred = format!(
                        "func() bool {{ chunks := {result_var}.Chunks; if chunks == nil {{ return false }}; for _, c := range *chunks {{ if c.Content == \"\" {{ return false }} }}; return true }}()"
                    );
                    match assertion.assertion_type.as_str() {
                        "is_true" => {
                            let _ = writeln!(out, "\tassert.True(t, {pred}, \"expected true\")");
                        }
                        "is_false" => {
                            let _ = writeln!(out, "\tassert.False(t, {pred}, \"expected false\")");
                        }
                        _ => {
                            let _ = writeln!(out, "\t// skipped: unsupported assertion type on synthetic field '{f}'");
                        }
                    }
                    return;
                }
                "chunks_have_embeddings" => {
                    let pred = format!(
                        "func() bool {{ chunks := {result_var}.Chunks; if chunks == nil {{ return false }}; for _, c := range *chunks {{ if c.Embedding == nil || len(*c.Embedding) == 0 {{ return false }} }}; return true }}()"
                    );
                    match assertion.assertion_type.as_str() {
                        "is_true" => {
                            let _ = writeln!(out, "\tassert.True(t, {pred}, \"expected true\")");
                        }
                        "is_false" => {
                            let _ = writeln!(out, "\tassert.False(t, {pred}, \"expected false\")");
                        }
                        _ => {
                            let _ = writeln!(out, "\t// skipped: unsupported assertion type on synthetic field '{f}'");
                        }
                    }
                    return;
                }
                "embeddings" => {
                    match assertion.assertion_type.as_str() {
                        "count_equals" => {
                            if let Some(val) = &assertion.value {
                                if let Some(n) = val.as_u64() {
                                    let _ = writeln!(
                                        out,
                                        "\tassert.Equal(t, {n}, len({embed_deref}), \"expected exactly {n} elements\")"
                                    );
                                }
                            }
                        }
                        "count_min" => {
                            if let Some(val) = &assertion.value {
                                if let Some(n) = val.as_u64() {
                                    let _ = writeln!(
                                        out,
                                        "\tassert.GreaterOrEqual(t, len({embed_deref}), {n}, \"expected at least {n} elements\")"
                                    );
                                }
                            }
                        }
                        "not_empty" => {
                            let _ = writeln!(
                                out,
                                "\tassert.NotEmpty(t, {embed_deref}, \"expected non-empty embeddings\")"
                            );
                        }
                        "is_empty" => {
                            let _ = writeln!(out, "\tassert.Empty(t, {embed_deref}, \"expected empty embeddings\")");
                        }
                        _ => {
                            let _ = writeln!(
                                out,
                                "\t// skipped: unsupported assertion type on synthetic field 'embeddings'"
                            );
                        }
                    }
                    return;
                }
                "embedding_dimensions" => {
                    let expr = format!(
                        "func() int {{ if len({embed_deref}) == 0 {{ return 0 }}; return len({embed_deref}[0]) }}()"
                    );
                    match assertion.assertion_type.as_str() {
                        "equals" => {
                            if let Some(val) = &assertion.value {
                                if let Some(n) = val.as_u64() {
                                    let _ = writeln!(
                                        out,
                                        "\tif {expr} != {n} {{\n\t\tt.Errorf(\"equals mismatch: got %v\", {expr})\n\t}}"
                                    );
                                }
                            }
                        }
                        "greater_than" => {
                            if let Some(val) = &assertion.value {
                                if let Some(n) = val.as_u64() {
                                    let _ = writeln!(out, "\tassert.Greater(t, {expr}, {n}, \"expected > {n}\")");
                                }
                            }
                        }
                        _ => {
                            let _ = writeln!(
                                out,
                                "\t// skipped: unsupported assertion type on synthetic field 'embedding_dimensions'"
                            );
                        }
                    }
                    return;
                }
                "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
                    let pred = match f.as_str() {
                        "embeddings_valid" => {
                            format!(
                                "func() bool {{ for _, e := range {embed_deref} {{ if len(e) == 0 {{ return false }} }}; return true }}()"
                            )
                        }
                        "embeddings_finite" => {
                            format!(
                                "func() bool {{ for _, e := range {embed_deref} {{ for _, v := range e {{ if v != v || v == float32(1.0/0.0) || v == float32(-1.0/0.0) {{ return false }} }} }}; return true }}()"
                            )
                        }
                        "embeddings_non_zero" => {
                            format!(
                                "func() bool {{ for _, e := range {embed_deref} {{ hasNonZero := false; for _, v := range e {{ if v != 0 {{ hasNonZero = true; break }} }}; if !hasNonZero {{ return false }} }}; return true }}()"
                            )
                        }
                        "embeddings_normalized" => {
                            format!(
                                "func() bool {{ for _, e := range {embed_deref} {{ var n float64; for _, v := range e {{ n += float64(v) * float64(v) }}; if n < 0.999 || n > 1.001 {{ return false }} }}; return true }}()"
                            )
                        }
                        _ => unreachable!(),
                    };
                    match assertion.assertion_type.as_str() {
                        "is_true" => {
                            let _ = writeln!(out, "\tassert.True(t, {pred}, \"expected true\")");
                        }
                        "is_false" => {
                            let _ = writeln!(out, "\tassert.False(t, {pred}, \"expected false\")");
                        }
                        _ => {
                            let _ = writeln!(out, "\t// skipped: unsupported assertion type on synthetic field '{f}'");
                        }
                    }
                    return;
                }
                // ---- keywords / keywords_count ----
                // Go ExtractionResult does not expose extracted_keywords; skip.
                "keywords" | "keywords_count" => {
                    let _ = writeln!(out, "\t// skipped: field '{f}' not available on Go ExtractionResult");
                    return;
                }
                _ => {}
            }
        }
    }

    // Skip assertions on fields that don't exist on the result type.
    // When result_is_simple, all field assertions operate on the scalar result directly.
    if !result_is_simple {
        if let Some(f) = &assertion.field {
            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
                let _ = writeln!(out, "\t// skipped: field '{f}' not available on result type");
                return;
            }
        }
    }

    let field_expr = if result_is_simple {
        // The result IS the value — field access is irrelevant.
        result_var.to_string()
    } else {
        match &assertion.field {
            Some(f) if !f.is_empty() => {
                // Use the local variable if the field was dereferenced above.
                if let Some(local_var) = optional_locals.get(f.as_str()) {
                    local_var.clone()
                } else {
                    field_resolver.accessor(f, "go", result_var)
                }
            }
            _ => result_var.to_string(),
        }
    };

    // Check if the field (after resolution) is optional, which means it's a pointer in Go.
    // Also check if a `.length` suffix's parent is optional (e.g., metadata.headings.length
    // where metadata.headings is optional → len() needs dereference).
    let is_optional = assertion
        .field
        .as_ref()
        .map(|f| {
            let resolved = field_resolver.resolve(f);
            let check_path = resolved
                .strip_suffix(".length")
                .or_else(|| resolved.strip_suffix(".count"))
                .or_else(|| resolved.strip_suffix(".size"))
                .unwrap_or(resolved);
            field_resolver.is_optional(check_path) && !optional_locals.contains_key(f.as_str())
        })
        .unwrap_or(false);

    // When field_expr is `len(X)` and X is an optional (pointer) field, rewrite to `len(*X)`
    // and we'll wrap with a nil guard in the assertion handlers.
    // However, slices are already nil-able and should not be dereferenced.
    let field_is_array_for_len = assertion
        .field
        .as_ref()
        .map(|f| {
            let resolved = field_resolver.resolve(f);
            let check_path = resolved
                .strip_suffix(".length")
                .or_else(|| resolved.strip_suffix(".count"))
                .or_else(|| resolved.strip_suffix(".size"))
                .unwrap_or(resolved);
            field_resolver.is_array(check_path)
        })
        .unwrap_or(false);
    let field_expr =
        if is_optional && field_expr.starts_with("len(") && field_expr.ends_with(')') && !field_is_array_for_len {
            let inner = &field_expr[4..field_expr.len() - 1];
            format!("len(*{inner})")
        } else {
            field_expr
        };
    // Build the nil-guard expression for the inner pointer (without len wrapper).
    let nil_guard_expr = if is_optional && field_expr.starts_with("len(*") {
        Some(field_expr[5..field_expr.len() - 1].to_string())
    } else {
        None
    };

    // For optional non-string fields that weren't dereferenced into locals,
    // we need to dereference the pointer in comparisons.
    // However, slices are already nil-able and should not be dereferenced.
    let field_is_slice = assertion
        .field
        .as_ref()
        .map(|f| field_resolver.is_array(field_resolver.resolve(f)))
        .unwrap_or(false);
    let deref_field_expr = if is_optional && !field_expr.starts_with("len(") && !field_is_slice {
        format!("*{field_expr}")
    } else {
        field_expr.clone()
    };

    // Detect array element access (e.g., `result.Assets[0].ContentHash`).
    // When the field_expr contains `[0]`, we must guard against an out-of-bounds
    // panic by checking that the array is non-empty first.
    // Extract the array slice expression (everything before `[0]`).
    let array_guard: Option<String> = if let Some(idx) = field_expr.find("[0]") {
        let mut array_expr = field_expr[..idx].to_string();
        if let Some(stripped) = array_expr.strip_prefix("len(") {
            array_expr = stripped.to_string();
        }
        Some(array_expr)
    } else {
        None
    };

    // Render the assertion into a temporary buffer first, then wrap with the array
    // bounds guard (if needed) by adding one extra level of indentation.
    let mut assertion_buf = String::new();
    let out_ref = &mut assertion_buf;

    match assertion.assertion_type.as_str() {
        "equals" => {
            if let Some(expected) = &assertion.value {
                let go_val = json_to_go(expected);
                // For string equality, trim whitespace to handle trailing newlines from the converter.
                if expected.is_string() {
                    // Wrap field expression with strings.TrimSpace() for string comparisons.
                    // Use string() cast to handle named string types (e.g. BatchStatus, FinishReason).
                    let trimmed_field = if is_optional && !field_expr.starts_with("len(") {
                        format!("strings.TrimSpace(string(*{field_expr}))")
                    } else {
                        format!("strings.TrimSpace(string({field_expr}))")
                    };
                    if is_optional && !field_expr.starts_with("len(") {
                        let _ = writeln!(out_ref, "\tif {field_expr} != nil && {trimmed_field} != {go_val} {{");
                    } else {
                        let _ = writeln!(out_ref, "\tif {trimmed_field} != {go_val} {{");
                    }
                } else if is_optional && !field_expr.starts_with("len(") {
                    let _ = writeln!(out_ref, "\tif {field_expr} != nil && {deref_field_expr} != {go_val} {{");
                } else {
                    let _ = writeln!(out_ref, "\tif {field_expr} != {go_val} {{");
                }
                let _ = writeln!(out_ref, "\t\tt.Errorf(\"equals mismatch: got %v\", {field_expr})");
                let _ = writeln!(out_ref, "\t}}");
            }
        }
        "contains" => {
            if let Some(expected) = &assertion.value {
                let go_val = json_to_go(expected);
                // Determine the "string view" of the field expression.
                // - []string (optional) → jsonString(field_expr) — Go slices are nil-able, no `*` needed
                // - *string → string(*field_expr)
                // - string → string(field_expr) (or just field_expr for plain strings)
                // - result_is_array (result_is_simple + array result) → jsonString(field_expr)
                let resolved_field = assertion.field.as_deref().unwrap_or("");
                let resolved_name = field_resolver.resolve(resolved_field);
                let field_is_array = result_is_array || field_resolver.is_array(resolved_name);
                let is_opt =
                    is_optional && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()));
                let field_for_contains = if is_opt && field_is_array {
                    // Go slices are nil-able directly — no pointer dereference needed.
                    format!("jsonString({field_expr})")
                } else if is_opt {
                    format!("fmt.Sprint(*{field_expr})")
                } else if field_is_array {
                    format!("jsonString({field_expr})")
                } else {
                    format!("fmt.Sprint({field_expr})")
                };
                if is_opt {
                    let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                    let _ = writeln!(out_ref, "\tif !strings.Contains({field_for_contains}, {go_val}) {{");
                    let _ = writeln!(
                        out_ref,
                        "\t\tt.Errorf(\"expected to contain %s, got %v\", {go_val}, {field_expr})"
                    );
                    let _ = writeln!(out_ref, "\t}}");
                    let _ = writeln!(out_ref, "\t}}");
                } else {
                    let _ = writeln!(out_ref, "\tif !strings.Contains({field_for_contains}, {go_val}) {{");
                    let _ = writeln!(
                        out_ref,
                        "\t\tt.Errorf(\"expected to contain %s, got %v\", {go_val}, {field_expr})"
                    );
                    let _ = writeln!(out_ref, "\t}}");
                }
            }
        }
        "contains_all" => {
            if let Some(values) = &assertion.values {
                let resolved_field = assertion.field.as_deref().unwrap_or("");
                let resolved_name = field_resolver.resolve(resolved_field);
                let field_is_array = result_is_array || field_resolver.is_array(resolved_name);
                let is_opt =
                    is_optional && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()));
                for val in values {
                    let go_val = json_to_go(val);
                    let field_for_contains = if is_opt && field_is_array {
                        // Go slices are nil-able directly — no pointer dereference needed.
                        format!("jsonString({field_expr})")
                    } else if is_opt {
                        format!("fmt.Sprint(*{field_expr})")
                    } else if field_is_array {
                        format!("jsonString({field_expr})")
                    } else {
                        format!("fmt.Sprint({field_expr})")
                    };
                    if is_opt {
                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                        let _ = writeln!(out_ref, "\tif !strings.Contains({field_for_contains}, {go_val}) {{");
                        let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected to contain %s\", {go_val})");
                        let _ = writeln!(out_ref, "\t}}");
                        let _ = writeln!(out_ref, "\t}}");
                    } else {
                        let _ = writeln!(out_ref, "\tif !strings.Contains({field_for_contains}, {go_val}) {{");
                        let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected to contain %s\", {go_val})");
                        let _ = writeln!(out_ref, "\t}}");
                    }
                }
            }
        }
        "not_contains" => {
            if let Some(expected) = &assertion.value {
                let go_val = json_to_go(expected);
                let resolved_field = assertion.field.as_deref().unwrap_or("");
                let resolved_name = field_resolver.resolve(resolved_field);
                let field_is_array = result_is_array || field_resolver.is_array(resolved_name);
                let is_opt =
                    is_optional && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()));
                let field_for_contains = if is_opt && field_is_array {
                    // Go slices are nil-able directly — no pointer dereference needed.
                    format!("jsonString({field_expr})")
                } else if is_opt {
                    format!("fmt.Sprint(*{field_expr})")
                } else if field_is_array {
                    format!("jsonString({field_expr})")
                } else {
                    format!("fmt.Sprint({field_expr})")
                };
                let _ = writeln!(out_ref, "\tif strings.Contains({field_for_contains}, {go_val}) {{");
                let _ = writeln!(
                    out_ref,
                    "\t\tt.Errorf(\"expected NOT to contain %s, got %v\", {go_val}, {field_expr})"
                );
                let _ = writeln!(out_ref, "\t}}");
            }
        }
        "not_empty" => {
            // For optional struct pointers (not arrays), just check != nil.
            // For optional slice/string pointers, check nil and len.
            let field_is_array = {
                let rf = assertion.field.as_deref().unwrap_or("");
                let rn = field_resolver.resolve(rf);
                field_resolver.is_array(rn)
            };
            if is_optional && !field_is_array {
                // Struct pointer: non-empty means not nil.
                let _ = writeln!(out_ref, "\tif {field_expr} == nil {{");
            } else if is_optional && field_is_slice {
                // Slice optional: Go slices are already nil-able — no dereference needed.
                let _ = writeln!(out_ref, "\tif {field_expr} == nil || len({field_expr}) == 0 {{");
            } else if is_optional {
                // Pointer-to-slice (*[]T): dereference then len.
                let _ = writeln!(out_ref, "\tif {field_expr} == nil || len(*{field_expr}) == 0 {{");
            } else if result_is_simple && result_is_array {
                // Simple array result ([]T) — direct slice, not a pointer; check length only.
                let _ = writeln!(out_ref, "\tif len({field_expr}) == 0 {{");
            } else {
                let _ = writeln!(out_ref, "\tif len({field_expr}) == 0 {{");
            }
            let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected non-empty value\")");
            let _ = writeln!(out_ref, "\t}}");
        }
        "is_empty" => {
            let field_is_array = {
                let rf = assertion.field.as_deref().unwrap_or("");
                let rn = field_resolver.resolve(rf);
                field_resolver.is_array(rn)
            };
            // Special case: result_is_simple && !result_is_array && no field means the result is a pointer.
            // Empty means nil.
            if result_is_simple && !result_is_array && assertion.field.as_ref().is_none_or(|f| f.is_empty()) {
                // Pointer result (not dereferenced): empty means nil.
                let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
            } else if is_optional && !field_is_array {
                // Struct pointer: empty means nil.
                let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
            } else if is_optional && field_is_slice {
                // Slice optional: Go slices are already nil-able — no dereference needed.
                let _ = writeln!(out_ref, "\tif {field_expr} != nil && len({field_expr}) != 0 {{");
            } else if is_optional {
                // Pointer-to-slice (*[]T): dereference then len.
                let _ = writeln!(out_ref, "\tif {field_expr} != nil && len(*{field_expr}) != 0 {{");
            } else {
                let _ = writeln!(out_ref, "\tif len({field_expr}) != 0 {{");
            }
            let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected empty value, got %v\", {field_expr})");
            let _ = writeln!(out_ref, "\t}}");
        }
        "contains_any" => {
            if let Some(values) = &assertion.values {
                let resolved_field = assertion.field.as_deref().unwrap_or("");
                let resolved_name = field_resolver.resolve(resolved_field);
                let field_is_array = field_resolver.is_array(resolved_name);
                let is_opt =
                    is_optional && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()));
                let field_for_contains = if is_opt && field_is_array {
                    // Go slices are nil-able directly — no pointer dereference needed.
                    format!("jsonString({field_expr})")
                } else if is_opt {
                    format!("fmt.Sprint(*{field_expr})")
                } else if field_is_array {
                    format!("jsonString({field_expr})")
                } else {
                    format!("fmt.Sprint({field_expr})")
                };
                let _ = writeln!(out_ref, "\t{{");
                let _ = writeln!(out_ref, "\t\tfound := false");
                for val in values {
                    let go_val = json_to_go(val);
                    let _ = writeln!(
                        out_ref,
                        "\t\tif strings.Contains({field_for_contains}, {go_val}) {{ found = true }}"
                    );
                }
                let _ = writeln!(out_ref, "\t\tif !found {{");
                let _ = writeln!(
                    out_ref,
                    "\t\t\tt.Errorf(\"expected to contain at least one of the specified values\")"
                );
                let _ = writeln!(out_ref, "\t\t}}");
                let _ = writeln!(out_ref, "\t}}");
            }
        }
        "greater_than" => {
            if let Some(val) = &assertion.value {
                let go_val = json_to_go(val);
                // Use `< N+1` instead of `<= N` to avoid golangci-lint sloppyLen
                // warning when N is 0 (len(x) <= 0 → len(x) < 1).
                // For optional (pointer) fields, dereference and guard with nil check.
                if is_optional {
                    let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                    if let Some(n) = val.as_u64() {
                        let next = n + 1;
                        let _ = writeln!(out_ref, "\t\tif {deref_field_expr} < {next} {{");
                    } else {
                        let _ = writeln!(out_ref, "\t\tif {deref_field_expr} <= {go_val} {{");
                    }
                    let _ = writeln!(
                        out_ref,
                        "\t\t\tt.Errorf(\"expected > {go_val}, got %v\", {deref_field_expr})"
                    );
                    let _ = writeln!(out_ref, "\t\t}}");
                    let _ = writeln!(out_ref, "\t}}");
                } else if let Some(n) = val.as_u64() {
                    let next = n + 1;
                    let _ = writeln!(out_ref, "\tif {field_expr} < {next} {{");
                    let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected > {go_val}, got %v\", {field_expr})");
                    let _ = writeln!(out_ref, "\t}}");
                } else {
                    let _ = writeln!(out_ref, "\tif {field_expr} <= {go_val} {{");
                    let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected > {go_val}, got %v\", {field_expr})");
                    let _ = writeln!(out_ref, "\t}}");
                }
            }
        }
        "less_than" => {
            if let Some(val) = &assertion.value {
                let go_val = json_to_go(val);
                let _ = writeln!(out_ref, "\tif {field_expr} >= {go_val} {{");
                let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected < {go_val}, got %v\", {field_expr})");
                let _ = writeln!(out_ref, "\t}}");
            }
        }
        "greater_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let go_val = json_to_go(val);
                if let Some(ref guard) = nil_guard_expr {
                    let _ = writeln!(out_ref, "\tif {guard} != nil {{");
                    let _ = writeln!(out_ref, "\t\tif {field_expr} < {go_val} {{");
                    let _ = writeln!(
                        out_ref,
                        "\t\t\tt.Errorf(\"expected >= {go_val}, got %v\", {field_expr})"
                    );
                    let _ = writeln!(out_ref, "\t\t}}");
                    let _ = writeln!(out_ref, "\t}}");
                } else if is_optional && !field_expr.starts_with("len(") {
                    // Optional pointer field: nil-guard and dereference before comparison.
                    let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                    let _ = writeln!(out_ref, "\t\tif {deref_field_expr} < {go_val} {{");
                    let _ = writeln!(
                        out_ref,
                        "\t\t\tt.Errorf(\"expected >= {go_val}, got %v\", {deref_field_expr})"
                    );
                    let _ = writeln!(out_ref, "\t\t}}");
                    let _ = writeln!(out_ref, "\t}}");
                } else {
                    let _ = writeln!(out_ref, "\tif {field_expr} < {go_val} {{");
                    let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected >= {go_val}, got %v\", {field_expr})");
                    let _ = writeln!(out_ref, "\t}}");
                }
            }
        }
        "less_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let go_val = json_to_go(val);
                let _ = writeln!(out_ref, "\tif {field_expr} > {go_val} {{");
                let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected <= {go_val}, got %v\", {field_expr})");
                let _ = writeln!(out_ref, "\t}}");
            }
        }
        "starts_with" => {
            if let Some(expected) = &assertion.value {
                let go_val = json_to_go(expected);
                let field_for_prefix = if is_optional
                    && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()))
                {
                    format!("string(*{field_expr})")
                } else {
                    format!("string({field_expr})")
                };
                let _ = writeln!(out_ref, "\tif !strings.HasPrefix({field_for_prefix}, {go_val}) {{");
                let _ = writeln!(
                    out_ref,
                    "\t\tt.Errorf(\"expected to start with %s, got %v\", {go_val}, {field_expr})"
                );
                let _ = writeln!(out_ref, "\t}}");
            }
        }
        "count_min" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    if is_optional {
                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                        // Slices are value types in Go — use len(slice) not len(*slice).
                        let len_expr = if field_is_slice {
                            format!("len({field_expr})")
                        } else {
                            format!("len(*{field_expr})")
                        };
                        let _ = writeln!(
                            out_ref,
                            "\t\tassert.GreaterOrEqual(t, {len_expr}, {n}, \"expected at least {n} elements\")"
                        );
                        let _ = writeln!(out_ref, "\t}}");
                    } else {
                        let _ = writeln!(
                            out_ref,
                            "\tassert.GreaterOrEqual(t, len({field_expr}), {n}, \"expected at least {n} elements\")"
                        );
                    }
                }
            }
        }
        "count_equals" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    if is_optional {
                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                        // Slices are value types in Go — use len(slice) not len(*slice).
                        let len_expr = if field_is_slice {
                            format!("len({field_expr})")
                        } else {
                            format!("len(*{field_expr})")
                        };
                        let _ = writeln!(
                            out_ref,
                            "\t\tassert.Equal(t, {len_expr}, {n}, \"expected exactly {n} elements\")"
                        );
                        let _ = writeln!(out_ref, "\t}}");
                    } else {
                        let _ = writeln!(
                            out_ref,
                            "\tassert.Equal(t, len({field_expr}), {n}, \"expected exactly {n} elements\")"
                        );
                    }
                }
            }
        }
        "is_true" => {
            if is_optional {
                let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                let _ = writeln!(out_ref, "\t\tassert.True(t, *{field_expr}, \"expected true\")");
                let _ = writeln!(out_ref, "\t}}");
            } else {
                let _ = writeln!(out_ref, "\tassert.True(t, {field_expr}, \"expected true\")");
            }
        }
        "is_false" => {
            if is_optional {
                let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                let _ = writeln!(out_ref, "\t\tassert.False(t, *{field_expr}, \"expected false\")");
                let _ = writeln!(out_ref, "\t}}");
            } else {
                let _ = writeln!(out_ref, "\tassert.False(t, {field_expr}, \"expected false\")");
            }
        }
        "method_result" => {
            if let Some(method_name) = &assertion.method {
                let info = build_go_method_call(result_var, method_name, assertion.args.as_ref(), import_alias);
                let check = assertion.check.as_deref().unwrap_or("is_true");
                // For pointer-returning functions, dereference with `*`. Value-returning
                // functions (e.g., NodeInfo field access) are used directly.
                let deref_expr = if info.is_pointer {
                    format!("*{}", info.call_expr)
                } else {
                    info.call_expr.clone()
                };
                match check {
                    "equals" => {
                        if let Some(val) = &assertion.value {
                            if val.is_boolean() {
                                if val.as_bool() == Some(true) {
                                    let _ = writeln!(out_ref, "\tassert.True(t, {deref_expr}, \"expected true\")");
                                } else {
                                    let _ = writeln!(out_ref, "\tassert.False(t, {deref_expr}, \"expected false\")");
                                }
                            } else {
                                // Apply type cast to numeric literals when the method returns
                                // a typed uint (e.g., *uint) to avoid reflect.DeepEqual
                                // mismatches between int and uint in testify's assert.Equal.
                                let go_val = if let Some(cast) = info.value_cast {
                                    if val.is_number() {
                                        format!("{cast}({})", json_to_go(val))
                                    } else {
                                        json_to_go(val)
                                    }
                                } else {
                                    json_to_go(val)
                                };
                                let _ = writeln!(
                                    out_ref,
                                    "\tassert.Equal(t, {go_val}, {deref_expr}, \"method_result equals assertion failed\")"
                                );
                            }
                        }
                    }
                    "is_true" => {
                        let _ = writeln!(out_ref, "\tassert.True(t, {deref_expr}, \"expected true\")");
                    }
                    "is_false" => {
                        let _ = writeln!(out_ref, "\tassert.False(t, {deref_expr}, \"expected false\")");
                    }
                    "greater_than_or_equal" => {
                        if let Some(val) = &assertion.value {
                            let n = val.as_u64().unwrap_or(0);
                            // Use the value_cast type if available (e.g., uint for named_children_count).
                            let cast = info.value_cast.unwrap_or("uint");
                            let _ = writeln!(
                                out_ref,
                                "\tassert.GreaterOrEqual(t, {deref_expr}, {cast}({n}), \"expected >= {n}\")"
                            );
                        }
                    }
                    "count_min" => {
                        if let Some(val) = &assertion.value {
                            let n = val.as_u64().unwrap_or(0);
                            let _ = writeln!(
                                out_ref,
                                "\tassert.GreaterOrEqual(t, len({deref_expr}), {n}, \"expected at least {n} elements\")"
                            );
                        }
                    }
                    "contains" => {
                        if let Some(val) = &assertion.value {
                            let go_val = json_to_go(val);
                            let _ = writeln!(
                                out_ref,
                                "\tassert.Contains(t, {deref_expr}, {go_val}, \"expected result to contain value\")"
                            );
                        }
                    }
                    "is_error" => {
                        let _ = writeln!(out_ref, "\t{{");
                        let _ = writeln!(out_ref, "\t\t_, methodErr := {}", info.call_expr);
                        let _ = writeln!(out_ref, "\t\tassert.Error(t, methodErr)");
                        let _ = writeln!(out_ref, "\t}}");
                    }
                    other_check => {
                        panic!("Go e2e generator: unsupported method_result check type: {other_check}");
                    }
                }
            } else {
                panic!("Go e2e generator: method_result assertion missing 'method' field");
            }
        }
        "min_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    if is_optional {
                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                        let _ = writeln!(
                            out_ref,
                            "\t\tassert.GreaterOrEqual(t, len(*{field_expr}), {n}, \"expected length >= {n}\")"
                        );
                        let _ = writeln!(out_ref, "\t}}");
                    } else if field_expr.starts_with("len(") {
                        let _ = writeln!(
                            out_ref,
                            "\tassert.GreaterOrEqual(t, {field_expr}, {n}, \"expected length >= {n}\")"
                        );
                    } else {
                        let _ = writeln!(
                            out_ref,
                            "\tassert.GreaterOrEqual(t, len({field_expr}), {n}, \"expected length >= {n}\")"
                        );
                    }
                }
            }
        }
        "max_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    if is_optional {
                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
                        let _ = writeln!(
                            out_ref,
                            "\t\tassert.LessOrEqual(t, len(*{field_expr}), {n}, \"expected length <= {n}\")"
                        );
                        let _ = writeln!(out_ref, "\t}}");
                    } else if field_expr.starts_with("len(") {
                        let _ = writeln!(
                            out_ref,
                            "\tassert.LessOrEqual(t, {field_expr}, {n}, \"expected length <= {n}\")"
                        );
                    } else {
                        let _ = writeln!(
                            out_ref,
                            "\tassert.LessOrEqual(t, len({field_expr}), {n}, \"expected length <= {n}\")"
                        );
                    }
                }
            }
        }
        "ends_with" => {
            if let Some(expected) = &assertion.value {
                let go_val = json_to_go(expected);
                let field_for_suffix = if is_optional
                    && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()))
                {
                    format!("string(*{field_expr})")
                } else {
                    format!("string({field_expr})")
                };
                let _ = writeln!(out_ref, "\tif !strings.HasSuffix({field_for_suffix}, {go_val}) {{");
                let _ = writeln!(
                    out_ref,
                    "\t\tt.Errorf(\"expected to end with %s, got %v\", {go_val}, {field_expr})"
                );
                let _ = writeln!(out_ref, "\t}}");
            }
        }
        "matches_regex" => {
            if let Some(expected) = &assertion.value {
                let go_val = json_to_go(expected);
                let field_for_regex = if is_optional
                    && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()))
                {
                    format!("*{field_expr}")
                } else {
                    field_expr.clone()
                };
                let _ = writeln!(
                    out_ref,
                    "\tassert.Regexp(t, {go_val}, {field_for_regex}, \"expected value to match regex\")"
                );
            }
        }
        "not_error" => {
            // Already handled by the `if err != nil` check above.
        }
        "error" => {
            // Handled at the test function level.
        }
        other => {
            panic!("Go e2e generator: unsupported assertion type: {other}");
        }
    }

    // If the assertion accesses an array element via [0], wrap the generated code in a
    // bounds check to prevent an index-out-of-range panic when the array is empty.
    if let Some(ref arr) = array_guard {
        if !assertion_buf.is_empty() {
            let _ = writeln!(out, "\tif len({arr}) > 0 {{");
            // Re-indent each line by one additional tab level.
            for line in assertion_buf.lines() {
                let _ = writeln!(out, "\t{line}");
            }
            let _ = writeln!(out, "\t}}");
        }
    } else {
        out.push_str(&assertion_buf);
    }
}

/// Metadata about the return type of a Go method call for `method_result` assertions.
struct GoMethodCallInfo {
    /// The call expression string.
    call_expr: String,
    /// Whether the return type is a pointer (needs `*` dereference for value comparison).
    is_pointer: bool,
    /// Optional Go type cast to apply to numeric literal values in `equals` assertions
    /// (e.g., `"uint"` so that `0` becomes `uint(0)` to match `*uint` deref type).
    value_cast: Option<&'static str>,
}

/// Build a Go call expression for a `method_result` assertion on a tree-sitter Tree.
///
/// Maps method names to the appropriate Go function calls, matching the Go binding API
/// in `packages/go/binding.go`. Returns a [`GoMethodCallInfo`] describing the call and
/// its return type characteristics.
///
/// Return types by method:
/// - `has_error_nodes`, `contains_node_type` → `*bool` (pointer)
/// - `error_count` → `*uint` (pointer, value_cast = "uint")
/// - `tree_to_sexp` → `*string` (pointer)
/// - `root_node_type` → `string` via `RootNodeInfo(tree).Kind` (value)
/// - `named_children_count` → `uint` via `RootNodeInfo(tree).NamedChildCount` (value, value_cast = "uint")
/// - `find_nodes_by_type` → `*[]NodeInfo` (pointer to slice)
/// - `run_query` → `(*[]QueryMatch, error)` (pointer + error; use `is_error` check type)
fn build_go_method_call(
    result_var: &str,
    method_name: &str,
    args: Option<&serde_json::Value>,
    import_alias: &str,
) -> GoMethodCallInfo {
    match method_name {
        "root_node_type" => GoMethodCallInfo {
            call_expr: format!("{import_alias}.RootNodeInfo({result_var}).Kind"),
            is_pointer: false,
            value_cast: None,
        },
        "named_children_count" => GoMethodCallInfo {
            call_expr: format!("{import_alias}.RootNodeInfo({result_var}).NamedChildCount"),
            is_pointer: false,
            value_cast: Some("uint"),
        },
        "has_error_nodes" => GoMethodCallInfo {
            call_expr: format!("{import_alias}.TreeHasErrorNodes({result_var})"),
            is_pointer: true,
            value_cast: None,
        },
        "error_count" | "tree_error_count" => GoMethodCallInfo {
            call_expr: format!("{import_alias}.TreeErrorCount({result_var})"),
            is_pointer: true,
            value_cast: Some("uint"),
        },
        "tree_to_sexp" => GoMethodCallInfo {
            call_expr: format!("{import_alias}.TreeToSexp({result_var})"),
            is_pointer: true,
            value_cast: None,
        },
        "contains_node_type" => {
            let node_type = args
                .and_then(|a| a.get("node_type"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            GoMethodCallInfo {
                call_expr: format!("{import_alias}.TreeContainsNodeType({result_var}, \"{node_type}\")"),
                is_pointer: true,
                value_cast: None,
            }
        }
        "find_nodes_by_type" => {
            let node_type = args
                .and_then(|a| a.get("node_type"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            GoMethodCallInfo {
                call_expr: format!("{import_alias}.FindNodesByType({result_var}, \"{node_type}\")"),
                is_pointer: true,
                value_cast: None,
            }
        }
        "run_query" => {
            let query_source = args
                .and_then(|a| a.get("query_source"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let language = args
                .and_then(|a| a.get("language"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let query_lit = go_string_literal(query_source);
            let lang_lit = go_string_literal(language);
            // RunQuery returns (*[]QueryMatch, error) — use is_error check type.
            GoMethodCallInfo {
                call_expr: format!("{import_alias}.RunQuery({result_var}, {lang_lit}, {query_lit}, []byte(source))"),
                is_pointer: false,
                value_cast: None,
            }
        }
        other => {
            let method_pascal = other.to_upper_camel_case();
            GoMethodCallInfo {
                call_expr: format!("{result_var}.{method_pascal}()"),
                is_pointer: false,
                value_cast: None,
            }
        }
    }
}

/// Convert a `serde_json::Value` to a Go literal string.
/// Recursively convert a JSON value for Go struct unmarshalling.
///
/// The Go binding's `ConversionOptions` struct uses:
/// - `snake_case` JSON field tags (e.g. `"code_block_style"` not `"codeBlockStyle"`)
/// - lowercase/snake_case string values for enums (e.g. `"indented"`, `"atx_closed"`)
///
/// Fixture JSON uses camelCase keys and PascalCase enum values (Python/TS conventions).
/// This function remaps both so the generated Go tests can unmarshal correctly.
fn convert_json_for_go(value: serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::Object(map) => {
            let new_map: serde_json::Map<String, serde_json::Value> = map
                .into_iter()
                .map(|(k, v)| (camel_to_snake_case(&k), convert_json_for_go(v)))
                .collect();
            serde_json::Value::Object(new_map)
        }
        serde_json::Value::Array(arr) => {
            // Check if this is a byte array (array of integers 0-255).
            // If so, encode as base64 string for Go json.Unmarshal compatibility.
            if is_byte_array(&arr) {
                let bytes: Vec<u8> = arr
                    .iter()
                    .filter_map(|v| v.as_u64().and_then(|n| if n <= 255 { Some(n as u8) } else { None }))
                    .collect();
                // Encode bytes as base64 for Go json.Unmarshal (Go expects []byte as base64 strings)
                let encoded = base64_encode(&bytes);
                serde_json::Value::String(encoded)
            } else {
                serde_json::Value::Array(arr.into_iter().map(convert_json_for_go).collect())
            }
        }
        serde_json::Value::String(s) => {
            // Convert PascalCase enum values to snake_case.
            // Only convert values that look like PascalCase (start with uppercase, no spaces).
            serde_json::Value::String(pascal_to_snake_case(&s))
        }
        other => other,
    }
}

/// Check if an array looks like a byte array (all elements are integers 0-255).
fn is_byte_array(arr: &[serde_json::Value]) -> bool {
    if arr.is_empty() {
        return false;
    }
    arr.iter().all(|v| {
        if let serde_json::Value::Number(n) = v {
            n.is_u64() && n.as_u64().is_some_and(|u| u <= 255)
        } else {
            false
        }
    })
}

/// Encode bytes as base64 string (standard alphabet without padding in this output,
/// though Go's json.Unmarshal handles both).
fn base64_encode(bytes: &[u8]) -> String {
    const TABLE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut result = String::new();
    let mut i = 0;

    while i + 2 < bytes.len() {
        let b1 = bytes[i];
        let b2 = bytes[i + 1];
        let b3 = bytes[i + 2];

        result.push(TABLE[(b1 >> 2) as usize] as char);
        result.push(TABLE[(((b1 & 0x03) << 4) | (b2 >> 4)) as usize] as char);
        result.push(TABLE[(((b2 & 0x0f) << 2) | (b3 >> 6)) as usize] as char);
        result.push(TABLE[(b3 & 0x3f) as usize] as char);

        i += 3;
    }

    // Handle remaining bytes
    if i < bytes.len() {
        let b1 = bytes[i];
        result.push(TABLE[(b1 >> 2) as usize] as char);

        if i + 1 < bytes.len() {
            let b2 = bytes[i + 1];
            result.push(TABLE[(((b1 & 0x03) << 4) | (b2 >> 4)) as usize] as char);
            result.push(TABLE[((b2 & 0x0f) << 2) as usize] as char);
            result.push('=');
        } else {
            result.push(TABLE[((b1 & 0x03) << 4) as usize] as char);
            result.push_str("==");
        }
    }

    result
}

/// Convert a camelCase or PascalCase string to snake_case.
fn camel_to_snake_case(s: &str) -> String {
    let mut result = String::new();
    let mut prev_upper = false;
    for (i, c) in s.char_indices() {
        if c.is_uppercase() {
            if i > 0 && !prev_upper {
                result.push('_');
            }
            result.push(c.to_lowercase().next().unwrap_or(c));
            prev_upper = true;
        } else {
            if prev_upper && i > 1 {
                // Handles sequences like "URLPath" → "url_path": insert _ before last uppercase
                // when transitioning from a run of uppercase back to lowercase.
                // This is tricky — use simple approach: detect Aa pattern.
            }
            result.push(c);
            prev_upper = false;
        }
    }
    result
}

/// Convert a PascalCase string to snake_case (for enum values).
///
/// Only converts if the string looks like PascalCase (starts uppercase, no spaces/underscores).
/// Values that are already lowercase/snake_case are returned unchanged.
fn pascal_to_snake_case(s: &str) -> String {
    // Skip conversion for strings that already contain underscores, spaces, or start lowercase.
    let first_char = s.chars().next();
    if first_char.is_none() || !first_char.unwrap().is_uppercase() || s.contains('_') || s.contains(' ') {
        return s.to_string();
    }
    camel_to_snake_case(s)
}

/// Map an `ArgMapping.element_type` to a Go slice type. Used for `json_object` args
/// whose fixture value is a JSON array. The element type is wrapped in `[]…` so an
/// element of `String` becomes `[]string` and `Vec<String>` becomes `[][]string`.
fn element_type_to_go_slice(element_type: Option<&str>, import_alias: &str) -> String {
    let elem = element_type.unwrap_or("String").trim();
    let go_elem = rust_type_to_go(elem, import_alias);
    format!("[]{go_elem}")
}

/// Map a small subset of Rust scalar / `Vec<T>` types to their Go equivalents.
/// For unknown types, qualify with the import alias (e.g., "kreuzberg.BatchBytesItem").
fn rust_type_to_go(rust: &str, import_alias: &str) -> String {
    let trimmed = rust.trim();
    if let Some(inner) = trimmed.strip_prefix("Vec<").and_then(|s| s.strip_suffix('>')) {
        return format!("[]{}", rust_type_to_go(inner, import_alias));
    }
    match trimmed {
        "String" | "&str" | "str" => "string".to_string(),
        "bool" => "bool".to_string(),
        "f32" => "float32".to_string(),
        "f64" => "float64".to_string(),
        "i8" => "int8".to_string(),
        "i16" => "int16".to_string(),
        "i32" => "int32".to_string(),
        "i64" | "isize" => "int64".to_string(),
        "u8" => "uint8".to_string(),
        "u16" => "uint16".to_string(),
        "u32" => "uint32".to_string(),
        "u64" | "usize" => "uint64".to_string(),
        _ => format!("{import_alias}.{trimmed}"),
    }
}

fn json_to_go(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => go_string_literal(s),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Null => "nil".to_string(),
        // For complex types, serialize to JSON string and pass as literal.
        other => go_string_literal(&other.to_string()),
    }
}

// ---------------------------------------------------------------------------
// Visitor generation
// ---------------------------------------------------------------------------

/// Derive a unique, exported Go struct name for a visitor from a fixture ID.
///
/// E.g. `visitor_continue_default` → `visitorContinueDefault` (unexported, avoids
/// polluting the exported API of the test package while still being package-level).
fn visitor_struct_name(fixture_id: &str) -> String {
    use heck::ToUpperCamelCase;
    // Use UpperCamelCase so Go treats it as exported — required for method sets.
    format!("testVisitor{}", fixture_id.to_upper_camel_case())
}

/// Emit a package-level Go struct declaration and all its visitor methods.
///
/// The struct embeds `BaseVisitor` to satisfy all interface methods not
/// explicitly overridden by the fixture callbacks.
fn emit_go_visitor_struct(
    out: &mut String,
    struct_name: &str,
    visitor_spec: &crate::fixture::VisitorSpec,
    import_alias: &str,
) {
    let _ = writeln!(out, "type {struct_name} struct{{");
    let _ = writeln!(out, "\t{import_alias}.BaseVisitor");
    let _ = writeln!(out, "}}");
    for (method_name, action) in &visitor_spec.callbacks {
        emit_go_visitor_method(out, struct_name, method_name, action, import_alias);
    }
}

/// Emit a Go visitor method for a callback action on the named struct.
fn emit_go_visitor_method(
    out: &mut String,
    struct_name: &str,
    method_name: &str,
    action: &CallbackAction,
    import_alias: &str,
) {
    let camel_method = method_to_camel(method_name);
    // Parameter signatures must exactly match the htmltomarkdown.Visitor interface.
    // Optional fields use pointer types (*string, *uint32, etc.) to indicate nil-ability.
    let params = match method_name {
        "visit_link" => format!("_ {import_alias}.NodeContext, href string, text string, title *string"),
        "visit_image" => format!("_ {import_alias}.NodeContext, src string, alt string, title *string"),
        "visit_heading" => format!("_ {import_alias}.NodeContext, level uint32, text string, id *string"),
        "visit_code_block" => format!("_ {import_alias}.NodeContext, lang *string, code string"),
        "visit_code_inline"
        | "visit_strong"
        | "visit_emphasis"
        | "visit_strikethrough"
        | "visit_underline"
        | "visit_subscript"
        | "visit_superscript"
        | "visit_mark"
        | "visit_button"
        | "visit_summary"
        | "visit_figcaption"
        | "visit_definition_term"
        | "visit_definition_description" => format!("_ {import_alias}.NodeContext, text string"),
        "visit_text" => format!("_ {import_alias}.NodeContext, text string"),
        "visit_list_item" => {
            format!("_ {import_alias}.NodeContext, ordered bool, marker string, text string")
        }
        "visit_blockquote" => format!("_ {import_alias}.NodeContext, content string, depth uint"),
        "visit_table_row" => format!("_ {import_alias}.NodeContext, cells []string, isHeader bool"),
        "visit_custom_element" => format!("_ {import_alias}.NodeContext, tagName string, html string"),
        "visit_form" => format!("_ {import_alias}.NodeContext, action *string, method *string"),
        "visit_input" => {
            format!("_ {import_alias}.NodeContext, inputType string, name *string, value *string")
        }
        "visit_audio" | "visit_video" | "visit_iframe" => {
            format!("_ {import_alias}.NodeContext, src *string")
        }
        "visit_details" => format!("_ {import_alias}.NodeContext, open bool"),
        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
            format!("_ {import_alias}.NodeContext, output string")
        }
        "visit_list_start" => format!("_ {import_alias}.NodeContext, ordered bool"),
        "visit_list_end" => format!("_ {import_alias}.NodeContext, ordered bool, output string"),
        _ => format!("_ {import_alias}.NodeContext"),
    };

    let _ = writeln!(
        out,
        "func (v *{struct_name}) {camel_method}({params}) {import_alias}.VisitResult {{"
    );
    match action {
        CallbackAction::Skip => {
            let _ = writeln!(out, "\treturn {import_alias}.VisitResultSkip()");
        }
        CallbackAction::Continue => {
            let _ = writeln!(out, "\treturn {import_alias}.VisitResultContinue()");
        }
        CallbackAction::PreserveHtml => {
            let _ = writeln!(out, "\treturn {import_alias}.VisitResultPreserveHTML()");
        }
        CallbackAction::Custom { output } => {
            let escaped = go_string_literal(output);
            let _ = writeln!(out, "\treturn {import_alias}.VisitResultCustom({escaped})");
        }
        CallbackAction::CustomTemplate { template } => {
            // Convert {var} placeholders to %s format verbs and collect arg names.
            // E.g. `QUOTE: "{text}"` → fmt.Sprintf("QUOTE: \"%s\"", text)
            //
            // For pointer-typed params (e.g. `src *string`), dereference with `*`
            // — the test fixtures always supply a non-nil value for methods that
            // fire a custom template, so this is safe in practice.
            let ptr_params = go_visitor_ptr_params(method_name);
            let (fmt_str, fmt_args) = template_to_sprintf(template, &ptr_params);
            let escaped_fmt = go_string_literal(&fmt_str);
            if fmt_args.is_empty() {
                let _ = writeln!(out, "\treturn {import_alias}.VisitResultCustom({escaped_fmt})");
            } else {
                let args_str = fmt_args.join(", ");
                let _ = writeln!(
                    out,
                    "\treturn {import_alias}.VisitResultCustom(fmt.Sprintf({escaped_fmt}, {args_str}))"
                );
            }
        }
    }
    let _ = writeln!(out, "}}");
}

/// Return the set of camelCase parameter names that are pointer types (`*string`) for a
/// given visitor method name.  Used to dereference pointers in template `fmt.Sprintf` calls.
fn go_visitor_ptr_params(method_name: &str) -> std::collections::HashSet<&'static str> {
    match method_name {
        "visit_link" => ["title"].into(),
        "visit_image" => ["title"].into(),
        "visit_heading" => ["id"].into(),
        "visit_code_block" => ["lang"].into(),
        "visit_form" => ["action", "method"].into(),
        "visit_input" => ["name", "value"].into(),
        "visit_audio" | "visit_video" | "visit_iframe" => ["src"].into(),
        _ => std::collections::HashSet::new(),
    }
}

/// Convert a `{var}` template string into a `fmt.Sprintf` format string and argument list.
///
/// For example, `QUOTE: "{text}"` becomes `("QUOTE: \"%s\"", vec!["text"])`.
///
/// Placeholder names in the template use snake_case (matching fixture field names); they
/// are converted to Go camelCase parameter names using `go_param_name` so they match the
/// generated visitor method signatures (e.g. `{input_type}` → `inputType`).
///
/// `ptr_params` — camelCase names of parameters that are `*string`; these are
/// dereferenced with `*` when used as `fmt.Sprintf` arguments.  The fixtures that
/// use `custom_template` on pointer-param methods always supply a non-nil value.
fn template_to_sprintf(template: &str, ptr_params: &std::collections::HashSet<&str>) -> (String, Vec<String>) {
    let mut fmt_str = String::new();
    let mut args: Vec<String> = Vec::new();
    let mut chars = template.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '{' {
            // Collect placeholder name until '}'.
            let mut name = String::new();
            for inner in chars.by_ref() {
                if inner == '}' {
                    break;
                }
                name.push(inner);
            }
            fmt_str.push_str("%s");
            // Convert snake_case placeholder to Go camelCase to match method param names.
            let go_name = go_param_name(&name);
            // Dereference pointer params so fmt.Sprintf receives a string value.
            let arg_expr = if ptr_params.contains(go_name.as_str()) {
                format!("*{go_name}")
            } else {
                go_name
            };
            args.push(arg_expr);
        } else {
            fmt_str.push(c);
        }
    }
    (fmt_str, args)
}

/// Convert snake_case method names to Go camelCase.
fn method_to_camel(snake: &str) -> String {
    use heck::ToUpperCamelCase;
    snake.to_upper_camel_case()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{CallConfig, E2eConfig};
    use crate::field_access::FieldResolver;
    use crate::fixture::{Assertion, Fixture};

    fn make_fixture(id: &str) -> Fixture {
        Fixture {
            id: id.to_string(),
            category: None,
            description: "test fixture".to_string(),
            tags: vec![],
            skip: None,
            env: None,
            call: None,
            input: serde_json::Value::Null,
            mock_response: Some(crate::fixture::MockResponse {
                status: 200,
                body: Some(serde_json::Value::Null),
                stream_chunks: None,
                headers: std::collections::HashMap::new(),
            }),
            source: String::new(),
            http: None,
            assertions: vec![Assertion {
                assertion_type: "not_error".to_string(),
                ..Default::default()
            }],
            visitor: None,
        }
    }

    /// snake_case function names in `[e2e.call]` must be routed through `to_go_name`
    /// so the emitted Go call uses the idiomatic CamelCase (e.g. `CleanExtractedText`
    /// instead of `clean_extracted_text`).
    #[test]
    fn test_go_method_name_uses_go_casing() {
        let e2e_config = E2eConfig {
            call: CallConfig {
                function: "clean_extracted_text".to_string(),
                module: "github.com/example/mylib".to_string(),
                result_var: "result".to_string(),
                returns_result: true,
                ..CallConfig::default()
            },
            ..E2eConfig::default()
        };

        let fixture = make_fixture("basic_text");
        let resolver = FieldResolver::new(
            &std::collections::HashMap::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
            &std::collections::HashSet::new(),
        );
        let mut out = String::new();
        render_test_function(&mut out, &fixture, "kreuzberg", &resolver, &e2e_config);

        assert!(
            out.contains("kreuzberg.CleanExtractedText("),
            "expected Go-cased method name 'CleanExtractedText', got:\n{out}"
        );
        assert!(
            !out.contains("kreuzberg.clean_extracted_text("),
            "must not emit raw snake_case method name, got:\n{out}"
        );
    }
}