alef 0.22.16

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

use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use crate::core::hash::{self, CommentStyle};
use crate::core::template_versions::pub_dev;
use crate::e2e::codegen::resolve_field;
use crate::e2e::config::E2eConfig;
use crate::e2e::escape::sanitize_filename;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::{Assertion, Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
use anyhow::Result;
use heck::ToLowerCamelCase;
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

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

/// Dart e2e code generator.
pub struct DartE2eCodegen;

impl E2eCodegen for DartE2eCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        enums: &[crate::core::ir::EnumDef],
    ) -> 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 package config.
        let dart_pkg = e2e_config.resolve_package("dart");
        let pkg_name = dart_pkg
            .as_ref()
            .and_then(|p| p.name.as_ref())
            .cloned()
            .unwrap_or_else(|| config.dart_pubspec_name());
        let pkg_path = dart_pkg
            .as_ref()
            .and_then(|p| p.path.as_ref())
            .cloned()
            .unwrap_or_else(|| "../../packages/dart".to_string());
        let pkg_version = dart_pkg
            .as_ref()
            .and_then(|p| p.version.as_ref())
            .cloned()
            .or_else(|| config.resolved_version())
            .unwrap_or_else(|| "0.1.0".to_string());

        // Generate pubspec.yaml with http dependency for HTTP client tests.
        files.push(GeneratedFile {
            path: output_base.join("pubspec.yaml"),
            content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
            generated_header: false,
        });

        // Generate dart_test.yaml to limit parallelism — the SUT uses keep-alive
        // connections and gets overwhelmed when test files run in parallel.
        files.push(GeneratedFile {
            path: output_base.join("dart_test.yaml"),
            content: concat!(
                "# Generated by alef — DO NOT EDIT.\n",
                "# Run test files sequentially to avoid overwhelming the SUT with\n",
                "# concurrent keep-alive connections.\n",
                "concurrency: 1\n",
            )
            .to_string(),
            generated_header: false,
        });

        // Check if any fixture is an HTTP test (needs app harness).
        let has_http_fixtures = groups.iter().any(|g| g.fixtures.iter().any(|f| f.is_http_test()));

        // Generate app_harness.dart when using server-pattern (HTTP fixtures).
        if has_http_fixtures {
            files.push(GeneratedFile {
                path: output_base.join("app_harness.dart"),
                content: render_app_harness(groups, e2e_config, &pkg_name),
                generated_header: true,
            });
        }

        let test_base = output_base.join("test");

        // One test file per fixture group.
        let bridge_class = config.dart_bridge_class_name();

        // FRB places its generated dart code under `lib/src/{module_name}_bridge_generated/`,
        // where `module_name` is the snake_cased crate name.
        // This is independent of the pubspec `name` (which may be a short alias).
        let frb_module_name = config.name.replace('-', "_");

        // Methods declared as `stub_methods` in `[crates.dart]` cannot be bridged through
        // FRB and have `unimplemented!()` bodies on the Rust side. Emitting e2e tests for
        // these fixtures would result in `PanicException` at run-time. Filter them out
        // here so the dart e2e suite mirrors the actual runtime surface of the binding.
        let dart_stub_methods: std::collections::HashSet<String> = config
            .dart
            .as_ref()
            .map(|d| d.stub_methods.iter().cloned().collect())
            .unwrap_or_default();

        // Build the Dart stringy field classification map for aggregating text
        // accessors in Vec<T> contains assertions.
        let dart_first_class_map = build_dart_first_class_map(type_defs, enums, e2e_config);

        for group in groups {
            let active: Vec<&Fixture> = group
                .fixtures
                .iter()
                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
                .filter(|f| {
                    let call_config = e2e_config.resolve_call_for_fixture(
                        f.call.as_deref(),
                        &f.id,
                        &f.resolved_category(),
                        &f.tags,
                        &f.input,
                    );
                    let resolved_function = call_config
                        .overrides
                        .get(lang)
                        .and_then(|o| o.function.as_ref())
                        .cloned()
                        .unwrap_or_else(|| call_config.function.clone());
                    !dart_stub_methods.contains(&resolved_function)
                })
                .collect();

            if active.is_empty() {
                continue;
            }

            let filename = format!("{}_test.dart", sanitize_filename(&group.category));
            let content = render_test_file(
                &group.category,
                &active,
                e2e_config,
                lang,
                &pkg_name,
                &frb_module_name,
                &bridge_class,
                &dart_first_class_map,
                &config.adapters,
                config,
                type_defs,
            );
            files.push(GeneratedFile {
                path: test_base.join(filename),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

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

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

fn render_pubspec(
    pkg_name: &str,
    pkg_path: &str,
    pkg_version: &str,
    dep_mode: crate::e2e::config::DependencyMode,
) -> String {
    let test_ver = pub_dev::TEST_PACKAGE;
    let http_ver = pub_dev::HTTP_PACKAGE;

    let dep_block = match dep_mode {
        crate::e2e::config::DependencyMode::Registry => {
            // Only add ^ prefix if version doesn't already start with a constraint operator
            let constraint = if pkg_version.starts_with('^')
                || pkg_version.starts_with('~')
                || pkg_version.starts_with('>')
                || pkg_version.starts_with('<')
                || pkg_version.starts_with('=')
            {
                pkg_version.to_string()
            } else {
                format!("^{pkg_version}")
            };
            format!("  {pkg_name}: {constraint}")
        }
        crate::e2e::config::DependencyMode::Local => {
            format!("  {pkg_name}:\n    path: {pkg_path}")
        }
    };

    let sdk = crate::core::template_versions::toolchain::DART_SDK_CONSTRAINT;
    format!(
        r#"name: e2e_dart
version: 0.1.0
publish_to: none

environment:
  sdk: "{sdk}"

dependencies:
{dep_block}

dev_dependencies:
  test: {test_ver}
  http: {http_ver}
"#
    )
}

pub(crate) fn render_app_harness(groups: &[FixtureGroup], e2e_config: &E2eConfig, pkg_name: &str) -> String {
    // Collect all HTTP fixtures from all groups.
    let mut fixtures_map = serde_json::Map::new();

    for group in groups {
        for fixture in &group.fixtures {
            if let Some(http) = &fixture.http {
                let mut fixture_obj = serde_json::Map::new();

                let mut http_obj = serde_json::Map::new();

                // handler: route, method, body_schema
                let mut handler_obj = serde_json::Map::new();
                handler_obj.insert("route".to_string(), serde_json::json!(http.handler.route));
                handler_obj.insert("method".to_string(), serde_json::json!(http.handler.method.as_str()));
                if let Some(body_schema) = &http.handler.body_schema {
                    handler_obj.insert("body_schema".to_string(), body_schema.clone());
                } else {
                    handler_obj.insert("body_schema".to_string(), serde_json::Value::Null);
                }
                http_obj.insert("handler".to_string(), serde_json::Value::Object(handler_obj));

                // expected_response: status_code, body, headers
                let mut response_obj = serde_json::Map::new();
                response_obj.insert(
                    "status_code".to_string(),
                    serde_json::json!(http.expected_response.status_code),
                );
                if let Some(body) = &http.expected_response.body {
                    response_obj.insert("body".to_string(), body.clone());
                } else {
                    response_obj.insert("body".to_string(), serde_json::Value::Null);
                }

                let headers: serde_json::Map<String, serde_json::Value> = http
                    .expected_response
                    .headers
                    .iter()
                    .map(|(k, v)| (k.clone(), serde_json::json!(v)))
                    .collect();
                response_obj.insert("headers".to_string(), serde_json::Value::Object(headers));

                http_obj.insert("expected_response".to_string(), serde_json::Value::Object(response_obj));

                fixture_obj.insert("http".to_string(), serde_json::Value::Object(http_obj));
                fixtures_map.insert(fixture.id.clone(), serde_json::Value::Object(fixture_obj));
            }
        }
    }

    let fixtures_json = serde_json::to_string(&fixtures_map).unwrap_or_else(|_| "{}".to_string());

    // Derive the bridge module name from the package name:
    // e.g. "my_pkg" → "my_pkg_bridge_generated"
    let bridge_module = format!("{pkg_name}_bridge_generated");

    // Render using the Jinja template.
    let ctx = minijinja::context! {
        fixtures_json => fixtures_json,
        pkg_name => pkg_name,
        bridge_module => bridge_module,
        host => &e2e_config.harness.host,
        port => e2e_config.harness.port,
    };
    crate::e2e::template_env::render("dart/app_harness.dart.jinja", ctx)
}

#[allow(clippy::too_many_arguments)]
fn render_test_file(
    category: &str,
    fixtures: &[&Fixture],
    e2e_config: &E2eConfig,
    lang: &str,
    pkg_name: &str,
    frb_module_name: &str,
    bridge_class: &str,
    dart_first_class_map: &crate::e2e::field_access::DartFirstClassMap,
    adapters: &[crate::core::config::extras::AdapterConfig],
    config: &ResolvedCrateConfig,
    type_defs: &[crate::core::ir::TypeDef],
) -> String {
    let mut out = String::new();
    out.push_str(&hash::header(CommentStyle::DoubleSlash));
    // Suppress unused_local_variable: `final result = await api.method(...)` is
    // emitted for every test case; tests that only check for absence of errors
    // do not consume `result`, triggering this dart-analyze warning.
    out.push_str("// ignore_for_file: unused_local_variable\n\n");

    // Check if any fixture needs the http package (HTTP server tests).
    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());

    // Check if any fixture needs Uint8List (trait_bridge byte args/returns).
    let has_batch_byte_items = fixtures.iter().any(|f| {
        let call_config =
            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
        f.resolved_args(call_config).iter().any(|a| {
            a.arg_type == "test_backend" // trait_bridge stubs may use Uint8List in method params
        })
    });

    // Detect whether any fixture uses file_path or bytes args — if so, setUpAll must chdir
    // to the test_documents directory so that relative paths like "docx/fake.docx" resolve.
    // Mirrors the Ruby/Python conftest and Swift setUp patterns.
    let needs_chdir = fixtures.iter().any(|f| {
        if f.is_http_test() {
            return false;
        }
        let call_config =
            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
        f.resolved_args(call_config)
            .iter()
            .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
    });

    // Detect whether any non-HTTP fixture uses a json_object arg that resolves to a JSON array —
    // those are materialized via `jsonDecode` at test-run time and cast to `List<String>`.
    // Handle args themselves no longer require `jsonDecode` since they construct the config via
    // the FRB-generated `createCrawlConfigFromJson(json:)` helper which accepts the JSON string
    // directly. The variable name is kept as `has_handle_args` for downstream stability.
    let has_handle_args = fixtures.iter().any(|f| {
        if f.is_http_test() {
            return false;
        }
        let call_config =
            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
        call_config
            .args
            .iter()
            .any(|a| a.arg_type == "json_object" && super::resolve_field(&f.input, &a.field).is_array())
    });

    // Detect whether any fixture uses a PageAction array argument (for interact calls).
    // PageAction and ScrollDirection types must be emitted in the test helper code only if used.
    let has_page_action = fixtures.iter().any(|f| {
        if f.is_http_test() {
            return false;
        }
        let call_config =
            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
        f.resolved_args(call_config).iter().any(|a| {
            a.element_type.as_deref() == Some("PageAction") && super::resolve_field(&f.input, &a.field).is_array()
        })
    });

    // Collect plugin trait types used in test_backend arguments. These types must be imported
    // from the main package (e.g., DocumentExtractor, OcrBackend, etc.) so test stubs can extend them.
    let used_trait_types: std::collections::HashSet<String> = fixtures
        .iter()
        .flat_map(|f| {
            if f.is_http_test() {
                return vec![];
            }
            let call_config = e2e_config.resolve_call_for_fixture(
                f.call.as_deref(),
                &f.id,
                &f.resolved_category(),
                &f.tags,
                &f.input,
            );
            f.resolved_args(call_config)
                .iter()
                .filter_map(|a| {
                    if a.arg_type == "test_backend" {
                        a.trait_name.clone()
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>()
        })
        .collect();

    // Non-HTTP fixtures that build a mock-server URL still reference `Platform.environment`
    // (from `dart:io`). This applies to `mock_url` and `mock_url_list` args and to fixtures
    // routed through a `client_factory` (per-call override or per-language override) that
    // derives `_mockUrl` inline. Without this, the generated tests fail to compile with
    // `Error: Undefined name 'Platform'`.
    let lang_client_factory = e2e_config
        .call
        .overrides
        .get(lang)
        .and_then(|o| o.client_factory.as_deref())
        .is_some();
    let has_mock_url_refs = lang_client_factory
        || fixtures.iter().any(|f| {
            if f.is_http_test() {
                return false;
            }
            let call_config = e2e_config.resolve_call_for_fixture(
                f.call.as_deref(),
                &f.id,
                &f.resolved_category(),
                &f.tags,
                &f.input,
            );
            if call_config
                .args
                .iter()
                .any(|a| a.arg_type == "mock_url" || a.arg_type == "mock_url_list")
            {
                return true;
            }
            call_config
                .overrides
                .get(lang)
                .and_then(|o| o.client_factory.as_deref())
                .is_some()
        });

    let _ = writeln!(out, "import 'package:test/test.dart';");
    // `dart:io` provides HttpClient/SocketException (HTTP fixtures), Platform/Directory
    // (file-path/bytes fixtures requiring chdir), and Platform.environment (mock-url
    // fixtures). Skip the import when none of these are in play — unconditional emission
    // triggers `unused_import` warnings.
    if has_http_fixtures || needs_chdir || has_mock_url_refs {
        let _ = writeln!(out, "import 'dart:io';");
    }
    if has_batch_byte_items {
        let _ = writeln!(out, "import 'dart:typed_data';");
    }
    let _ = writeln!(out, "import 'package:{pkg_name}/{pkg_name}.dart';");
    // Import plugin trait types used in test_backend arguments so stubs can extend them.
    for trait_type in &used_trait_types {
        let _ = writeln!(out, "import 'package:{pkg_name}/{pkg_name}.dart' show {trait_type};");
    }
    // RustLib is the flutter_rust_bridge entrypoint; must be initialized before any FRB call.
    // FRB places its generated dart sources under `lib/src/{module_name}_bridge_generated/`,
    // where `module_name` is the snake_cased crate name (independent of the pubspec `name`,
    // which may be a short alias). `RustLib` lives in `frb_generated.dart` and
    // is not re-exported by the FRB barrel `lib.dart`, so we import it directly.
    let _ = writeln!(
        out,
        "import 'package:{pkg_name}/src/{frb_module_name}_bridge_generated/frb_generated.dart' show RustLib;"
    );
    // dart:async provides Completer (HTTP response handling + the mock-server
    // spawn harness, which awaits a Completer for the startup URL line).
    if has_http_fixtures || has_mock_url_refs {
        let _ = writeln!(out, "import 'dart:async';");
    }
    // dart:convert provides jsonDecode for handle-arg engine construction, HTTP response parsing,
    // and PageAction array deserialization, plus utf8/LineSplitter for decoding the mock-server's
    // startup stdout (MOCK_SERVER_URL= / MOCK_SERVERS=) in the spawn harness.
    if has_http_fixtures || has_handle_args || has_page_action || has_mock_url_refs {
        let _ = writeln!(out, "import 'dart:convert';");
    }
    let _ = writeln!(out);

    // Emit file-level HTTP client and serialization mutex.
    //
    // The shared HttpClient reuses keep-alive connections to minimize TCP overhead.
    // The mutex (_lock) ensures requests are serialized within the file so the
    // connection pool is not exercised concurrently by dart:test's async runner.
    //
    // _withRetry wraps the entire request closure with one automatic retry on
    // transient connection errors (keep-alive connections can be silently closed
    // by the server just as the client tries to reuse them).
    if has_http_fixtures {
        let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out);
        let _ = writeln!(out, "var _lock = Future<void>.value();");
        let _ = writeln!(out);
        let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
        let _ = writeln!(out, "  final current = _lock;");
        let _ = writeln!(out, "  final next = Completer<void>();");
        let _ = writeln!(out, "  _lock = next.future;");
        let _ = writeln!(out, "  try {{");
        let _ = writeln!(out, "    await current;");
        let _ = writeln!(out, "    return await fn();");
        let _ = writeln!(out, "  }} finally {{");
        let _ = writeln!(out, "    next.complete();");
        let _ = writeln!(out, "  }}");
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
        // The `fn` here is the full request closure. Transient connection errors
        // (`SocketException` / `HttpException: Connection reset by peer`) happen rarely
        // but non-deterministically when the local mock server drops a connection mid-flight;
        // a single retry is not always enough, so retry several times with a short backoff,
        // recreating the HttpClient each time to drop any poisoned pooled connection. The
        // final attempt is outside the catch so a genuine, persistent failure still surfaces.
        let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
        let _ = writeln!(out, "  for (var attempt = 0; attempt < 5; attempt++) {{");
        let _ = writeln!(out, "    try {{");
        let _ = writeln!(out, "      return await fn();");
        let _ = writeln!(out, "    }} on SocketException {{");
        let _ = writeln!(out, "      _httpClient.close(force: true);");
        let _ = writeln!(out, "      _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out, "    }} on HttpException {{");
        let _ = writeln!(out, "      _httpClient.close(force: true);");
        let _ = writeln!(out, "      _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out, "    }}");
        let _ = writeln!(
            out,
            "    await Future<void>.delayed(Duration(milliseconds: 25 * (attempt + 1)));"
        );
        let _ = writeln!(out, "  }}");
        let _ = writeln!(out, "  return await fn();");
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
    }

    let _ = writeln!(out, "// E2e tests for category: {category}");
    let _ = writeln!(out);

    // Emit a helper function to normalize enum values to their serde wire format.
    // Dart enums' .toString() returns "EnumName.variant" but fixtures use serde wire format
    // (e.g. "stop" for FinishReason.stop, "tool_calls" for FinishReason.toolCalls).
    // This helper handles enum-to-wire conversion by calling .name (which gives the Dart
    // variant name like "toolCalls") and converting back to snake_case for multi-word variants.
    let _ = writeln!(out, "String _alefE2eText(Object? value) {{");
    let _ = writeln!(out, "  if (value == null) return '';");
    let _ = writeln!(
        out,
        "  // Check if it's an enum by examining its toString representation."
    );
    let _ = writeln!(out, "  final str = value.toString();");
    let _ = writeln!(out, "  if (str.contains('.')) {{");
    let _ = writeln!(
        out,
        "    // Enum.toString() returns 'EnumName.variantName'. Extract the variant name."
    );
    let _ = writeln!(out, "    final parts = str.split('.');");
    let _ = writeln!(out, "    if (parts.length == 2) {{");
    let _ = writeln!(out, "      final variantName = parts[1];");
    let _ = writeln!(
        out,
        "      // Convert camelCase variant names to snake_case for serde compatibility."
    );
    let _ = writeln!(out, "      // E.g. 'toolCalls' -> 'tool_calls', 'stop' -> 'stop'.");
    let _ = writeln!(out, "      return _camelToSnake(variantName);");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out, "  }}");
    let _ = writeln!(out, "  return str;");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);

    // Helper to convert camelCase to snake_case.
    let _ = writeln!(out, "String _camelToSnake(String camel) {{");
    let _ = writeln!(out, "  final buffer = StringBuffer();");
    let _ = writeln!(out, "  for (int i = 0; i < camel.length; i++) {{");
    let _ = writeln!(out, "    final char = camel[i];");
    let _ = writeln!(out, "    if (char.contains(RegExp(r'[A-Z]'))) {{");
    let _ = writeln!(out, "      if (i > 0) buffer.write('_');");
    let _ = writeln!(out, "      buffer.write(char.toLowerCase());");
    let _ = writeln!(out, "    }} else {{");
    let _ = writeln!(out, "      buffer.write(char);");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out, "  }}");
    let _ = writeln!(out, "  return buffer.toString();");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);

    // Only emit _parsePageAction if any fixture uses PageAction arrays.
    if has_page_action {
        let _ = writeln!(out, "PageAction _parsePageAction(Map<String, dynamic> json) {{");
        let _ = writeln!(out, "  final actionType = json['type'] as String?;");
        let _ = writeln!(out, "  switch (actionType) {{");
        let _ = writeln!(out, "    case 'click':");
        let _ = writeln!(
            out,
            "      return PageAction.click(selector: json['selector'] as String);"
        );
        let _ = writeln!(out, "    case 'type':");
        let _ = writeln!(out, "      return PageAction.typeText(");
        let _ = writeln!(out, "        selector: json['selector'] as String,");
        let _ = writeln!(out, "        text: json['text'] as String,");
        let _ = writeln!(out, "      );");
        let _ = writeln!(out, "    case 'press':");
        let _ = writeln!(out, "      return PageAction.press(");
        let _ = writeln!(out, "        key: json['key'] as String,");
        let _ = writeln!(out, "      );");
        let _ = writeln!(out, "    case 'scroll':");
        let _ = writeln!(out, "      return PageAction.scroll(");
        let _ = writeln!(out, "        direction: ScrollDirection.down,");
        let _ = writeln!(out, "        selector: json['selector'] as String? ?? '',");
        let _ = writeln!(out, "        amount: json['amount'] as int? ?? 0,");
        let _ = writeln!(out, "      );");
        let _ = writeln!(out, "    case 'wait':");
        let _ = writeln!(out, "      return PageAction.wait(");
        let _ = writeln!(out, "        milliseconds: json['timeout_ms'] as int? ?? 0,");
        let _ = writeln!(out, "        selector: json['selector'] as String,");
        let _ = writeln!(out, "      );");
        let _ = writeln!(out, "    case 'screenshot':");
        let _ = writeln!(
            out,
            "      return PageAction.screenshot(fullPage: json['full_page'] as bool? ?? false);"
        );
        let _ = writeln!(out, "    case 'executeJs':");
        let _ = writeln!(
            out,
            "      return PageAction.executeJs(script: json['script'] as String);"
        );
        let _ = writeln!(out, "    case 'scrape':");
        let _ = writeln!(out, "      return const PageAction.scrape();");
        let _ = writeln!(out, "    default:");
        let _ = writeln!(
            out,
            "      throw UnsupportedError('Unknown PageAction type: $actionType');"
        );
        let _ = writeln!(out, "  }}");
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
    }

    // Whether this test file must spawn the SUT app harness. True for direct HTTP
    // fixtures and for any fixture that derives a URL from `SUT_URL`
    // (mock_url args / client_factory). `package:test` has no cross-file global
    // setup, so each file spawns its own server in `setUpAll` and tears it down
    // in `tearDownAll`; `dart_test.yaml` pins `concurrency: 1` so at most one
    // server runs at a time. A pre-set `SUT_URL` environment variable (external CI
    // orchestration) short-circuits the spawn. Mirrors the Python conftest /
    // Ruby spec_helper / Java MockServerListener pattern.
    let needs_sut_spawn = has_http_fixtures || has_mock_url_refs;

    // Top-level SUT app harness state. `Platform.environment` is read-only in Dart,
    // so the spawned server's URL is held in mutable globals and read through
    // helper functions (rather than re-reading the environment) by the test
    // bodies below.
    if needs_sut_spawn {
        let _ = writeln!(out, "Process? _sutProcess;");
        let _ = writeln!(out, "String? _spawnedSutUrl;");
        let _ = writeln!(out);
        // Prefer `MOCK_SERVER_URL` (exported by `scripts/e2e/run-with-mock-server.sh`
        // and by `alef test --e2e` mock-server bootstrap) so the tests hit the
        // ephemeral port the alef-spawned mock-server picked; fall back to a
        // pre-set `SUT_URL` (external CI orchestration that runs a custom harness)
        // or the legacy `localhost:8008` only if neither env var is set.
        let _ = writeln!(
            out,
            "String _sutUrl() => _spawnedSutUrl ?? Platform.environment['MOCK_SERVER_URL'] ?? Platform.environment['SUT_URL'] ?? 'http://localhost:8008';"
        );
        let _ = writeln!(out);
    }

    // First pass: collect module-level test stub class definitions BEFORE void main().
    // Dart does not allow class definitions inside functions, so we must emit them
    // at the module level before void main().
    let mut test_stub_classes = String::new();
    for fixture in fixtures {
        collect_dart_test_stub_classes(&mut test_stub_classes, fixture, e2e_config, config, type_defs);
    }
    if !test_stub_classes.is_empty() {
        out.push_str(&test_stub_classes);
        let _ = writeln!(out);
    }

    let _ = writeln!(out, "void main() {{");

    // Emit setUpAll to initialize the flutter_rust_bridge before any test runs and,
    // when fixtures load files by path, chdir to test_documents so that relative
    // paths like "docx/fake.docx" resolve correctly.
    //
    // The test_documents directory lives two levels above e2e/dart/ (at the repo root).
    // The FIXTURES_DIR environment variable can override this for CI environments.
    let _ = writeln!(out, "  setUpAll(() async {{");
    let _ = writeln!(out, "    await RustLib.init();");
    if needs_chdir {
        let test_docs_path = e2e_config.test_documents_relative_from(0);
        let _ = writeln!(
            out,
            "    final _testDocs = Platform.environment['FIXTURES_DIR'] ?? '{test_docs_path}';"
        );
        let _ = writeln!(out, "    final _dir = Directory(_testDocs);");
        let _ = writeln!(out, "    if (_dir.existsSync()) Directory.current = _dir;");
    }
    if needs_sut_spawn {
        render_dart_sut_spawn(&mut out);
    }
    let _ = writeln!(out, "  }});");
    let _ = writeln!(out);

    // Always emit tearDownAll to dispose of RustLib singleton and close resources.
    // RustLib is initialized in setUpAll and must be cleaned up after all tests.
    // RustLib.dispose() is always called to ensure proper cleanup (required for non-empty body).
    let _ = writeln!(out, "  tearDownAll(() async {{");
    let _ = writeln!(out, "    RustLib.dispose();");
    if has_http_fixtures {
        let _ = writeln!(out, "    _httpClient.close(force: true);");
    }
    if needs_sut_spawn {
        let _ = writeln!(out, "    final proc = _sutProcess;");
        let _ = writeln!(out, "    if (proc != null) {{");
        let _ = writeln!(out, "      proc.kill();");
        let _ = writeln!(out, "      await proc.exitCode;");
        let _ = writeln!(out, "    }}");
    }
    let _ = writeln!(out, "  }});");
    let _ = writeln!(out);

    for fixture in fixtures {
        render_test_case(
            &mut out,
            fixture,
            DartTestCaseContext {
                e2e_config,
                lang,
                bridge_class,
                dart_first_class_map,
                adapters,
                config,
                type_defs,
            },
        );
    }

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

/// Emit the `setUpAll` body that spawns the app_harness.dart subprocess and
/// captures its URL into the top-level `_spawnedSutUrl` global.
///
/// The app_harness binds an ephemeral `127.0.0.1:8008` and prints
/// `SUT_URL=http://127.0.0.1:8008` on stdout once it is listening.
/// A pre-set `SUT_URL` environment variable (external CI orchestration)
/// short-circuits the spawn. Mirrors the Python conftest /
/// Ruby spec_helper / Java MockServerListener spawn pattern.
///
/// Emitted inside an `async` `setUpAll`; the harness lives at
/// `app_harness.dart` relative to `Directory.current`, which points to the test_app /
/// e2e suite root because the Taskfile / harness invokes `dart test` from there.
/// `Platform.script` is unusable here because `dart test` stages test files to a tmpdir
/// (`/var/folders/.../T/dart_test.kernel.<random>/test.dart_<n>.dill`); relative
/// resolves against that URI escape the source tree entirely.
fn render_dart_sut_spawn(out: &mut String) {
    // Skip spawning any server when either `MOCK_SERVER_URL` (alef e2e
    // wrapper / `scripts/e2e/run-with-mock-server.sh`) or `SUT_URL` (external
    // CI orchestration) is already set — the parent process has already
    // arranged the HTTP target the tests should hit.
    let _ = writeln!(
        out,
        "    if (Platform.environment['MOCK_SERVER_URL'] == null && Platform.environment['SUT_URL'] == null) {{"
    );
    let _ = writeln!(
        out,
        "      final _harness = Directory.current.uri.resolve('app_harness.dart').toFilePath();"
    );
    let _ = writeln!(out, "      if (File(_harness).existsSync()) {{");
    let _ = writeln!(
        out,
        "        _sutProcess = await Process.start('dart', ['run', _harness], mode: ProcessStartMode.normal);"
    );
    // A single `listen` keeps draining stdout after the startup line is seen
    // (so a full pipe never blocks the child); the Completer resolves once the
    // URL has been captured. `Process.stdout` is a single-subscription stream,
    // so it must be consumed exactly once — re-reading `.stdout` would throw.
    let _ = writeln!(out, "        final _ready = Completer<void>();");
    let _ = writeln!(out, "        _sutProcess!.stdout");
    let _ = writeln!(out, "            .transform(utf8.decoder)");
    let _ = writeln!(out, "            .transform(const LineSplitter())");
    let _ = writeln!(out, "            .listen((_line) {{");
    let _ = writeln!(out, "          final _trimmed = _line.trim();");
    let _ = writeln!(out, "          if (_trimmed.startsWith('SUT_URL=')) {{");
    let _ = writeln!(
        out,
        "            _spawnedSutUrl = _trimmed.substring('SUT_URL='.length);"
    );
    let _ = writeln!(out, "            if (!_ready.isCompleted) _ready.complete();");
    let _ = writeln!(out, "          }}");
    let _ = writeln!(out, "        }}, onDone: () {{");
    let _ = writeln!(out, "          if (!_ready.isCompleted) _ready.complete();");
    let _ = writeln!(out, "        }});");
    let _ = writeln!(
        out,
        "        await _ready.future.timeout(const Duration(seconds: 15), onTimeout: () {{}});"
    );
    // When app_harness.dart is absent this is a mock-server test (not a server-pattern
    // test). Build the alef-generated mock-server binary if it is missing, then spawn
    // it and capture `MOCK_SERVER_URL=` from its stdout — the same sentinel line that
    // Ruby spec_helper and the `alef test-apps run` orchestrator read.
    // Resolve paths relative to the test file to locate the mock-server project.
    let _ = writeln!(out, "      }} else {{");
    let _ = writeln!(
        out,
        "        // Standalone mock-server mode: build if missing, then spawn."
    );
    let _ = writeln!(
        out,
        "        final _mockBin = Directory.current.uri.resolve('../rust/target/release/mock-server').toFilePath();"
    );
    let _ = writeln!(
        out,
        "        final _mockManifest = Directory.current.uri.resolve('../rust/Cargo.toml').toFilePath();"
    );
    let _ = writeln!(out, "        if (!File(_mockBin).existsSync()) {{");
    let _ = writeln!(
        out,
        "          final _build = await Process.run('cargo', ['build', '--release', '--manifest-path', _mockManifest, '--bin', 'mock-server']);"
    );
    let _ = writeln!(
        out,
        "          if (_build.exitCode != 0) throw StateError('mock-server build failed: ${{_build.stderr}}');"
    );
    let _ = writeln!(out, "        }}");
    let _ = writeln!(
        out,
        "        final _fixturesDir = Directory.current.uri.resolve('../../fixtures').toFilePath();"
    );
    let _ = writeln!(
        out,
        "        _sutProcess = await Process.start(_mockBin, [_fixturesDir], mode: ProcessStartMode.normal);"
    );
    let _ = writeln!(out, "        final _ready2 = Completer<void>();");
    let _ = writeln!(out, "        _sutProcess!.stdout");
    let _ = writeln!(out, "            .transform(utf8.decoder)");
    let _ = writeln!(out, "            .transform(const LineSplitter())");
    let _ = writeln!(out, "            .listen((_line) {{");
    let _ = writeln!(out, "          final _trimmed = _line.trim();");
    let _ = writeln!(out, "          if (_trimmed.startsWith('MOCK_SERVER_URL=')) {{");
    let _ = writeln!(
        out,
        "            _spawnedSutUrl = _trimmed.substring('MOCK_SERVER_URL='.length);"
    );
    let _ = writeln!(out, "            if (!_ready2.isCompleted) _ready2.complete();");
    let _ = writeln!(out, "          }}");
    let _ = writeln!(out, "        }}, onDone: () {{");
    let _ = writeln!(out, "          if (!_ready2.isCompleted) _ready2.complete();");
    let _ = writeln!(out, "        }});");
    let _ = writeln!(
        out,
        "        await _ready2.future.timeout(const Duration(seconds: 60), onTimeout: () {{}});"
    );
    let _ = writeln!(out, "      }}");
    let _ = writeln!(out, "    }}");
}

/// Collect module-level test stub class definitions for Dart.
/// Dart does not allow class definitions inside functions, so we must emit them
/// at the module level before void main(). This function checks if the fixture
/// uses a test_backend argument and if so, emits the class definition.
fn collect_dart_test_stub_classes(
    out: &mut String,
    fixture: &Fixture,
    _e2e_config: &E2eConfig,
    config: &ResolvedCrateConfig,
    type_defs: &[crate::core::ir::TypeDef],
) {
    // HTTP fixtures do not use test_backend.
    if fixture.is_http_test() {
        return;
    }

    // Check fixture.args directly (not call_config.args, which is empty for trait-bridge calls).
    // The fixture JSON defines the actual arguments including test_backend definitions.
    for arg_def in &fixture.args {
        if arg_def.arg_type != "test_backend" {
            continue;
        }
        if let Some(trait_name) = &arg_def.trait_name {
            if let Some(trait_bridge) = config.trait_bridges.iter().find(|tb| tb.trait_name == *trait_name) {
                let methods: Vec<&crate::core::ir::MethodDef> = type_defs
                    .iter()
                    .find(|t| t.name == *trait_name)
                    .map(|t| t.methods.iter().collect())
                    .unwrap_or_default();
                let emission = emit_test_backend(trait_bridge, &methods, fixture);
                // Emit only the class definition at module-level.
                let _ = writeln!(out, "{}", emission.setup_block);
                let _ = writeln!(out);
            }
        }
    }
}

struct DartTestCaseContext<'a> {
    e2e_config: &'a E2eConfig,
    lang: &'a str,
    bridge_class: &'a str,
    dart_first_class_map: &'a crate::e2e::field_access::DartFirstClassMap,
    adapters: &'a [crate::core::config::extras::AdapterConfig],
    config: &'a ResolvedCrateConfig,
    type_defs: &'a [crate::core::ir::TypeDef],
}

fn render_test_case(out: &mut String, fixture: &Fixture, context: DartTestCaseContext<'_>) {
    let DartTestCaseContext {
        e2e_config,
        lang,
        bridge_class,
        dart_first_class_map,
        adapters,
        config,
        type_defs,
    } = context;
    // HTTP fixtures: hit the mock server.
    if let Some(http) = &fixture.http {
        render_http_test_case(out, fixture, http);
        return;
    }

    // Non-HTTP fixtures: render a call-based test using the resolved call config.
    let call_config = e2e_config.resolve_call_for_fixture(
        fixture.call.as_deref(),
        &fixture.id,
        &fixture.resolved_category(),
        &fixture.tags,
        &fixture.input,
    );
    let call_recipe = crate::e2e::codegen::recipe::E2eCallRecipe::resolve(lang, fixture, call_config, type_defs);
    // Build per-call field resolver using the effective field sets for this call.
    let call_field_resolver = FieldResolver::new_with_dart_first_class(
        e2e_config.effective_fields(call_config),
        e2e_config.effective_fields_optional(call_config),
        e2e_config.effective_result_fields(call_config),
        e2e_config.effective_fields_array(call_config),
        e2e_config.effective_fields_method_calls(call_config),
        &HashMap::new(),
        dart_first_class_map.clone(),
    )
    .with_dart_root_type(dart_call_result_type(call_config).or_else(|| dart_first_class_map.root_type.clone()));
    let field_resolver = &call_field_resolver;
    let enum_fields_base = e2e_config.effective_fields_enum(call_config);

    // Merge per-language enum_fields from the Dart override into the effective enum set so that
    // fields like "status" (BatchStatus on BatchObject) are treated as enum-typed
    // even when they are not globally listed in fields_enum (they are context-
    // dependent — BatchStatus on BatchObject but plain String on ResponseObject).
    let effective_enum_fields: std::collections::HashSet<String> = {
        let dart_overrides = call_config.overrides.get("dart");
        if let Some(overrides) = dart_overrides {
            let mut merged = enum_fields_base.clone();
            merged.extend(overrides.enum_fields.keys().cloned());
            merged
        } else {
            enum_fields_base.clone()
        }
    };
    let enum_fields = &effective_enum_fields;
    let call_overrides = call_config.overrides.get(lang);
    let mut function_name = call_overrides
        .and_then(|o| o.function.as_ref())
        .cloned()
        .unwrap_or_else(|| call_config.function.clone());
    // Convert snake_case function names to camelCase for Dart conventions.
    function_name = function_name
        .split('_')
        .enumerate()
        .map(|(i, part)| {
            if i == 0 {
                part.to_string()
            } else {
                let mut chars = part.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                }
            }
        })
        .collect::<Vec<_>>()
        .join("");
    let result_var = &call_config.result_var;
    let description = escape_dart(&fixture.description);
    let fixture_id = &fixture.id;
    // `is_async` retained for future use (e.g. non-FRB backends); unused with FRB since
    // all wrappers return Future<T>.
    let _is_async = call_overrides.and_then(|o| o.r#async).unwrap_or(call_config.r#async);

    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
    let is_streaming = crate::e2e::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
    // `result_is_simple = true` means the dart return is a scalar/bytes value
    // (e.g. `Uint8List` for speech/file_content), not a struct. Field-based
    // assertions like `audio.not_empty` collapse to whole-result checks so we
    // don't emit `result.audio` against a `Uint8List` receiver.
    let result_is_simple = call_overrides.is_some_and(|o| o.result_is_simple) || call_config.result_is_simple;

    // Resolve options_type and options_via from per-fixture → per-call → default.
    // These drive how `json_object` args are constructed:
    //   options_via = "from_json" — call `createTypeNameFromJson(json: r'...')` bridge
    //                               helper and pass the result as a named parameter `req:`.
    //   All other values (or absent) — existing behaviour (batch arrays, config objects,
    //   generic JSON arrays, or nothing).
    let options_type: Option<&str> = call_recipe.options_type;
    let options_via: &str = call_recipe.options_via;

    // Build argument list from fixture.input and resolved args (fixture.args or call_config.args).
    // Use `resolve_field` (respects the `field` path like "input.data") rather than
    // looking up by `arg_def.name` directly — the name and the field key may differ.
    //
    // For `extract_file_sync` / `extract_file` fixtures that omit `mime_type`,
    // derive the MIME from the path extension so `extractBytesSync`/`extractBytes`
    // can be called (both require an explicit MIME type).
    let file_path_for_mime: Option<&str> = fixture
        .resolved_args(call_config)
        .iter()
        .find(|a| a.arg_type == "file_path")
        .and_then(|a| resolve_field(&fixture.input, &a.field).as_str());

    // Detect whether this call converts a file_path arg to bytes at test-run time.
    // Most dart fixtures take the bytes path historically (`extractFile` →
    // `extractBytes`), but source-code files need the path-based variant to reach
    // CodeExtractor's `extract_file` implementation (its `extract_bytes` path
    // requires a shebang line for language detection, so `code/hello.py` fed as
    // bytes errors out with "Cannot detect programming language from content").
    // We therefore keep the bytes remap for ordinary file types and skip it for
    // source-code extensions, letting the binding's own `extractFileSync` /
    // `extractFile` accept the path directly.
    let has_file_path_arg = fixture
        .resolved_args(call_config)
        .iter()
        .any(|a| a.arg_type == "file_path");
    let routes_to_source_code = file_path_for_mime
        .and_then(mime_from_extension)
        .map(|m| m == "text/x-source-code")
        .unwrap_or(false);
    // Apply the remap only when no per-fixture dart override has already specified the
    // function — if the fixture author set a dart-specific function name we trust it.
    let caller_supplied_override = call_overrides.and_then(|o| o.function.as_ref()).is_some();
    if has_file_path_arg && !caller_supplied_override && !routes_to_source_code {
        function_name = match function_name.as_str() {
            "extractFile" => "extractBytes".to_string(),
            "extractFileSync" => "extractBytesSync".to_string(),
            other => other.to_string(),
        };
    }

    // Resolve client_factory early so the per-arg builders below can pick the
    // calling convention. When `client_factory` is set the test calls methods on
    // an FRB-generated client instance (e.g. sample-llm's `retrieveFile`), and FRB
    // emits every non-`config` parameter as a Dart named-required parameter. When
    // unset the call routes through a hand-written facade whose required args are
    // positional. See the `"string"` arg handler below.
    let client_factory_for_args: Option<&str> =
        call_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())
        });

    // Resolve adapter request type for streaming methods.
    let adapter = adapters.iter().find(|a| a.name == call_config.function.as_str());
    let adapter_request_type: Option<String> = adapter
        .and_then(|a| a.request_type.as_deref())
        .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());

    // setup_lines holds per-test statements that must precede the main call:
    // engine construction (handle args) and URL building (mock_url args).
    let mut setup_lines: Vec<String> = Vec::new();
    let mut args = Vec::new();

    for arg_def in call_recipe.args {
        match arg_def.arg_type.as_str() {
            "mock_url" => {
                let name = arg_def.name.clone();
                setup_lines.push(format!(r#"final {name} = "${{_sutUrl()}}/fixtures/{fixture_id}";"#));
                // For streaming adapters with a request_type, wrap the URL in the request constructor.
                if let Some(ref req_type) = adapter_request_type {
                    let req_var = format!("{}Req", name);
                    // Extract just the type name (last segment after ::).
                    let req_type_name = req_type.rsplit("::").next().unwrap_or(req_type.as_str());
                    setup_lines.push(format!("final {req_var} = {req_type_name}(url: {name});"));
                    args.push(req_var);
                } else {
                    args.push(name);
                }
                continue;
            }
            "handle" => {
                let name = arg_def.name.clone();
                let field = arg_def.field.strip_prefix("input.").unwrap_or(&arg_def.field);
                let config_value = fixture.input.get(field).cloned().unwrap_or(serde_json::Value::Null);
                // Derive the create-function name: "engine" → "createEngine".
                let create_fn = {
                    let mut chars = name.chars();
                    let pascal = match chars.next() {
                        None => String::new(),
                        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                    };
                    format!("create{pascal}")
                };
                if config_value.is_null()
                    || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
                {
                    setup_lines.push(format!("final {name} = await {bridge_class}.{create_fn}();"));
                } else {
                    let json_str = serde_json::to_string(&config_value).unwrap_or_default();
                    let config_var = format!("{name}Config");
                    // FRB-generated free function: `createCrawlConfigFromJson(json: '...')` — async,
                    // deserializes the JSON into the mirror struct via the Rust `create_<type>_from_json`
                    // helper emitted by the dart backend. This avoids relying on a Dart-side `fromJson`
                    // constructor (FRB classes don't expose one).
                    setup_lines.push(format!(
                        "final {config_var} = await createCrawlConfigFromJson(json: r'{json_str}');"
                    ));
                    // Facade exposes `createEngine` with a positional-optional `[ConfigType? config]`
                    // parameter (see dart `gen_bindings/functions.rs::format_param` for handles),
                    // so the call site uses positional-arg syntax — `createEngine(cfg)`, not
                    // `createEngine(config: cfg)` (the latter raises "No named parameter 'config'").
                    setup_lines.push(format!(
                        "final {name} = await {bridge_class}.{create_fn}({config_var});"
                    ));
                }
                args.push(name);
                continue;
            }
            "mock_url_list" => {
                // List<String> of URLs: each element is either a bare path (`/seed1`) — prefixed
                // with the SUT URL at runtime — or an absolute URL kept as-is.
                let field = arg_def.field.strip_prefix("input.").unwrap_or(&arg_def.field);
                let val = fixture.input.get(field).unwrap_or(&serde_json::Value::Null);

                let paths: Vec<String> = if let Some(arr) = val.as_array() {
                    arr.iter()
                        .filter_map(|v| v.as_str())
                        .map(|s| format!("'{}'", escape_dart(s)))
                        .collect()
                } else {
                    Vec::new()
                };

                let var_name = &arg_def.name;
                let paths_literal = paths.join(", ");

                setup_lines.push(format!(r#"final {var_name}Base = _sutUrl();"#));
                setup_lines.push(format!(
                    r#"final {var_name} = <String>[{paths_literal}].map((p) => p.startsWith('http') ? p : {var_name}Base + p).toList();"#
                ));

                // For streaming adapters with a request_type, wrap the URL list in the request constructor.
                if let Some(ref req_type) = adapter_request_type {
                    let req_var = format!("{}Req", var_name);
                    // Extract just the type name (last segment after ::).
                    let req_type_name = req_type.rsplit("::").next().unwrap_or(req_type.as_str());
                    setup_lines.push(format!("final {req_var} = {req_type_name}(urls: {var_name});"));
                    args.push(req_var);
                } else {
                    args.push(var_name.to_string());
                }
                continue;
            }
            "test_backend" => {
                if let Some(trait_name) = &arg_def.trait_name {
                    if let Some(trait_bridge) = config.trait_bridges.iter().find(|tb| tb.trait_name == *trait_name) {
                        let methods: Vec<&crate::core::ir::MethodDef> = type_defs
                            .iter()
                            .find(|t| t.name == *trait_name)
                            .map(|t| t.methods.iter().collect())
                            .unwrap_or_default();
                        let emission = crate::e2e::codegen::emit_test_backend("dart", trait_bridge, &methods, fixture);
                        // Dart class definitions are emitted at module-level (before void main)
                        // in collect_dart_test_stub_classes, so we only push the instantiation here.
                        args.push(emission.arg_expr);
                        continue;
                    }
                }
                let emission = crate::e2e::codegen::TestBackendEmission::unimplemented("dart");
                setup_lines.push(format!("// {}", emission.arg_expr));
                args.push("null".to_string());
                continue;
            }
            _ => {}
        }

        let arg_value = resolve_field(&fixture.input, &arg_def.field);
        match arg_def.arg_type.as_str() {
            "bytes" | "file_path" => {
                // `bytes`: value is a file path string; load file contents at test-run time.
                // `file_path`: for dart, normally remapped to bytes via the extract
                // facade convention. The exception is source-code paths — those
                // route through extractFile/extractFileSync directly (see
                // `routes_to_source_code` above), so the path string must be
                // passed verbatim instead of materialised as bytes.
                if let serde_json::Value::String(file_path) = arg_value {
                    if arg_def.arg_type == "file_path" && routes_to_source_code {
                        args.push(format!("'{file_path}'"));
                    } else {
                        args.push(format!("File('{}').readAsBytesSync()", file_path));
                    }
                }
            }
            "int" | "integer" | "i64" => {
                // Scalar integer argument: emit the numeric value as-is (positional required).
                match arg_value {
                    serde_json::Value::Number(n) => {
                        args.push(n.to_string());
                    }
                    serde_json::Value::Null if arg_def.optional => {
                        // Optional int absent: omit it.
                    }
                    _ => {
                        // Required int with no fixture value: emit 0 as default.
                        args.push("0".to_string());
                    }
                }
            }
            "float" | "number" => {
                // Scalar float/number argument: emit the numeric value as-is (positional required).
                match arg_value {
                    serde_json::Value::Number(n) => {
                        args.push(n.to_string());
                    }
                    serde_json::Value::Null if arg_def.optional => {
                        // Optional float absent: omit it.
                    }
                    _ => {
                        // Required float with no fixture value: emit 0.0 as default.
                        args.push("0.0".to_string());
                    }
                }
            }
            "bool" | "boolean" => {
                // Scalar boolean argument: emit the boolean value as-is (positional required).
                match arg_value {
                    serde_json::Value::Bool(b) => {
                        args.push(if *b { "true" } else { "false" }.to_string());
                    }
                    serde_json::Value::Null if arg_def.optional => {
                        // Optional bool absent: omit it.
                    }
                    _ => {
                        // Required bool with no fixture value: emit false as default.
                        args.push("false".to_string());
                    }
                }
            }
            "string" => {
                // Polyglot repos expose their Dart surface through a hand-written facade
                // (e.g. `SampleMarkupBridge.convert(String html, {ConversionOptions? options})`,
                // `SampleLanguagePackBridge.process(String source, ProcessConfig config)`,
                // `SampleCrateBridge.extractBytes(Uint8List content, String mimeType, [SampleSettings? settings])`)
                // that wraps the FRB-generated bridge methods. Those facades follow the
                // Rust idiom: required args are positional, optional args are named with
                // defaults. The "always emit named" heuristic targets the raw FRB bridge
                // call site but breaks every hand-written facade.
                //
                // Mirror the policy used by the `json_object` handler below: required →
                // positional, optional → named. Sample-llm's `chat`/`embed` calls are
                // unaffected because they route through the `from_json` path (which
                // always emits `req:` named) and the `client_factory` path (which
                // hardcodes its own arg shape).
                let dart_param_name = snake_to_camel(&arg_def.name);
                // The `mime_type` parameter is a *positional* parameter in every facade
                // extract method — both `extractBytes`/`extractBytesSync` (where it is a
                // required `String mimeType`) and `extractFile`/`extractFileSync` (where
                // it is a required-but-nullable `String? mimeType`). It always precedes
                // the trailing optional config slot, so it can never be
                // a Dart named parameter. The `optional` flag on the call config marks it
                // optional only because `extract_file`'s Rust signature takes
                // `Option<&str>`; it does not change the Dart facade's positional shape.
                // Only the `client_factory` FRB path declares non-`config` params named.
                let mime_type_is_positional = arg_def.name == "mime_type" && client_factory_for_args.is_none();
                match arg_value {
                    serde_json::Value::String(s) => {
                        let literal = format!("'{}'", escape_dart(s));
                        // FRB-generated client methods (the `client_factory` path, e.g.
                        // sample-llm's `retrieveFile({required String fileId})`) declare
                        // every non-`config` parameter as named-required, so required
                        // string args must be passed with a `name:` label too. Facade
                        // methods (no `client_factory`) keep required args positional.
                        if (arg_def.optional || client_factory_for_args.is_some()) && !mime_type_is_positional {
                            args.push(format!("{dart_param_name}: {literal}"));
                        } else {
                            args.push(literal);
                        }
                    }
                    serde_json::Value::Null
                        if arg_def.optional
                        // Optional string absent from fixture — try to infer MIME from path
                        // when the arg name looks like a MIME-type parameter.
                        && arg_def.name == "mime_type" =>
                    {
                        let inferred = file_path_for_mime
                            .and_then(mime_from_extension)
                            .unwrap_or("application/octet-stream");
                        // Emit positionally for the facade path (see above); only the
                        // `client_factory` FRB path uses the `mimeType:` named label.
                        if mime_type_is_positional {
                            args.push(format!("'{inferred}'"));
                        } else {
                            args.push(format!("{dart_param_name}: '{inferred}'"));
                        }
                    }
                    // Other optional strings with null value are omitted.
                    _ => {}
                }
            }
            "json_object" => {
                if let Some(elem_type) = &arg_def.element_type {
                    if elem_type == "String" && arg_value.is_array() {
                        // Scalar string array (e.g. `texts: ["a", "b"]` for embed_texts).
                        // The `SampleCrateBridge` facade declares these parameters as required
                        // positional (e.g. `embedTexts(List<String> texts, SampleSettings settings)`),
                        // so the list literal must be passed positionally — matching the
                        // facade contract rather than the underlying FRB bridge's named-arg
                        // convention.
                        let items: Vec<String> = arg_value
                            .as_array()
                            .unwrap()
                            .iter()
                            .filter_map(|v| v.as_str())
                            .map(|s| format!("'{}'", escape_dart(s)))
                            .collect();
                        args.push(format!("<String>[{}]", items.join(", ")));
                    } else if arg_value.is_array() {
                        // Generic typed array (e.g. `actions: [PageAction]` for interact).
                        // Decode via jsonDecode at test-run time and convert to typed instances.
                        let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
                        let var_name = arg_def.name.clone();
                        if elem_type == "PageAction" {
                            setup_lines.push(format!(
                                "final {var_name} = (jsonDecode(r'{json_str}') as List<dynamic>).map((e) => _parsePageAction(e as Map<String, dynamic>)).toList();"
                            ));
                        } else {
                            setup_lines.push(format!(
                                "final {var_name} = (jsonDecode(r'{json_str}') as List<dynamic>).cast<Map<String, dynamic>>();"
                            ));
                        }
                        args.push(var_name);
                    }
                } else if options_via == "from_json" {
                    // `from_json` path: construct a typed mirror-struct via the generated
                    // `create<TypeName>FromJson(json: '...')` bridge helper, then pass it
                    // as the named FRB parameter `req: _var`.
                    //
                    // The helper is generated by `emit_from_json_fn` in the dart bridge-crate
                    // generator and made available as a top-level function via the exported
                    // the generated bridge package. The parameter name used in the
                    // bridge method call is always `req:` for single-request-object methods
                    // (derived from the Rust IR param name).
                    if let Some(opts_type) = options_type {
                        if !arg_value.is_null() {
                            let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
                            // Escape for Dart single-quoted string literal (handles embedded quotes,
                            // backslashes, and interpolation markers).
                            let escaped_json = escape_dart(&json_str);
                            let var_name = format!("_{}", arg_def.name);
                            let dart_fn = type_name_to_create_from_json_dart(opts_type);
                            setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
                            // FRB bridge method param name is `req` for all single-request methods.
                            // Use `req:` as the named argument label.
                            args.push(format!("req: {var_name}"));
                        }
                    }
                } else if call_recipe.should_materialize_json_object(arg_def, arg_value) && arg_value.is_null() {
                    if let Some(opts_type) = options_type {
                        let var_name = format!("_{}", arg_def.name);
                        let dart_fn = type_name_to_create_from_json_dart(opts_type);
                        setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{{}}');"));
                        args.push(var_name);
                    }
                } else if arg_def.name == "config" {
                    if let serde_json::Value::Object(map) = &arg_value {
                        if !map.is_empty() {
                            // Round-trip object config JSON through a generated helper.
                            // Prefer explicit type metadata; the arg name fallback is only
                            // a neutral best effort for legacy configs.
                            let opts_type = options_type.unwrap_or(&arg_def.name);
                            let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
                            let escaped_json = escape_dart(&json_str);
                            let var_name = format!("_{}", arg_def.name);
                            let dart_fn = type_name_to_create_from_json_dart(opts_type);
                            setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
                            args.push(var_name);
                        } else {
                            // Empty config object: construct a default instance via FRB's
                            // `create<Type>FromJson(json: '{}')` helper (supports all
                            // configured config types). This ensures the
                            // call signature matches the binding, which expects a required
                            // config parameter even when all fields use their defaults.
                            if let Some(opts_type) = options_type {
                                let var_name = format!("_{}", arg_def.name);
                                let dart_fn = type_name_to_create_from_json_dart(opts_type);
                                setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{{}}');"));
                                args.push(var_name);
                            }
                        }
                    } else if arg_def.optional {
                        // Fixture has no config block (null/absent) but the Dart facade
                        // declares the arg as a required-positional non-nullable type
                        // (e.g. `embed_texts_async(texts, settings)` with `SampleSettings`).
                        // Construct a default instance via FRB's
                        // `create<Type>FromJson(json: '{}')` helper when IR metadata says
                        // the configured type has a default.
                        if let Some(opts_type) = options_type.filter(|_| {
                            call_recipe.json_object_arg_has_default(arg_def)
                                || call_recipe.should_materialize_json_object(arg_def, arg_value)
                        }) {
                            let var_name = format!("_{}", arg_def.name);
                            let dart_fn = type_name_to_create_from_json_dart(opts_type);
                            setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{{}}');"));
                            args.push(var_name);
                        }
                    }
                } else if arg_value.is_array() {
                    // Generic JSON array (e.g. batch_urls: ["/page1", "/page2"]).
                    // Decode via jsonDecode and cast to List<String> at test-run time.
                    let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
                    let var_name = arg_def.name.clone();
                    setup_lines.push(format!(
                        "final {var_name} = (jsonDecode(r'{json_str}') as List<dynamic>).cast<String>();"
                    ));
                    args.push(var_name);
                } else if let serde_json::Value::Object(map) = &arg_value {
                    // Generic options-style json_object arg (for APIs whose
                    // `options: ConversionOptions` on `convert(html, options)`). When the
                    // fixture provides input.options and the call config declares an
                    // `options_type`, build the mirror struct via the FRB-generated
                    // `create<OptionsType>FromJson(json: '...')` helper. Use the arg's
                    // original name (e.g. `options`) as the named parameter label.
                    //
                    // When the fixture also carries a visitor spec, swap to the
                    // `create<OptionsType>FromJsonWithVisitor(json, visitor)` helper
                    // (emitted by `alef-backend-dart` for trait bridges with `type_alias`
                    // + `options_field` binding). The `_visitor` variable is materialised
                    // in the visitor block below — its setup line is inserted ahead of
                    // this options call by `build_dart_visitor`.
                    if !map.is_empty() {
                        if let Some(opts_type) = options_type {
                            let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
                            let escaped_json = escape_dart(&json_str);
                            let dart_param_name = snake_to_camel(&arg_def.name);
                            let var_name = format!("_{}", arg_def.name);
                            let dart_fn = type_name_to_create_from_json_dart(opts_type);
                            if fixture.visitor.is_some() {
                                setup_lines.push(format!(
                                    "final {var_name} = await {dart_fn}WithVisitor(json: '{escaped_json}', visitor: _visitor);"
                                ));
                            } else {
                                setup_lines
                                    .push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
                            }
                            if arg_def.optional {
                                args.push(format!("{dart_param_name}: {var_name}"));
                            } else {
                                args.push(var_name);
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }

    // Fixture-driven visitor handle. When `fixture.visitor` is set we build a
    // `_visitor` via the generated visitor factory (emitted by
    // `alef-backend-dart`'s trait-bridge generator in the `type_alias` mode)
    // and thread it into the options blob via the
    // `create<OptionsType>FromJsonWithVisitor(json, visitor)` helper (handled
    // a few lines above in the json_object arg branch).
    //
    // The visitor setup line is INSERTED at the front of `setup_lines` so
    // `_visitor` is defined before any `_options` line that references it.
    // Fixtures without an `options` json_object in input still need an options
    // blob to carry the visitor through to convert — we synthesise an empty-
    // options call to `createConversionOptionsFromJsonWithVisitor(json: '{}',
    // visitor: _visitor)` here when no `options` arg was emitted in the loop
    // above.
    if let Some(visitor_spec) = &fixture.visitor {
        let mut visitor_setup: Vec<String> = Vec::new();
        let visitor_config = super::dart_visitors::resolve_dart_visitor_config(call_overrides, type_defs, visitor_spec);
        let _ = super::dart_visitors::build_dart_visitor(&mut visitor_setup, visitor_spec, &visitor_config);
        // Prepend the visitor block so `_visitor` is in scope by the time the
        // options call (which may reference it) runs.
        for line in visitor_setup.into_iter().rev() {
            setup_lines.insert(0, line);
        }

        // If no `options` arg was emitted by the loop above (the fixture has no
        // input.options block), build an empty options-with-visitor and add it as
        // an `options:` named arg so the visitor reaches the convert call.
        let already_has_options = args.iter().any(|a| a.starts_with("options:") || a == "_options");
        if !already_has_options {
            if let Some(opts_type) = options_type {
                let dart_fn = type_name_to_create_from_json_dart(opts_type);
                setup_lines.push(format!(
                    "final _options = await {dart_fn}WithVisitor(json: '{{}}', visitor: _visitor);"
                ));
                args.push("options: _options".to_string());
            }
        }
    }

    // Resolve client_factory: when set, tests create a client instance and call
    // methods on it rather than using static bridge-class calls. This mirrors the
    // go/python/zig pattern for stateful clients (e.g. sample-llm).
    let client_factory: Option<&str> = call_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())
    });

    // Convert factory name to camelCase (same rule as function_name above).
    let client_factory_camel: Option<String> = client_factory.map(|f| {
        f.split('_')
            .enumerate()
            .map(|(i, part)| {
                if i == 0 {
                    part.to_string()
                } else {
                    let mut chars = part.chars();
                    match chars.next() {
                        None => String::new(),
                        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                    }
                }
            })
            .collect::<Vec<_>>()
            .join("")
    });

    // All bridge methods return Future<T> because FRB v2 wraps every Rust
    // function as async in Dart — even "sync" Rust functions. Always emit an async
    // test body and await the call so the test framework waits for the future.
    let _ = writeln!(out, "  test('{description}', () async {{");

    let args_str = args.join(", ");
    let receiver_class = call_overrides
        .and_then(|o| o.class.as_ref())
        .cloned()
        .unwrap_or_else(|| bridge_class.to_string());

    // When client_factory is set, determine the mock URL and emit client instantiation.
    // The mock URL derivation follows the same has_host_root_route / plain-fixture split
    // used by the mock_url arg handler above.
    let (receiver, extra_setup): (String, Option<String>) = if let Some(factory) = &client_factory_camel {
        let has_mock_url = fixture
            .resolved_args(call_config)
            .iter()
            .any(|a| a.arg_type == "mock_url");
        let mock_url_setup = if !has_mock_url {
            // No explicit mock_url arg — derive the URL inline.
            Some(format!(r#"final _mockUrl = "${{_sutUrl()}}/fixtures/{fixture_id}";"#))
        } else {
            None
        };
        let url_expr = if has_mock_url {
            // A mock_url arg was emitted into setup_lines already — reuse the variable name
            // from the first mock_url arg definition so we don't duplicate the URL.
            call_config
                .args
                .iter()
                .find(|a| a.arg_type == "mock_url")
                .map(|a| a.name.clone())
                .unwrap_or_else(|| "_mockUrl".to_string())
        } else {
            "_mockUrl".to_string()
        };
        let create_line = format!("final _client = await {receiver_class}.{factory}('test-key', baseUrl: {url_expr});");
        let full_setup = if let Some(url_line) = mock_url_setup {
            Some(format!("{url_line}\n    {create_line}"))
        } else {
            Some(create_line)
        };
        ("_client".to_string(), full_setup)
    } else {
        (receiver_class.clone(), None)
    };

    if expects_error && (!setup_lines.is_empty() || extra_setup.is_some()) {
        // Wrap setup + call in an async lambda so any exception at any step is caught.
        // flutter_rust_bridge 2.x decodes Rust errors as raw String values (not Exception
        // subtypes), so throwsException will not match. Use throwsA(anything) instead.
        let _ = writeln!(out, "    await expectLater(() async {{");
        for line in &setup_lines {
            // Handle multi-line setup blocks (e.g., class definitions from emit_test_backend).
            // Each embedded newline in `line` needs proper indentation.
            for inner_line in line.lines() {
                let _ = writeln!(out, "      {inner_line}");
            }
        }
        if let Some(extra) = &extra_setup {
            for line in extra.lines() {
                let _ = writeln!(out, "      {line}");
            }
        }
        if is_streaming {
            let _ = writeln!(out, "      return {receiver}.{function_name}({args_str}).toList();");
        } else {
            let _ = writeln!(out, "      return {receiver}.{function_name}({args_str});");
        }
        let _ = writeln!(out, "    }}(), throwsA(anything));");
    } else if expects_error {
        // No setup lines, direct call — same throwsA(anything) rationale as above.
        if let Some(extra) = &extra_setup {
            for line in extra.lines() {
                let _ = writeln!(out, "    {line}");
            }
        }
        if is_streaming {
            let _ = writeln!(
                out,
                "    await expectLater({receiver}.{function_name}({args_str}).toList(), throwsA(anything));"
            );
        } else {
            let _ = writeln!(
                out,
                "    await expectLater({receiver}.{function_name}({args_str}), throwsA(anything));"
            );
        }
    } else {
        for line in &setup_lines {
            // Handle multi-line setup blocks (e.g., class definitions from emit_test_backend).
            // Each embedded newline in `line` needs proper indentation.
            for inner_line in line.lines() {
                let _ = writeln!(out, "    {inner_line}");
            }
        }
        if let Some(extra) = &extra_setup {
            for line in extra.lines() {
                let _ = writeln!(out, "    {line}");
            }
        }
        if is_streaming {
            let _ = writeln!(
                out,
                "    final {result_var} = await {receiver}.{function_name}({args_str}).toList();"
            );
        } else {
            let _ = writeln!(
                out,
                "    final {result_var} = await {receiver}.{function_name}({args_str});"
            );
        }
        for assertion in &fixture.assertions {
            if is_streaming {
                render_streaming_assertion_dart(out, assertion, result_var);
            } else {
                render_assertion_dart(
                    out,
                    assertion,
                    result_var,
                    result_is_simple,
                    field_resolver,
                    enum_fields,
                );
            }
        }
    }

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

/// Render `.length` / `?.length ?? 0` against a Dart field accessor.
///
/// Count-style assertions (`count_equals`, `count_min`, `min_length`, `max_length`)
/// operate on collection-typed fields. FRB v2 maps `Option<Vec<T>>` to `List<T>?`
/// (nullable) but `Vec<T>` to `List<T>` (non-null). Emitting `?.length ?? 0`
/// against a non-null receiver triggers `invalid_null_aware_operator`. Inspect
/// the IR via `FieldResolver::is_optional` and choose the safe form per field.
fn dart_length_expr(field_accessor: &str, field: Option<&str>, field_resolver: &FieldResolver) -> String {
    let is_optional = field
        .map(|f| {
            let resolved = field_resolver.resolve(f);
            field_resolver.is_optional(f) || field_resolver.is_optional(resolved)
        })
        .unwrap_or(false);
    if is_optional {
        format!("{field_accessor}?.length ?? 0")
    } else {
        format!("{field_accessor}.length")
    }
}

fn dart_format_value(val: &serde_json::Value) -> String {
    match val {
        serde_json::Value::String(s) => format!("'{}'", escape_dart(s)),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Null => "null".to_string(),
        other => format!("'{}'", escape_dart(&other.to_string())),
    }
}

/// Render a single fixture assertion as a Dart `package:test` `expect(...)` call.
///
/// Field paths are converted per-segment to camelCase (FRB v2 convention) using
/// [`field_to_dart_accessor`].  All 24 fixture assertion types are handled.
///
/// Assertions on fixture fields that are not in the configured `result_fields` set
/// are emitted as a `// skipped:` comment instead — the Dart binding may model a
/// different result shape than the fixture asserts on (e.g. flat `ScrapeResult` vs.
/// nested `result.browser.*`), and emitting unresolvable getters would break the
/// whole file at compile time.
fn render_assertion_dart(
    out: &mut String,
    assertion: &Assertion,
    result_var: &str,
    result_is_simple: bool,
    field_resolver: &FieldResolver,
    enum_fields: &std::collections::HashSet<String>,
) {
    // Skip assertions on fields that don't exist on the dart result type. This must run
    // BEFORE the array-traversal and standard accessor paths since both emit code that
    // references the field — an unknown field path produces an `isn't defined` error.
    if !result_is_simple {
        if let Some(f) = assertion.field.as_deref() {
            // Use the head segment (before any `[].`) for validation since `is_valid_for_result`
            // only checks the first path component.
            let head = f.split("[].").next().unwrap_or(f);
            if !head.is_empty() && !field_resolver.is_valid_for_result(head) {
                let _ = writeln!(out, "    // skipped: field '{f}' not available on dart result type");
                return;
            }
        }
    }

    // Skip assertions that traverse a tagged-union variant boundary. FRB exposes
    // tagged unions like `FormatMetadata` as sealed classes whose variants are
    // accessed via pattern matching (`switch (m) { case FormatMetadata_Excel ... }`)
    // — there is no `.excel?` getter, so the fixture path cannot be expressed as
    // a simple chained accessor without language-specific pattern-matching codegen.
    if let Some(f) = assertion.field.as_deref() {
        if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
            let _ = writeln!(
                out,
                "    // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Dart)"
            );
            return;
        }
    }

    // Handle array traversal (e.g. "links[].link_type" → any() expression).
    if let Some(f) = assertion.field.as_deref() {
        if let Some(dot) = f.find("[].") {
            // Apply the alias mapping to the full `xxx[].yyy` path first so renamed
            // sub-fields (e.g. `assets[].category` → `assets[].asset_category`) resolve
            // correctly. Split *after* resolving so both the array head and the element
            // path reflect any alias rewrites.
            let resolved_full = field_resolver.resolve(f);
            let (array_part, elem_part) = match resolved_full.find("[].") {
                Some(rdot) => (&resolved_full[..rdot], &resolved_full[rdot + 3..]),
                // Resolver mapped the path away from `[].` form — fall back to the original
                // split, since downstream code expects the array/elem structure.
                None => (&f[..dot], &f[dot + 3..]),
            };
            let array_accessor = if array_part.is_empty() {
                result_var.to_string()
            } else {
                field_resolver.accessor(array_part, "dart", result_var)
            };
            let elem_accessor = field_to_dart_accessor(elem_part);
            match assertion.assertion_type.as_str() {
                "contains" => {
                    if let Some(expected) = &assertion.value {
                        let dart_val = dart_format_value(expected);
                        let _ = writeln!(
                            out,
                            "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
                        );
                    }
                }
                "contains_all" => {
                    if let Some(values) = &assertion.values {
                        for val in values {
                            let dart_val = dart_format_value(val);
                            let _ = writeln!(
                                out,
                                "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
                            );
                        }
                    }
                }
                "not_contains" => {
                    if let Some(expected) = &assertion.value {
                        let dart_val = dart_format_value(expected);
                        let _ = writeln!(
                            out,
                            "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
                        );
                    } else if let Some(values) = &assertion.values {
                        for val in values {
                            let dart_val = dart_format_value(val);
                            let _ = writeln!(
                                out,
                                "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
                            );
                        }
                    }
                }
                "not_empty" => {
                    let _ = writeln!(
                        out,
                        "    expect({array_accessor}.any((e) => e.{elem_accessor}.toString().isNotEmpty), isTrue);"
                    );
                }
                other => {
                    let _ = writeln!(
                        out,
                        "    // skipped: unsupported traversal assertion '{other}' on '{f}'"
                    );
                }
            }
            return;
        }
    }

    let field_accessor = if result_is_simple {
        // Whole-result assertion path: the dart return is a scalar (e.g. a
        // `Uint8List` for speech/file_content), so any `field` on the
        // assertion resolves to the whole value rather than a sub-accessor.
        result_var.to_string()
    } else {
        match assertion.field.as_deref() {
            // Use the shared accessor builder (`FieldResolver::accessor`) — it applies the
            // alias mapping (e.g. `robots.is_allowed` → `is_allowed`), expands array
            // segments to `[0]` lookups, and injects `!` after optional intermediates so
            // chained access compiles under sound null safety.
            Some(f) if !f.is_empty() => field_resolver.accessor(f, "dart", result_var),
            _ => result_var.to_string(),
        }
    };

    let format_value = |val: &serde_json::Value| -> String { dart_format_value(val) };

    match assertion.assertion_type.as_str() {
        "equals" | "field_equals" => {
            if let Some(expected) = &assertion.value {
                let dart_val = format_value(expected);
                // Check if this field is an enum field. Enum fields need _alefE2eText for serde
                // wire format conversion (e.g. FinishReason.toolCalls → "tool_calls").
                let is_enum_field = assertion
                    .field
                    .as_deref()
                    .map(|f| {
                        let resolved = field_resolver.resolve(f);
                        enum_fields.contains(f) || enum_fields.contains(resolved)
                    })
                    .unwrap_or(false);

                // Match the rust codegen's behaviour: trim both sides for string equality
                // so trailing-newline differences between generated text output and the
                // fixture's expected value don't produce false positives.
                if expected.is_string() {
                    if is_enum_field {
                        // For enum fields, use _alefE2eText to normalize the enum value to its
                        // serde wire format before comparison.
                        let _ = writeln!(
                            out,
                            "    expect(_alefE2eText({field_accessor}).trim(), equals({dart_val}.toString().trim()));"
                        );
                    } else {
                        // When result_is_simple is true and the field_accessor is nullable (e.g. String?),
                        // use null-coalescing operator (?? '') to handle null gracefully.
                        let safe_accessor = if result_is_simple && assertion.field.is_none() {
                            format!("({field_accessor} ?? '').toString().trim()")
                        } else {
                            format!("{field_accessor}.toString().trim()")
                        };
                        let _ = writeln!(
                            out,
                            "    expect({safe_accessor}, equals({dart_val}.toString().trim()));"
                        );
                    }
                } else {
                    let _ = writeln!(out, "    expect({field_accessor}, equals({dart_val}));");
                }
            } else {
                let _ = writeln!(
                    out,
                    "    // skipped: '{}' assertion missing value",
                    assertion.assertion_type
                );
            }
        }
        "not_equals" => {
            if let Some(expected) = &assertion.value {
                let dart_val = format_value(expected);
                // Check if this field is an enum field.
                let is_enum_field = assertion
                    .field
                    .as_deref()
                    .map(|f| {
                        let resolved = field_resolver.resolve(f);
                        enum_fields.contains(f) || enum_fields.contains(resolved)
                    })
                    .unwrap_or(false);

                if expected.is_string() {
                    if is_enum_field {
                        let _ = writeln!(
                            out,
                            "    expect(_alefE2eText({field_accessor}).trim(), isNot(equals({dart_val}.toString().trim())));"
                        );
                    } else {
                        // When result_is_simple is true and the field_accessor is nullable (e.g. String?),
                        // use null-coalescing operator (?? '') to handle null gracefully.
                        let safe_accessor = if result_is_simple && assertion.field.is_none() {
                            format!("({field_accessor} ?? '').toString().trim()")
                        } else {
                            format!("{field_accessor}.toString().trim()")
                        };
                        let _ = writeln!(
                            out,
                            "    expect({safe_accessor}, isNot(equals({dart_val}.toString().trim())));"
                        );
                    }
                } else {
                    let _ = writeln!(out, "    expect({field_accessor}, isNot(equals({dart_val})));");
                }
            }
        }
        "contains" => {
            if let Some(expected) = &assertion.value {
                let dart_val = format_value(expected);
                // Try the "stringy aggregator" path first: when the field is a list of DTOs
                // with multiple text-bearing accessors (e.g. List<ImportInfo> with
                // source/items/alias), emit code that walks every accessor and does
                // substring matching. This avoids the brittle "primary accessor" guess.
                let aggregator = dart_stringy_aggregator_contains_assert(
                    assertion.field.as_deref(),
                    result_var,
                    field_resolver,
                    &dart_val,
                );
                if let Some(line) = aggregator {
                    let _ = writeln!(out, "{line}");
                } else {
                    let _ = writeln!(out, "    expect({field_accessor}, contains({dart_val}));");
                }
            } else {
                let _ = writeln!(out, "    // skipped: 'contains' assertion missing value");
            }
        }
        "contains_all" => {
            if let Some(values) = &assertion.values {
                for val in values {
                    let dart_val = format_value(val);
                    let _ = writeln!(out, "    expect({field_accessor}, contains({dart_val}));");
                }
            }
        }
        "contains_any" => {
            if let Some(values) = &assertion.values {
                let checks: Vec<String> = values
                    .iter()
                    .map(|v| {
                        let dart_val = format_value(v);
                        format!("{field_accessor}.contains({dart_val})")
                    })
                    .collect();
                let joined = checks.join(" || ");
                let _ = writeln!(out, "    expect({joined}, isTrue);");
            }
        }
        "not_contains" => {
            if let Some(expected) = &assertion.value {
                let dart_val = format_value(expected);
                let _ = writeln!(out, "    expect({field_accessor}, isNot(contains({dart_val})));");
            } else if let Some(values) = &assertion.values {
                for val in values {
                    let dart_val = format_value(val);
                    let _ = writeln!(out, "    expect({field_accessor}, isNot(contains({dart_val})));");
                }
            }
        }
        "not_empty" => {
            // `isNotEmpty` only applies to types with a `.isEmpty` getter (collections,
            // strings, maps). For struct-shaped fields (e.g. `document: DocumentStructure`)
            // we instead assert the value is non-null — those types have no notion of
            // "empty" and the fixture intent is "the field is present".
            let is_collection = assertion.field.as_deref().is_some_and(|f| {
                let resolved = field_resolver.resolve(f);
                field_resolver.is_array(f) || field_resolver.is_array(resolved)
            });
            if is_collection {
                let _ = writeln!(out, "    expect({field_accessor}, isNotEmpty);");
            } else {
                let _ = writeln!(out, "    expect({field_accessor}, isNotNull);");
            }
        }
        "is_empty" => {
            // FRB models `Option<String>` / `Option<Vec<T>>` as nullable in Dart. The `isEmpty`
            // matcher throws `NoSuchMethodError` on `null`. Accept `null` as semantically
            // empty by combining `isNull` with `isEmpty` via `anyOf`.
            let _ = writeln!(out, "    expect({field_accessor}, anyOf(isNull, isEmpty));");
        }
        "starts_with" => {
            if let Some(expected) = &assertion.value {
                let dart_val = format_value(expected);
                let _ = writeln!(out, "    expect({field_accessor}, startsWith({dart_val}));");
            }
        }
        "ends_with" => {
            if let Some(expected) = &assertion.value {
                let dart_val = format_value(expected);
                let _ = writeln!(out, "    expect({field_accessor}, endsWith({dart_val}));");
            }
        }
        "min_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
                    let _ = writeln!(out, "    expect({length_expr}, greaterThanOrEqualTo({n}));");
                }
            }
        }
        "max_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
                    let _ = writeln!(out, "    expect({length_expr}, lessThanOrEqualTo({n}));");
                }
            }
        }
        "count_equals" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
                    let _ = writeln!(out, "    expect({length_expr}, equals({n}));");
                }
            }
        }
        "count_min" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
                    let _ = writeln!(out, "    expect({length_expr}, greaterThanOrEqualTo({n}));");
                }
            }
        }
        "matches_regex" => {
            if let Some(expected) = &assertion.value {
                let dart_val = format_value(expected);
                let _ = writeln!(out, "    expect({field_accessor}, matches(RegExp({dart_val})));");
            }
        }
        "is_true" => {
            let _ = writeln!(out, "    expect({field_accessor}, isTrue);");
        }
        "is_false" => {
            let _ = writeln!(out, "    expect({field_accessor}, isFalse);");
        }
        "greater_than" => {
            if let Some(val) = &assertion.value {
                let dart_val = format_value(val);
                let _ = writeln!(out, "    expect({field_accessor}, greaterThan({dart_val}));");
            }
        }
        "less_than" => {
            if let Some(val) = &assertion.value {
                let dart_val = format_value(val);
                let _ = writeln!(out, "    expect({field_accessor}, lessThan({dart_val}));");
            }
        }
        "greater_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let dart_val = format_value(val);
                let _ = writeln!(out, "    expect({field_accessor}, greaterThanOrEqualTo({dart_val}));");
            }
        }
        "less_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let dart_val = format_value(val);
                let _ = writeln!(out, "    expect({field_accessor}, lessThanOrEqualTo({dart_val}));");
            }
        }
        "not_null" => {
            let _ = writeln!(out, "    expect({field_accessor}, isNotNull);");
        }
        "not_error" => {
            // The `await` already guarantees no thrown error reaches this point — if
            // the call throws, the test fails before reaching here. Don't emit
            // `expect(result, isNotNull)`: for void-returning trait-bridge fns
            // (clear_*) Dart rejects `expect(<void>, ...)` with "expression has type
            // 'void' and can't be used". The implicit exception handling proves
            // success.
        }
        "error" => {
            // Handled at the test method level via throwsA(anything).
        }
        "method_result" => {
            if let Some(method) = &assertion.method {
                let dart_method = method.to_lower_camel_case();
                let check = assertion.check.as_deref().unwrap_or("not_null");
                let method_call = format!("{field_accessor}.{dart_method}()");
                match check {
                    "equals" => {
                        if let Some(expected) = &assertion.value {
                            let dart_val = format_value(expected);
                            let _ = writeln!(out, "    expect({method_call}, equals({dart_val}));");
                        }
                    }
                    "is_true" => {
                        let _ = writeln!(out, "    expect({method_call}, isTrue);");
                    }
                    "is_false" => {
                        let _ = writeln!(out, "    expect({method_call}, isFalse);");
                    }
                    "greater_than_or_equal" => {
                        if let Some(val) = &assertion.value {
                            let dart_val = format_value(val);
                            let _ = writeln!(out, "    expect({method_call}, greaterThanOrEqualTo({dart_val}));");
                        }
                    }
                    "count_min" => {
                        if let Some(val) = &assertion.value {
                            if let Some(n) = val.as_u64() {
                                let _ = writeln!(out, "    expect({method_call}.length, greaterThanOrEqualTo({n}));");
                            }
                        }
                    }
                    _ => {
                        let _ = writeln!(out, "    expect({method_call}, isNotNull);");
                    }
                }
            }
        }
        other => {
            let _ = writeln!(out, "    // skipped: unknown assertion type '{other}'");
        }
    }
}

/// Render a single fixture assertion for a streaming result.
///
/// `result_var` is the `List<T>` collected via `.toList()` on the stream.
/// Supports:
/// - `not_error`: `expect(result, isNotNull)` (a thrown error would already fail
///   the test; the explicit expect keeps the test body non-empty).
/// - `count_min` with `field = "chunks"`: assert `result_var.length >= value`.
/// - `equals` with `field = "stream_content"`: concatenate `delta.content` and compare.
///
/// Other assertion types are emitted as comments.
fn render_streaming_assertion_dart(out: &mut String, assertion: &Assertion, result_var: &str) {
    match assertion.assertion_type.as_str() {
        "not_error" => {
            // `.toList()` would have thrown to fail the test on error; emit an
            // explicit `expect` so the test body isn't empty and the collected
            // stream variable is consumed.
            let _ = writeln!(out, "    expect({result_var}, isNotNull);");
        }
        "count_min" if assertion.field.as_deref() == Some("chunks") => {
            if let Some(serde_json::Value::Number(n)) = &assertion.value {
                let _ = writeln!(out, "    expect({result_var}.length, greaterThanOrEqualTo({n}));");
            }
        }
        "equals" if assertion.field.as_deref() == Some("stream_content") => {
            if let Some(serde_json::Value::String(expected)) = &assertion.value {
                let escaped = escape_dart(expected);
                let _ = writeln!(
                    out,
                    "    final _content = {result_var}.map((c) => c.choices.firstOrNull?.delta.content ?? '').join();"
                );
                let _ = writeln!(out, "    expect(_content, equals('{escaped}'));");
            }
        }
        other => {
            let _ = writeln!(out, "    // skipped streaming assertion: '{other}'");
        }
    }
}

/// Converts a snake_case JSON key to Dart camelCase.
fn snake_to_camel(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut next_upper = false;
    for ch in s.chars() {
        if ch == '_' {
            next_upper = true;
        } else if next_upper {
            result.extend(ch.to_uppercase());
            next_upper = false;
        } else {
            result.push(ch);
        }
    }
    result
}

/// Convert a dot-separated fixture field path to a Dart accessor expression.
///
/// Each segment is converted to camelCase (FRB v2 convention); array-index brackets
/// (e.g. `choices[0]`) and map-key brackets (e.g. `tags[name]`) are preserved.
/// This replaces the former single-pass `snake_to_camel` call which incorrectly
/// treated the entire path string as one identifier.
///
/// Examples:
/// - `"choices"` → `"choices"`
/// - `"choices[0].message.content"` → `"choices[0].message.content"`
/// - `"metadata.document_title"` → `"metadata.documentTitle"`
/// - `"model_id"` → `"modelId"`
fn field_to_dart_accessor(path: &str) -> String {
    let mut result = String::with_capacity(path.len());
    for (i, segment) in path.split('.').enumerate() {
        if i > 0 {
            result.push('.');
        }
        // Separate a trailing `[...]` bracket from the field name so we only
        // camelCase the identifier part, not the bracket content. The owning
        // collection may be `List<T>?` when the underlying Rust field is
        // `Option<Vec<T>>`; force-unwrap with `!` so the `[N]` lookup and any
        // subsequent member access compile under sound null safety.
        if let Some(bracket_pos) = segment.find('[') {
            let name = &segment[..bracket_pos];
            let bracket = &segment[bracket_pos..];
            result.push_str(&name.to_lower_camel_case());
            result.push('!');
            result.push_str(bracket);
        } else {
            result.push_str(&segment.to_lower_camel_case());
        }
    }
    result
}

// ---------------------------------------------------------------------------
// HTTP server test rendering — DartTestClientRenderer impl + thin driver wrapper
// ---------------------------------------------------------------------------

/// Renderer that emits `package:test` `test(...)` blocks using `dart:io HttpClient`
/// against the mock server (`Platform.environment['MOCK_SERVER_URL']`).
///
/// Skipped tests are emitted as self-contained stubs (complete test block with
/// `markTestSkipped`) entirely inside `render_test_open`. `render_test_close` uses
/// `in_skip` to emit the right closing token: nothing extra for skip stubs (already
/// closed) vs. `})));` for regular tests.
///
/// `is_redirect` must be set to `true` before invoking the shared driver for 3xx
/// fixtures so that `render_call` can inject `ioReq.followRedirects = false` after
/// the `openUrl` call.
struct DartTestClientRenderer {
    /// Set to `true` when `render_test_open` is called with a skip reason so that
    /// `render_test_close` can match the opening shape.
    in_skip: Cell<bool>,
    /// Pre-set to `true` by the thin wrapper when the fixture expects a 3xx response.
    /// `render_call` injects `ioReq.followRedirects = false` when this is `true`.
    is_redirect: Cell<bool>,
}

impl DartTestClientRenderer {
    fn new(is_redirect: bool) -> Self {
        Self {
            in_skip: Cell::new(false),
            is_redirect: Cell::new(is_redirect),
        }
    }
}

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

    /// Emit the test opening.
    ///
    /// For skipped fixtures: emit the entire self-contained stub (open + body +
    /// close + blank line) and set `in_skip = true` so `render_test_close` is a
    /// no-op.
    ///
    /// For active fixtures: emit `test('desc', () => _serialized(() => _withRetry(() async {`
    /// leaving the block open for the assertion primitives.
    fn render_test_open(&self, out: &mut String, _fn_name: &str, description: &str, skip_reason: Option<&str>) {
        let escaped_desc = escape_dart(description);
        if let Some(reason) = skip_reason {
            let escaped_reason = escape_dart(reason);
            let _ = writeln!(out, "  test('{escaped_desc}', () {{");
            let _ = writeln!(out, "    markTestSkipped('{escaped_reason}');");
            let _ = writeln!(out, "  }});");
            let _ = writeln!(out);
            self.in_skip.set(true);
        } else {
            let _ = writeln!(
                out,
                "  test('{escaped_desc}', () => _serialized(() => _withRetry(() async {{"
            );
            self.in_skip.set(false);
        }
    }

    /// Emit the test closing token.
    ///
    /// No-op for skip stubs (the stub was fully closed in `render_test_open`).
    /// Emits `})));` followed by a blank line for regular tests.
    fn render_test_close(&self, out: &mut String) {
        if self.in_skip.get() {
            // Stub was already closed in render_test_open.
            return;
        }
        let _ = writeln!(out, "  }})));");
        let _ = writeln!(out);
    }

    /// Emit the full `dart:io HttpClient` request scaffolding.
    ///
    /// Emits:
    /// - URL construction from `MOCK_SERVER_URL`.
    /// - `_httpClient.openUrl(method, uri)`.
    /// - `followRedirects = false` when `is_redirect` is pre-set on the renderer.
    /// - Content-Type header, request headers, cookies, optional body bytes.
    /// - `ioReq.contentLength` when a body is present (avoids chunked encoding).
    /// - `ioReq.close()` → `ioResp`.
    /// - Response-body drain into `bodyStr` (always emitted, including for 3xx).
    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
        // dart:io restricted headers (handled automatically by the HTTP stack).
        const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];

        let method = ctx.method.to_uppercase();
        let escaped_method = escape_dart(&method);

        // Fixture path is `/fixtures/<id>` — extract the id portion for URL construction.
        let fixture_path = escape_dart(ctx.path);

        // Determine effective content-type.
        let has_explicit_content_type = ctx.headers.keys().any(|k| k.to_lowercase() == "content-type");
        let effective_content_type = if has_explicit_content_type {
            ctx.headers
                .iter()
                .find(|(k, _)| k.to_lowercase() == "content-type")
                .map(|(_, v)| v.as_str())
                .unwrap_or("application/json")
        } else if ctx.body.is_some() {
            ctx.content_type.unwrap_or("application/json")
        } else {
            ""
        };

        let _ = writeln!(out, "    final baseUrl = _sutUrl();");
        let _ = writeln!(out, "    final uri = Uri.parse('$baseUrl{fixture_path}');");
        let _ = writeln!(
            out,
            "    final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
        );

        // Use a fresh (non-persistent) connection per request. Dart's HttpClient keeps
        // connections alive and reuses them; when the mock server closes an idle keep-alive
        // socket, the next reused request races into a "Connection reset by peer". Disabling
        // persistence trades a little speed for deterministic, reset-free runs.
        let _ = writeln!(out, "    ioReq.persistentConnection = false;");

        // Disable automatic redirect following for 3xx fixtures so the test can
        // assert on the redirect status code itself.
        if self.is_redirect.get() {
            let _ = writeln!(out, "    ioReq.followRedirects = false;");
        }

        // Set content-type header.
        if !effective_content_type.is_empty() {
            let escaped_ct = escape_dart(effective_content_type);
            let _ = writeln!(out, "    ioReq.headers.set('content-type', '{escaped_ct}');");
        }

        // Set request headers (skip dart:io restricted headers and content-type, already handled).
        let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
        header_pairs.sort_by_key(|(k, _)| k.as_str());
        for (name, value) in &header_pairs {
            if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
                continue;
            }
            if name.to_lowercase() == "content-type" {
                continue; // Already handled above.
            }
            let escaped_name = escape_dart(&name.to_lowercase());
            let escaped_value = escape_dart(value);
            let _ = writeln!(out, "    ioReq.headers.set('{escaped_name}', '{escaped_value}');");
        }

        // Add cookies.
        if !ctx.cookies.is_empty() {
            let mut cookie_pairs: Vec<(&String, &String)> = ctx.cookies.iter().collect();
            cookie_pairs.sort_by_key(|(k, _)| k.as_str());
            let cookie_str: Vec<String> = cookie_pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
            let cookie_header = escape_dart(&cookie_str.join("; "));
            let _ = writeln!(out, "    ioReq.headers.set('cookie', '{cookie_header}');");
        }

        // Write body bytes if present (bypass charset-based encoding issues).
        // Set contentLength explicitly so Dart sends Content-Length rather than
        // chunked Transfer-Encoding — consistent with Python (urllib) and Go (http)
        // which both set Content-Length automatically. Chunked encoding is valid
        // HTTP/1.1 but some server configurations respond with a connection reset.
        if let Some(body) = ctx.body {
            let json_str = serde_json::to_string(body).unwrap_or_default();
            let escaped = escape_dart(&json_str);
            let _ = writeln!(out, "    final bodyBytes = utf8.encode('{escaped}');");
            let _ = writeln!(out, "    ioReq.contentLength = bodyBytes.length;");
            let _ = writeln!(out, "    ioReq.add(bodyBytes);");
        }

        let _ = writeln!(out, "    final ioResp = await ioReq.close();");
        // Always drain the response body into `bodyStr` so assertion primitives
        // (render_assert_json_body, render_assert_partial_body, etc.) can reference
        // it unconditionally. For 3xx redirect responses with followRedirects=false,
        // the mock server still sends a response body (e.g. `{}`) — draining it is
        // safe and necessary when the fixture has a body assertion.
        let _ = writeln!(out, "    final bodyStr = await ioResp.transform(utf8.decoder).join();");
    }

    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
        let _ = writeln!(
            out,
            "    expect(ioResp.statusCode, equals({status}), reason: 'status code mismatch');"
        );
    }

    /// Emit a single header assertion, handling special tokens `<<present>>`,
    /// `<<absent>>`, and `<<uuid>>`.
    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
        let escaped_name = escape_dart(&name.to_lowercase());
        match expected {
            "<<present>>" => {
                let _ = writeln!(
                    out,
                    "    expect(ioResp.headers.value('{escaped_name}'), isNotNull, reason: 'header {escaped_name} should be present');"
                );
            }
            "<<absent>>" => {
                let _ = writeln!(
                    out,
                    "    expect(ioResp.headers.value('{escaped_name}'), isNull, reason: 'header {escaped_name} should be absent');"
                );
            }
            "<<uuid>>" => {
                let _ = writeln!(
                    out,
                    "    expect(ioResp.headers.value('{escaped_name}'), matches(RegExp(r'^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$')), reason: 'header {escaped_name} should be a UUID');"
                );
            }
            exact => {
                let escaped_value = escape_dart(exact);
                let _ = writeln!(
                    out,
                    "    expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
                );
            }
        }
    }

    /// Emit an exact-equality body assertion.
    ///
    /// String bodies are compared as decoded text; structured JSON bodies are
    /// compared via `jsonDecode`.
    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 = escape_dart(&json_str);
                let _ = writeln!(out, "    final bodyJson = jsonDecode(bodyStr);");
                let _ = writeln!(out, "    final expectedJson = jsonDecode('{escaped}');");
                let _ = writeln!(
                    out,
                    "    expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
                );
            }
            serde_json::Value::String(s) => {
                let escaped = escape_dart(s);
                let _ = writeln!(
                    out,
                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
                );
            }
            other => {
                let escaped = escape_dart(&other.to_string());
                let _ = writeln!(
                    out,
                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
                );
            }
        }
    }

    /// Emit partial-body assertions — every key in `expected` must match the
    /// corresponding field in the parsed JSON response.
    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
        let _ = writeln!(
            out,
            "    final partialJson = jsonDecode(bodyStr) as Map<String, dynamic>;"
        );
        if let Some(obj) = expected.as_object() {
            for (idx, (key, val)) in obj.iter().enumerate() {
                let escaped_key = escape_dart(key);
                let json_val = serde_json::to_string(val).unwrap_or_default();
                let escaped_val = escape_dart(&json_val);
                // Use an index-based variable name so keys with special characters
                // don't produce invalid Dart identifiers.
                let _ = writeln!(out, "    final _expectedField{idx} = jsonDecode('{escaped_val}');");
                let _ = writeln!(
                    out,
                    "    expect(partialJson['{escaped_key}'], equals(_expectedField{idx}), reason: 'partial body field \\'{escaped_key}\\' mismatch');"
                );
            }
        }
    }

    /// Emit validation-error assertions for 422 responses.
    fn render_assert_validation_errors(
        &self,
        out: &mut String,
        _response_var: &str,
        errors: &[ValidationErrorExpectation],
    ) {
        let _ = writeln!(out, "    final errBody = jsonDecode(bodyStr) as Map<String, dynamic>;");
        let _ = writeln!(out, "    final errList = (errBody['errors'] ?? []) as List<dynamic>;");
        for ve in errors {
            let loc_dart: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_dart(s))).collect();
            let loc_str = loc_dart.join(", ");
            let escaped_msg = escape_dart(&ve.msg);
            let _ = writeln!(
                out,
                "    expect(errList.any((e) => e is Map && (e['loc'] as List?)?.join(',') == [{loc_str}].join(',') && (e['msg'] as String? ?? '').contains('{escaped_msg}')), isTrue, reason: 'validation error not found: {escaped_msg}');"
            );
        }
    }
}

/// Render a `package:test` `test(...)` block for an HTTP server fixture.
///
/// Delegates to the shared [`client::http_call::render_http_test`] driver via
/// [`DartTestClientRenderer`]. HTTP 101 (WebSocket upgrade) fixtures are emitted
/// as skip stubs before reaching the driver because `dart:io HttpClient` cannot
/// handle protocol-switch responses.
fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
    // HTTP 101 (WebSocket upgrade) — dart:io HttpClient cannot handle upgrade responses.
    if http.expected_response.status_code == 101 {
        let description = escape_dart(&fixture.description);
        let _ = writeln!(out, "  test('{description}', () {{");
        let _ = writeln!(
            out,
            "    markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
        );
        let _ = writeln!(out, "  }});");
        let _ = writeln!(out);
        return;
    }

    // Pre-set `is_redirect` on the renderer so `render_call` can inject
    // `ioReq.followRedirects = false` for 3xx fixtures. The shared driver has no
    // concept of expected status code so we thread it through renderer state.
    let is_redirect = http.expected_response.status_code / 100 == 3;
    client::http_call::render_http_test(out, &DartTestClientRenderer::new(is_redirect), fixture);
}

/// Infer a MIME type from a file path extension.
///
/// Returns `None` when the extension is unknown so the caller can supply a fallback.
/// Used in dart e2e tests when a fixture omits `mime_type` but uses a `file_path` arg.
fn mime_from_extension(path: &str) -> Option<&'static str> {
    let ext = path.rsplit('.').next()?;
    match ext.to_lowercase().as_str() {
        "docx" => Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
        "xlsx" => Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
        "pptx" => Some("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
        "pdf" => Some("application/pdf"),
        "txt" | "text" => Some("text/plain"),
        "html" | "htm" => Some("text/html"),
        "json" => Some("application/json"),
        "xml" => Some("application/xml"),
        "csv" => Some("text/csv"),
        "md" | "markdown" => Some("text/markdown"),
        "png" => Some("image/png"),
        "jpg" | "jpeg" => Some("image/jpeg"),
        "gif" => Some("image/gif"),
        "zip" => Some("application/zip"),
        "odt" => Some("application/vnd.oasis.opendocument.text"),
        "ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),
        "odp" => Some("application/vnd.oasis.opendocument.presentation"),
        "rtf" => Some("application/rtf"),
        "epub" => Some("application/epub+zip"),
        "msg" => Some("application/vnd.ms-outlook"),
        "eml" => Some("message/rfc822"),
        // Source-code extensions resolve to the internal `text/x-source-code` MIME.
        // The bytes-path can't extract these (CodeExtractor::extract_bytes needs a
        // shebang for language detection), so the caller code in this module
        // checks the inferred MIME and routes source-code files through
        // `extractFileSync`/`extractFile` (path-based) instead of remapping to
        // the bytes facade.
        "py" | "rs" | "go" | "java" | "kt" | "kts" | "swift" | "ts" | "tsx" | "js" | "jsx" | "mjs" | "cjs" | "rb"
        | "php" | "c" | "h" | "cc" | "cpp" | "cxx" | "hh" | "hpp" | "hxx" | "cs" | "scala" | "ex" | "exs" | "erl"
        | "hrl" | "elm" | "ml" | "mli" | "fs" | "fsx" | "hs" | "lhs" | "lua" | "pl" | "pm" | "r" | "R" | "sh"
        | "bash" | "zsh" | "fish" | "ps1" | "psm1" | "psd1" | "dart" | "groovy" | "gd" | "nim" | "zig" | "v"
        | "vhdl" | "sv" | "svh" => Some("text/x-source-code"),
        _ => None,
    }
}

/// Emit a `expect(array.where(...).any(...), isTrue)` line that aggregates
/// every accessor on the element type of a `List<T>` field, mirroring
/// python's `_alef_e2e_item_texts` helper.
///
/// Since Dart e2e codegen doesn't currently carry type information for per-type
/// field classification, this fallback always tries to aggregate common text-bearing
/// accessors (kind, name, source, items, alias, and similar snake_case names) on any
/// element type. This is lenient and works well with opaque DTOs from FRB binding
/// generation where we can't statically determine the exact field structure.
///
/// Returns `None` when:
///   - `field` is missing or the field doesn't look like an array field
///
/// When matched, emits code that tries to gather text from a set of known
/// accessor names into a `[String]` and substring-matches the expected value
/// against every entry. The matcher is lenient so that fixtures asserting `"os"`
/// against the `imports` field succeed regardless of which accessor surfaces
/// the value (`ImportInfo.source`, `ImportInfo.items`, etc.).
///
/// First tries the "stringy aggregator" path: when the array element is an
/// opaque DTO with several text-bearing accessors, emit a `where(...)`
/// closure that walks every accessor and does substring matching. Falls back
/// to the catch-all path if no stringy fields are recorded for the element type.
fn dart_stringy_aggregator_contains_assert(
    field: Option<&str>,
    result_var: &str,
    field_resolver: &crate::e2e::field_access::FieldResolver,
    dart_val: &str,
) -> Option<String> {
    use crate::e2e::field_access::StringyFieldKind;
    let field = field?;
    let resolved = field_resolver.resolve(field);

    // Only handle simple top-level array fields (no nested chains).
    if resolved.contains('.') || resolved.contains('[') {
        return None;
    }

    // Check if this is a known array field. If not, we can't tell if it's a
    // list of DTOs so bail out and let the scalar list path handle it.
    if !field_resolver.is_array(field) && !field_resolver.is_array(resolved) {
        return None;
    }

    let array_accessor = field_resolver.accessor(field, "dart", result_var);

    // Try the stringy aggregator path: if the element type has multiple
    // text-bearing accessors, emit a proper aggregator instead of a catch-all.
    let root_type = field_resolver.dart_root_type().cloned();
    if let Some(elem_type) = field_resolver.dart_advance(root_type.as_deref(), resolved) {
        if let Some(stringy) = field_resolver.dart_stringy_fields(&elem_type) {
            // Only emit the aggregator if the element type has 2+ stringy fields.
            // Single-field types are better served by the simpler single-accessor path.
            if stringy.len() >= 2 {
                // flutter_rust_bridge renders struct DTOs as plain Dart classes
                // with `final` fields, so accessors are property reads (no
                // parens). Dart is statically typed — calling `item.field()` on
                // a non-callable field, or naming a field the type lacks, is a
                // compile error, not a runtime miss.
                let mut texts_lines: Vec<String> = Vec::new();
                for sf in stringy {
                    let call = sf.name.to_lower_camel_case();
                    match sf.kind {
                        StringyFieldKind::Plain => {
                            texts_lines.push(format!("            texts.add(item.{call}.toString());"));
                        }
                        StringyFieldKind::Optional => {
                            texts_lines.push(format!(
                                "            final v_{call} = item.{call};\n            if (v_{call} != null) texts.add(v_{call}.toString());"
                            ));
                        }
                        StringyFieldKind::Vec => {
                            texts_lines.push(format!(
                                "            texts.addAll(item.{call}.map((e) => e.toString()));"
                            ));
                        }
                    }
                }
                let texts_block = texts_lines.join("\n");
                // Case-insensitive substring match: enum/sealed-class fields
                // stringify to `EnumName.variant()` (lowerCamelCase variant),
                // while fixture node-type values are PascalCase (`Function`).
                return Some(format!(
                    "    expect({array_accessor}.where((item) {{\n            final texts = <String>[];\n{texts_block}\n            return texts.any((t) => t.toLowerCase().contains(({dart_val}).toString().toLowerCase()));\n          }}).isEmpty, isFalse);"
                ));
            }
        }
    }

    // Fallback: the element type's fields could not be resolved from the IR
    // (unknown root type, or fewer than two recorded stringy fields). Dart is
    // statically typed, so probing arbitrary accessor names cannot compile —
    // emit a lenient whole-object stringification match that always compiles.
    Some(format!(
        "    expect({array_accessor}.where((item) => item.toString().toLowerCase().contains(({dart_val}).toString().toLowerCase())).isEmpty, isFalse);"
    ))
}

/// Resolve the IR type name backing this call's result, mirroring
/// `swift_call_result_type`. Any of `c, csharp, java, kotlin, go, php`
/// overrides may carry a `result_type` field; the first non-empty value wins.
/// These are language-agnostic IR type names shared across every binding.
///
/// Returns `None` when no override sets `result_type`; the renderer then falls
/// back to the workspace-default root-type heuristic in `DartFirstClassMap`.
fn dart_call_result_type(call_config: &crate::core::config::e2e::CallConfig) -> Option<String> {
    const LOOKUP_LANGS: &[&str] = &["c", "csharp", "java", "kotlin", "go", "php"];
    for lang in LOOKUP_LANGS {
        if let Some(o) = call_config.overrides.get(*lang)
            && let Some(rt) = o.result_type.as_deref()
            && !rt.is_empty()
        {
            return Some(rt.to_string());
        }
    }
    None
}

/// Escape a string for embedding in a Dart single-quoted string literal.
pub(super) fn escape_dart(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('\'', "\\'")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
        .replace('$', "\\$")
}

/// Derive the Dart top-level helper function name for constructing a mirror type from JSON.
///
/// The alef dart bridge-crate generator emits a Rust free function
/// `create_<snake_type>_from_json(json: String)` for each non-opaque mirror struct.
/// FRB generates the corresponding Dart function as `createTypeNameFromJson` (camelCase).
///
/// Example: `"ChatCompletionRequest"` → `"createChatCompletionRequestFromJson"`.
fn type_name_to_create_from_json_dart(type_name: &str) -> String {
    // Convert PascalCase type name to snake_case.
    let mut snake = String::with_capacity(type_name.len() + 8);
    for (i, ch) in type_name.char_indices() {
        if ch.is_uppercase() {
            if i > 0 {
                snake.push('_');
            }
            snake.extend(ch.to_lowercase());
        } else {
            snake.push(ch);
        }
    }
    // snake is now e.g. "chat_completion_request"
    // Full Rust function name: "create_chat_completion_request_from_json"
    let rust_fn = format!("create_{snake}_from_json");
    // Convert to Dart camelCase: "createChatCompletionRequestFromJson"
    rust_fn
        .split('_')
        .enumerate()
        .map(|(i, part)| {
            if i == 0 {
                part.to_string()
            } else {
                let mut chars = part.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                }
            }
        })
        .collect::<Vec<_>>()
        .join("")
}

/// Build the Dart stringy field classification map for aggregating text accessors
/// in `Vec<T>` contains assertions. Similar to Swift's `build_swift_first_class_map`,
/// but Dart doesn't distinguish first-class vs opaque types — we just track stringy
/// fields per type for the `contains(where:)` closure aggregator.
fn build_dart_first_class_map(
    type_defs: &[crate::core::ir::TypeDef],
    enum_defs: &[crate::core::ir::EnumDef],
    e2e_config: &crate::e2e::config::E2eConfig,
) -> crate::e2e::field_access::DartFirstClassMap {
    use crate::core::ir::TypeRef;
    use crate::e2e::field_access::{StringyField, StringyFieldKind};

    let mut field_types: std::collections::HashMap<String, std::collections::HashMap<String, String>> =
        std::collections::HashMap::new();

    fn inner_named(ty: &TypeRef) -> Option<String> {
        match ty {
            TypeRef::Named(n) => Some(n.clone()),
            TypeRef::Optional(inner) | TypeRef::Vec(inner) => inner_named(inner),
            _ => None,
        }
    }

    let enum_names: std::collections::HashSet<&str> = enum_defs.iter().map(|e| e.name.as_str()).collect();
    let classify_stringy = |ty: &TypeRef, field_optional: bool| -> Option<StringyFieldKind> {
        match ty {
            TypeRef::String => Some(if field_optional {
                StringyFieldKind::Optional
            } else {
                StringyFieldKind::Plain
            }),
            TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(if field_optional {
                StringyFieldKind::Optional
            } else {
                StringyFieldKind::Plain
            }),
            TypeRef::Optional(inner) => match inner.as_ref() {
                TypeRef::String => Some(StringyFieldKind::Optional),
                TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(StringyFieldKind::Optional),
                _ => None,
            },
            TypeRef::Vec(inner) => match inner.as_ref() {
                TypeRef::String => Some(StringyFieldKind::Vec),
                TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(StringyFieldKind::Vec),
                _ => None,
            },
            _ => None,
        }
    };

    let mut stringy_fields_by_type: std::collections::HashMap<String, Vec<StringyField>> =
        std::collections::HashMap::new();
    for td in type_defs {
        let mut td_field_types: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        let mut td_stringy: Vec<StringyField> = Vec::new();
        for f in &td.fields {
            if let Some(named) = inner_named(&f.ty) {
                td_field_types.insert(f.name.clone(), named);
            }
            if f.binding_excluded {
                continue;
            }
            if let Some(kind) = classify_stringy(&f.ty, f.optional) {
                td_stringy.push(StringyField {
                    name: f.name.clone(),
                    kind,
                });
            }
        }
        if !td_field_types.is_empty() {
            field_types.insert(td.name.clone(), td_field_types);
        }
        if !td_stringy.is_empty() {
            stringy_fields_by_type.insert(td.name.clone(), td_stringy);
        }
    }

    // Best-effort root-type detection: pick a unique TypeDef that contains all
    // `result_fields`.
    let root_type = if e2e_config.result_fields.is_empty() {
        None
    } else {
        let matches: Vec<&crate::core::ir::TypeDef> = type_defs
            .iter()
            .filter(|td| {
                let names: std::collections::HashSet<&str> = td.fields.iter().map(|f| f.name.as_str()).collect();
                e2e_config.result_fields.iter().all(|rf| names.contains(rf.as_str()))
            })
            .collect();
        if matches.len() == 1 {
            Some(matches[0].name.clone())
        } else {
            None
        }
    };

    crate::e2e::field_access::DartFirstClassMap {
        field_types,
        root_type,
        stringy_fields_by_type,
    }
}

/// Emit a Dart test backend stub class for a trait bridge.
///
/// Generates a concrete subclass of the trait's abstract base class. Required
/// methods are overridden with `Future.value(default)` (async) or the direct
/// default (sync). The `name` getter is emitted when a Plugin super-trait is
/// configured.
#[allow(unused_imports)]
pub fn emit_test_backend(
    trait_bridge: &crate::core::config::TraitBridgeConfig,
    methods: &[&crate::core::ir::MethodDef],
    fixture: &crate::e2e::fixture::Fixture,
) -> super::TestBackendEmission {
    use crate::backends::dart::type_map::DartMapper;
    use crate::codegen::defaults::language_defaults;
    use crate::codegen::type_mapper::TypeMapper as _;
    use heck::{ToLowerCamelCase, ToUpperCamelCase};
    use std::fmt::Write as _;

    let pascal_id = fixture.id.to_upper_camel_case();
    let class_name = format!("TestStub{pascal_id}");
    let trait_class = &trait_bridge.trait_name;

    // Prefer the fixture's input "name" field (e.g. "test-extractor") over the
    // fixture id, which is a snake_case internal identifier not a backend name.
    let plugin_name = fixture
        .input
        .get("name")
        .and_then(|v| v.as_str())
        .unwrap_or(&fixture.id)
        .to_string();

    let defaults = language_defaults("dart");
    let mapper = DartMapper;

    // Collect all types used in method signatures to determine needed imports.
    let mut needs_uint8list = false;
    for method in methods {
        for param in &method.params {
            if param.ty == crate::core::ir::TypeRef::Bytes {
                needs_uint8list = true;
            }
        }
        if method.return_type == crate::core::ir::TypeRef::Bytes {
            needs_uint8list = true;
        }
    }

    let mut setup = String::new();
    let _ = writeln!(setup, "class {class_name} extends {trait_class} {{");

    // Plugin super-trait `name` getter — no @override on local class members.
    if trait_bridge.super_trait.is_some() {
        let escaped_name = escape_dart(&plugin_name);
        let _ = writeln!(setup, "  String get name => '{escaped_name}';");
    }

    // Emit all methods (both required and optional with defaults) so the factory wrapper
    // can invoke them all. Optional methods return default values.
    for method in methods {
        let method_name = method.name.to_lower_camel_case();

        // Build typed parameter list using DartMapper for concrete type names.
        let params: Vec<String> = method
            .params
            .iter()
            .map(|p| {
                let param_type = map_dart_type_with_fallback(&mapper, &p.ty);
                format!("{} {}", param_type, p.name.to_lower_camel_case())
            })
            .collect();
        let params_str = params.join(", ");

        let return_type = map_dart_type_with_fallback(&mapper, &method.return_type);
        let default_val = emit_dart_default_for_type(defaults.as_ref(), &method.return_type);

        // Always emit `Future<T> ... async => default` to match the abstract trait, which
        // wraps every method in `Future<T>` because FRB bridges every Dart-side callback as
        // `DartFnFuture<T>`. Mirroring this on sync methods avoids "return type 'int' does
        // not match overridden 'Future<int>'" errors when subclassing the abstract trait.
        let _ = method.is_async;
        let _ = writeln!(
            setup,
            "  Future<{return_type}> {method_name}({params_str}) async => {default_val};"
        );
    }

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

    // Dart trait bridges require wrapping the implementation in a `create<Trait>DartImpl()` call.
    // The wrapper requires pluginName, pluginVersion, and callbacks for all trait methods.
    let create_fn = format!("create{}DartImpl", trait_bridge.trait_name);
    let plugin_name = fixture
        .input
        .get("name")
        .and_then(|v| v.as_str())
        .unwrap_or(&fixture.id);

    let instance_name = format!("_{class_name}_instance");
    let factory_fn = format!("_create{class_name}Wrapper");

    // Emit the instance creation and factory initialization.
    // For module-level scope: declare a factory function that does the async work.
    // The actual test will call this factory function when needed.
    let _ = writeln!(setup, "final {instance_name} = {class_name}();");
    let trait_name = &trait_bridge.trait_name;
    let _ = writeln!(
        setup,
        "Future<{trait_name}DartImpl> {factory_fn}() async => await {create_fn}("
    );
    let escaped_plugin_name = escape_dart(plugin_name);
    let _ = writeln!(setup, "  pluginName: '{escaped_plugin_name}',");
    let _ = writeln!(setup, "  pluginVersion: '0.0.1',");

    // Emit method callbacks for all methods (required and optional). The factory wrapper
    // requires callbacks for all trait methods to satisfy the Rust bridge signature.
    // Skip binding_excluded methods — these are not part of the FRB-generated factory.
    // Closure parameters are emitted with explicit Dart types so they satisfy the
    // typed `BoxFn…` parameter of the FRB-generated factory; bare `(a, b) => …`
    // closures infer `dynamic` and fail Dart strong-mode type checks.
    let emitted_methods: Vec<_> = methods.iter().filter(|m| !m.binding_excluded).collect();
    for (i, method) in emitted_methods.iter().enumerate() {
        let method_name = method.name.to_lower_camel_case();
        let typed_params: Vec<String> = method
            .params
            .iter()
            .map(|p| {
                let ty = map_dart_type_with_fallback(&mapper, &p.ty);
                format!("{} {}", ty, p.name.to_lower_camel_case())
            })
            .collect();
        let typed_params_str = typed_params.join(", ");
        let param_names: Vec<String> = method.params.iter().map(|p| p.name.to_lower_camel_case()).collect();
        let arg_pass = param_names.join(", ");
        let binding = if param_names.is_empty() {
            format!("{method_name}: () => {instance_name}.{method_name}()")
        } else {
            format!("{method_name}: ({typed_params_str}) => {instance_name}.{method_name}({arg_pass})")
        };
        let comma = if i < emitted_methods.len() - 1 { "," } else { "" };
        let _ = writeln!(setup, "  {binding}{comma}");
    }
    let _ = writeln!(setup, ");");

    let mut type_imports = Vec::new();
    if needs_uint8list {
        type_imports.push("dart:typed_data".to_string());
    }

    // The arg_expr is a call to the factory function, which returns a Future.
    let factory_fn = format!("_create{class_name}Wrapper");
    let arg_expr = format!("await {factory_fn}()");

    super::TestBackendEmission {
        setup_block: setup,
        arg_expr,
        type_imports,
        teardown_block: String::new(),
    }
}

/// Map a Dart type, with an explicit bridge carrier for internal-only types.
/// Internal named types use a generated `<TypeName>Bridge` carrier so tests preserve
/// the Rust trait contract instead of substituting a public DTO.
fn map_dart_type_with_fallback(
    mapper: &crate::backends::dart::type_map::DartMapper,
    ty: &crate::core::ir::TypeRef,
) -> String {
    use crate::codegen::type_mapper::TypeMapper as _;
    if let crate::core::ir::TypeRef::Named(name) = ty {
        if name.contains("Internal") {
            return format!("{name}Bridge");
        }
    }
    mapper.map_type(ty).to_string()
}

/// Emit a Dart default value for a type, with special handling for enums and internal types.
fn emit_dart_default_for_type(
    defaults: &dyn crate::codegen::defaults::LanguageDefaults,
    ty: &crate::core::ir::TypeRef,
) -> String {
    use crate::core::ir::TypeRef;

    // Map internal-only types to the opaque bridge carrier for default generation.
    let effective_ty = match ty {
        TypeRef::Named(name) if name.contains("Internal") => TypeRef::Named(format!("{name}Bridge")),
        _ => ty.clone(),
    };

    if let TypeRef::Named(_) = &effective_ty {
        // Avoid `T()` defaults because the FRB-generated class or enum may require
        // constructor params or a specific variant we cannot enumerate generically. Stubs in the
        // generated e2e plugin tests are registration-only — methods are never invoked —
        // so a `throw UnimplementedError()` body is type-safe (Never assignable to T)
        // and semantically correct.
        return "throw UnimplementedError()".to_string();
    }
    // Integer primitives default to `1` (not `0`). Floats stay at `0.0`;
    // booleans stay at `false`. Mirrors the Python e2e generator policy.
    if let TypeRef::Primitive(p) = &effective_ty {
        use crate::core::ir::PrimitiveType;
        match p {
            PrimitiveType::Bool | PrimitiveType::F32 | PrimitiveType::F64 => {}
            _ => return "1".to_string(),
        }
    }
    defaults.emit_default(&effective_ty).to_string()
}

#[cfg(test)]
mod test_backend_tests {
    use super::emit_test_backend;
    use crate::core::config::TraitBridgeConfig;
    use crate::core::ir::{MethodDef, PrimitiveType, TypeRef};
    use crate::e2e::fixture::Fixture;

    fn make_trait_bridge(trait_name: &str) -> TraitBridgeConfig {
        TraitBridgeConfig {
            trait_name: trait_name.to_string(),
            super_trait: Some("Plugin".to_string()),
            register_fn: Some(format!("register_{}", trait_name.to_lowercase())),
            ..Default::default()
        }
    }

    fn make_method(name: &str, required: bool) -> MethodDef {
        MethodDef {
            name: name.to_string(),
            params: vec![],
            return_type: TypeRef::Primitive(PrimitiveType::Bool),
            is_async: true,
            is_static: false,
            error_type: None,
            doc: String::new(),
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: !required,
            binding_excluded: false,
            binding_exclusion_reason: None,
        }
    }

    fn make_fixture(id: &str) -> Fixture {
        Fixture {
            id: id.to_string(),
            category: None,
            description: "test".to_string(),
            tags: vec![],
            skip: None,
            env: None,
            call: None,
            input: serde_json::Value::Null,
            mock_response: None,
            source: String::new(),
            http: None,
            assertions: vec![],
            visitor: None,
            args: vec![],
        }
    }

    /// Verify that no sample_core-domain names leak into the generated output when
    /// the trait bridge is configured for a synthetic `TestTrait` in `testlib`.
    #[test]
    fn dart_stub_contains_no_sample_crate_domain_names() {
        let bridge = make_trait_bridge("TestTrait");
        let required_method = make_method("doWork", true);
        let methods = [&required_method];
        let fixture = make_fixture("my_test_fixture");

        let emission = emit_test_backend(&bridge, &methods, &fixture);

        let output = format!("{}\n{}", emission.setup_block, emission.arg_expr);

        assert!(
            !output.contains("SampleCrate"),
            "must not contain literal 'SampleCrate', got:\n{output}"
        );
        assert!(
            !output.contains("sample_crate::"),
            "must not contain 'sample_crate::', got:\n{output}"
        );
        assert!(
            !output.contains("SampleCrateBridge"),
            "must not contain 'SampleCrateBridge', got:\n{output}"
        );
        assert!(
            output.contains("TestStubMyTestFixture"),
            "class name must be derived from fixture id, got:\n{output}"
        );
        assert!(
            output.contains("extends TestTrait"),
            "class must extend the configured trait class, got:\n{output}"
        );
        assert!(
            output.contains("doWork"),
            "required method must be emitted, got:\n{output}"
        );
    }

    fn make_param(name: &str, ty: TypeRef) -> crate::core::ir::ParamDef {
        crate::core::ir::ParamDef {
            name: name.to_string(),
            ty,
            optional: false,
            default: None,
            sanitized: false,
            typed_default: None,
            is_ref: false,
            is_mut: false,
            newtype_wrapper: None,
            original_type: None,
            map_is_ahash: false,
            map_key_is_cow: false,
            vec_inner_is_ref: false,
        }
    }

    fn make_method_with_params(name: &str, required: bool) -> MethodDef {
        MethodDef {
            name: name.to_string(),
            params: vec![
                make_param("content", TypeRef::Bytes),
                make_param("mime_type", TypeRef::String),
            ],
            return_type: TypeRef::Named("SampleResult".to_string()),
            is_async: true,
            is_static: false,
            error_type: Some("anyhow::Error".to_string()),
            doc: String::new(),
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: !required,
            binding_excluded: false,
            binding_exclusion_reason: None,
        }
    }

    /// Verify params use concrete Dart types (not `dynamic`) and no @override annotation.
    #[test]
    fn dart_stub_uses_typed_params_not_dynamic() {
        let bridge = make_trait_bridge("TestTrait");
        let required_method = make_method_with_params("extract", true);
        let methods = [&required_method];
        let fixture = make_fixture("my_test_fixture");

        let emission = emit_test_backend(&bridge, &methods, &fixture);
        let output = format!("{}\n{}", emission.setup_block, emission.arg_expr);

        assert!(
            !output.contains("dynamic content"),
            "param must not use `dynamic`, got:\n{output}"
        );
        assert!(
            output.contains("Uint8List content"),
            "bytes param must map to Uint8List, got:\n{output}"
        );
        assert!(
            output.contains("String mimeType"),
            "string param must map to String, got:\n{output}"
        );
        assert!(
            output.contains("Future<SampleResult>"),
            "return type must be concrete not dynamic, got:\n{output}"
        );
        assert!(
            !output.contains("@override"),
            "local class members must not use @override annotation, got:\n{output}"
        );
    }

    /// Verify that `fixture.input["name"]` is used as the plugin name when present.
    #[test]
    fn dart_stub_uses_fixture_input_name_for_plugin_name() {
        let bridge = make_trait_bridge("TestTrait");
        let required_method = make_method("doWork", true);
        let methods = [&required_method];
        let mut fixture = make_fixture("my_fixture_id");
        fixture.input = serde_json::json!({ "name": "my-backend-name" });

        let emission = emit_test_backend(&bridge, &methods, &fixture);
        let output = format!("{}\n{}", emission.setup_block, emission.arg_expr);

        assert!(
            output.contains("'my-backend-name'"),
            "plugin name must come from fixture.input.name, got:\n{output}"
        );
        assert!(
            !output.contains("my_fixture_id"),
            "fixture id must not appear as plugin name when input.name is set, got:\n{output}"
        );
    }
}