alef-e2e 0.13.2

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

use crate::codegen::resolve_field;
use crate::config::E2eConfig;
use crate::escape::{escape_rust, rust_raw_string, sanitize_filename, sanitize_ident};
use crate::field_access::FieldResolver;
use crate::fixture::{Assertion, CallbackAction, CorsConfig, Fixture, FixtureGroup, StaticFilesConfig};
use alef_core::backend::GeneratedFile;
use alef_core::config::AlefConfig;
use alef_core::hash::{self, CommentStyle};
use alef_core::template_versions as tv;
use anyhow::Result;
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

/// Rust e2e test code generator.
pub struct RustE2eCodegen;

impl super::E2eCodegen for RustE2eCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        alef_config: &AlefConfig,
    ) -> Result<Vec<GeneratedFile>> {
        let mut files = Vec::new();
        let output_base = PathBuf::from(e2e_config.effective_output()).join("rust");

        // Resolve crate name and path from config.
        let crate_name = resolve_crate_name(e2e_config, alef_config);
        let crate_path = resolve_crate_path(e2e_config, &crate_name);
        let dep_name = crate_name.replace('-', "_");

        // Cargo.toml
        // Check if any call config (default or named) uses json_object/handle args (needs serde_json dep).
        let all_call_configs = std::iter::once(&e2e_config.call).chain(e2e_config.calls.values());
        let needs_serde_json = all_call_configs
            .flat_map(|c| c.args.iter())
            .any(|a| a.arg_type == "json_object" || a.arg_type == "handle");

        // Check if any fixture in any group requires a mock HTTP server.
        // This includes both liter-llm mock_response fixtures and spikard http fixtures.
        let needs_mock_server = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .any(|f| !is_skipped(f, "rust") && f.mock_response.is_some());

        // Check if any fixture uses the http integration test pattern (spikard http fixtures).
        let needs_http_tests = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .any(|f| !is_skipped(f, "rust") && f.http.is_some());

        // Check if any http fixture uses CORS or static-files middleware (needs tower-http).
        let needs_tower_http = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .filter(|f| !is_skipped(f, "rust"))
            .filter_map(|f| f.http.as_ref())
            .filter_map(|h| h.handler.middleware.as_ref())
            .any(|m| m.cors.is_some() || m.static_files.is_some());

        // Tokio is needed when any test is async (mock server, http tests, or async call config).
        let any_async_call = std::iter::once(&e2e_config.call)
            .chain(e2e_config.calls.values())
            .any(|c| c.r#async);
        let needs_tokio = needs_mock_server || needs_http_tests || any_async_call;

        let crate_version = resolve_crate_version(e2e_config);
        files.push(GeneratedFile {
            path: output_base.join("Cargo.toml"),
            content: render_cargo_toml(
                &crate_name,
                &dep_name,
                &crate_path,
                needs_serde_json,
                needs_mock_server,
                needs_http_tests,
                needs_tokio,
                needs_tower_http,
                e2e_config.dep_mode,
                crate_version.as_deref(),
                &alef_config.crate_config.features,
            ),
            generated_header: true,
        });

        // Generate mock_server.rs when at least one fixture uses mock_response.
        if needs_mock_server {
            files.push(GeneratedFile {
                path: output_base.join("tests").join("mock_server.rs"),
                content: render_mock_server_module(),
                generated_header: true,
            });
        }
        // Always generate standalone mock-server binary for cross-language e2e suites
        // when any fixture has http data (serves fixture responses for non-Rust tests).
        if needs_mock_server || needs_http_tests {
            files.push(GeneratedFile {
                path: output_base.join("src").join("main.rs"),
                content: render_mock_server_binary(),
                generated_header: true,
            });
        }

        // Per-category test files.
        for group in groups {
            let fixtures: Vec<&Fixture> = group.fixtures.iter().filter(|f| !is_skipped(f, "rust")).collect();

            if fixtures.is_empty() {
                continue;
            }

            let filename = format!("{}_test.rs", sanitize_filename(&group.category));
            let content = render_test_file(&group.category, &fixtures, e2e_config, &dep_name, needs_mock_server);

            files.push(GeneratedFile {
                path: output_base.join("tests").join(filename),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

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

// ---------------------------------------------------------------------------
// Config resolution helpers
// ---------------------------------------------------------------------------

fn resolve_crate_name(_e2e_config: &E2eConfig, alef_config: &AlefConfig) -> String {
    // Always use the Cargo package name (with hyphens) from alef.toml [crate].
    // The `crate_name` override in [e2e.call.overrides.rust] is for the Rust
    // import identifier, not the Cargo package name.
    alef_config.crate_config.name.clone()
}

fn resolve_crate_path(e2e_config: &E2eConfig, crate_name: &str) -> String {
    e2e_config
        .resolve_package("rust")
        .and_then(|p| p.path.clone())
        .unwrap_or_else(|| format!("../../crates/{crate_name}"))
}

fn resolve_crate_version(e2e_config: &E2eConfig) -> Option<String> {
    e2e_config.resolve_package("rust").and_then(|p| p.version.clone())
}

fn resolve_function_name_for_call(call_config: &crate::config::CallConfig) -> String {
    call_config
        .overrides
        .get("rust")
        .and_then(|o| o.function.clone())
        .unwrap_or_else(|| call_config.function.clone())
}

fn resolve_module(e2e_config: &E2eConfig, dep_name: &str) -> String {
    resolve_module_for_call(&e2e_config.call, dep_name)
}

fn resolve_module_for_call(call_config: &crate::config::CallConfig, dep_name: &str) -> String {
    // For Rust, the module name is the crate identifier (underscores).
    // Priority: override.crate_name > override.module > dep_name
    let overrides = call_config.overrides.get("rust");
    overrides
        .and_then(|o| o.crate_name.clone())
        .or_else(|| overrides.and_then(|o| o.module.clone()))
        .unwrap_or_else(|| dep_name.to_string())
}

fn is_skipped(fixture: &Fixture, language: &str) -> bool {
    fixture.skip.as_ref().is_some_and(|s| s.should_skip(language))
}

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

#[allow(clippy::too_many_arguments)]
pub fn render_cargo_toml(
    crate_name: &str,
    dep_name: &str,
    crate_path: &str,
    needs_serde_json: bool,
    needs_mock_server: bool,
    needs_http_tests: bool,
    needs_tokio: bool,
    needs_tower_http: bool,
    dep_mode: crate::config::DependencyMode,
    version: Option<&str>,
    features: &[String],
) -> String {
    let e2e_name = format!("{dep_name}-e2e-rust");
    // Use only the features explicitly configured in alef.toml.
    // Do NOT auto-add "serde" — the target crate may not have that feature.
    // serde_json is added as a separate dependency when needed.
    let effective_features: Vec<&str> = features.iter().map(|s| s.as_str()).collect();
    let features_str = if effective_features.is_empty() {
        String::new()
    } else {
        format!(", default-features = false, features = {:?}", effective_features)
    };
    let dep_spec = match dep_mode {
        crate::config::DependencyMode::Registry => {
            let ver = version.unwrap_or("0.1.0");
            if crate_name != dep_name {
                format!("{dep_name} = {{ package = \"{crate_name}\", version = \"{ver}\"{features_str} }}")
            } else if effective_features.is_empty() {
                format!("{dep_name} = \"{ver}\"")
            } else {
                format!("{dep_name} = {{ version = \"{ver}\"{features_str} }}")
            }
        }
        crate::config::DependencyMode::Local => {
            if crate_name != dep_name {
                format!("{dep_name} = {{ package = \"{crate_name}\", path = \"{crate_path}\"{features_str} }}")
            } else if effective_features.is_empty() {
                format!("{dep_name} = {{ path = \"{crate_path}\" }}")
            } else {
                format!("{dep_name} = {{ path = \"{crate_path}\"{features_str} }}")
            }
        }
    };
    // serde_json is needed either when args use json_object/handle, or when the
    // mock server binary is present (it uses serde_json::Value for fixture bodies),
    // or when http integration tests are generated (they serialize fixture bodies).
    let effective_needs_serde_json = needs_serde_json || needs_mock_server || needs_http_tests;
    let serde_line = if effective_needs_serde_json {
        "\nserde_json = \"1\""
    } else {
        ""
    };
    // An empty `[workspace]` table makes the e2e crate its own workspace root, so
    // it never gets pulled into a parent crate's workspace. This means consumers
    // don't have to remember to add `e2e/rust` to `workspace.exclude`, and
    // `cargo fmt`/`cargo build` work the same whether the parent has a
    // workspace or not.
    // Mock server requires axum (HTTP router) and tokio-stream (SSE streaming).
    // The standalone binary additionally needs serde (derive) and walkdir.
    // Http integration tests require axum-test for the test server.
    let needs_axum = needs_mock_server || needs_http_tests;
    let mock_lines = if needs_axum {
        let mut lines = format!(
            "\naxum = \"{axum}\"\nserde = {{ version = \"1\", features = [\"derive\"] }}\nwalkdir = \"{walkdir}\"",
            axum = tv::cargo::AXUM,
            walkdir = tv::cargo::WALKDIR,
        );
        if needs_mock_server {
            lines.push_str(&format!(
                "\ntokio-stream = \"{tokio_stream}\"",
                tokio_stream = tv::cargo::TOKIO_STREAM
            ));
        }
        if needs_http_tests {
            lines.push_str("\naxum-test = \"20\"\nbytes = \"1\"");
        }
        if needs_tower_http {
            lines.push_str(&format!(
                "\ntower-http = {{ version = \"{tower_http}\", features = [\"cors\", \"fs\"] }}\ntempfile = \"{tempfile}\"",
                tower_http = tv::cargo::TOWER_HTTP,
                tempfile = tv::cargo::TEMPFILE,
            ));
        }
        lines
    } else {
        String::new()
    };
    let mut machete_ignored: Vec<&str> = Vec::new();
    if effective_needs_serde_json {
        machete_ignored.push("\"serde_json\"");
    }
    if needs_axum {
        machete_ignored.push("\"axum\"");
        machete_ignored.push("\"serde\"");
        machete_ignored.push("\"walkdir\"");
    }
    if needs_mock_server {
        machete_ignored.push("\"tokio-stream\"");
    }
    if needs_http_tests {
        machete_ignored.push("\"axum-test\"");
        machete_ignored.push("\"bytes\"");
    }
    if needs_tower_http {
        machete_ignored.push("\"tower-http\"");
        machete_ignored.push("\"tempfile\"");
    }
    let machete_section = if machete_ignored.is_empty() {
        String::new()
    } else {
        format!(
            "\n[package.metadata.cargo-machete]\nignored = [{}]\n",
            machete_ignored.join(", ")
        )
    };
    let tokio_line = if needs_tokio {
        "\ntokio = { version = \"1\", features = [\"full\"] }"
    } else {
        ""
    };
    let bin_section = if needs_mock_server || needs_http_tests {
        "\n[[bin]]\nname = \"mock-server\"\npath = \"src/main.rs\"\n"
    } else {
        ""
    };
    let header = hash::header(CommentStyle::Hash);
    format!(
        r#"{header}
[workspace]

[package]
name = "{e2e_name}"
version = "0.1.0"
edition = "2021"
license = "MIT"
publish = false
{bin_section}
[dependencies]
{dep_spec}{serde_line}{mock_lines}{tokio_line}
{machete_section}"#
    )
}

fn render_test_file(
    category: &str,
    fixtures: &[&Fixture],
    e2e_config: &E2eConfig,
    dep_name: &str,
    needs_mock_server: bool,
) -> String {
    let mut out = String::new();
    out.push_str(&hash::header(CommentStyle::DoubleSlash));
    let _ = writeln!(out, "//! E2e tests for category: {category}");
    let _ = writeln!(out);

    let module = resolve_module(e2e_config, dep_name);
    let field_resolver = FieldResolver::new(
        &e2e_config.fields,
        &e2e_config.fields_optional,
        &e2e_config.result_fields,
        &e2e_config.fields_array,
    );

    // Check if this file has http-fixture tests (separate from call-based tests).
    let file_has_http = fixtures.iter().any(|f| f.http.is_some());
    // Call-based: has mock_response (liter-llm style), NOT pure stub fixtures.
    // Pure stub fixtures (neither http nor mock_response) use a stub path — no function import.
    let file_has_call_based = fixtures.iter().any(|f| f.mock_response.is_some());

    // Collect all unique (module, function) pairs needed across call-based fixtures only.
    // Http fixtures and stub fixtures use different code paths and don't import the call function.
    if file_has_call_based {
        let mut imported: std::collections::BTreeSet<(String, String)> = std::collections::BTreeSet::new();
        for fixture in fixtures.iter().filter(|f| f.mock_response.is_some()) {
            let call_config = e2e_config.resolve_call(fixture.call.as_deref());
            let fn_name = resolve_function_name_for_call(call_config);
            let mod_name = resolve_module_for_call(call_config, dep_name);
            imported.insert((mod_name, fn_name));
        }
        // Emit use statements, grouping by module when possible.
        let mut by_module: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
        for (mod_name, fn_name) in &imported {
            by_module.entry(mod_name.clone()).or_default().push(fn_name.clone());
        }
        for (mod_name, fns) in &by_module {
            if fns.len() == 1 {
                let _ = writeln!(out, "use {mod_name}::{};", fns[0]);
            } else {
                let joined = fns.join(", ");
                let _ = writeln!(out, "use {mod_name}::{{{joined}}};");
            }
        }
    }

    // Http fixtures use App + RequestContext for integration tests.
    if file_has_http {
        let _ = writeln!(out, "use {module}::{{App, RequestContext}};");
    }

    // Import handle constructor functions and the config type they use.
    let has_handle_args = e2e_config.call.args.iter().any(|a| a.arg_type == "handle");
    if has_handle_args {
        let _ = writeln!(out, "use {module}::CrawlConfig;");
    }
    for arg in &e2e_config.call.args {
        if arg.arg_type == "handle" {
            use heck::ToSnakeCase;
            let constructor_name = format!("create_{}", arg.name.to_snake_case());
            let _ = writeln!(out, "use {module}::{constructor_name};");
        }
    }

    // Import mock_server module when any fixture in this file uses mock_response.
    let file_needs_mock = needs_mock_server && fixtures.iter().any(|f| f.mock_response.is_some());
    if file_needs_mock {
        let _ = writeln!(out, "mod mock_server;");
        let _ = writeln!(out, "use mock_server::{{MockRoute, MockServer}};");
    }

    // Import the visitor trait, result enum, and node context when any fixture
    // in this file declares a `visitor` block. Without these, the inline
    // `impl HtmlVisitor for _TestVisitor` block fails to resolve.
    let file_needs_visitor = fixtures.iter().any(|f| f.visitor.is_some());
    if file_needs_visitor {
        let visitor_trait = resolve_visitor_trait(&module);
        let _ = writeln!(out, "use {module}::{{{visitor_trait}, NodeContext, VisitResult}};");
    }

    let _ = writeln!(out);

    for fixture in fixtures {
        render_test_function(&mut out, fixture, e2e_config, dep_name, &field_resolver);
        let _ = writeln!(out);
    }

    if !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

fn render_test_function(
    out: &mut String,
    fixture: &Fixture,
    e2e_config: &E2eConfig,
    dep_name: &str,
    field_resolver: &FieldResolver,
) {
    // Http fixtures get their own integration test code path.
    if fixture.http.is_some() {
        render_http_test_function(out, fixture, dep_name);
        return;
    }

    // Fixtures that have neither `http` nor `mock_response` are schema/spec
    // validation fixtures (asyncapi, grpc, graphql_schema, etc.). These don't
    // yet have a callable function in the Rust e2e suite — generate a stub
    // that compiles and passes to preserve test count without breaking builds.
    if fixture.http.is_none() && fixture.mock_response.is_none() {
        let fn_name = sanitize_ident(&fixture.id);
        let description = &fixture.description;
        let _ = writeln!(out, "#[tokio::test]");
        let _ = writeln!(out, "async fn test_{fn_name}() {{");
        let _ = writeln!(out, "    // {description}");
        let _ = writeln!(
            out,
            "    // TODO: implement when a callable API is available for this fixture type."
        );
        let _ = writeln!(out, "}}");
        return;
    }

    let fn_name = sanitize_ident(&fixture.id);
    let description = &fixture.description;
    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
    let function_name = resolve_function_name_for_call(call_config);
    let module = resolve_module_for_call(call_config, dep_name);
    let result_var = &call_config.result_var;
    let has_mock = fixture.mock_response.is_some();

    // Tests with a mock server are always async (Axum requires a Tokio runtime).
    let is_async = call_config.r#async || has_mock;
    if is_async {
        let _ = writeln!(out, "#[tokio::test]");
        let _ = writeln!(out, "async fn test_{fn_name}() {{");
    } else {
        let _ = writeln!(out, "#[test]");
        let _ = writeln!(out, "fn test_{fn_name}() {{");
    }
    let _ = writeln!(out, "    // {description}");

    // Emit mock server setup before building arguments so arg expressions can
    // reference `mock_server.url` when needed.
    if has_mock {
        render_mock_server_setup(out, fixture, e2e_config);
    }

    // Check if any assertion is an error assertion.
    let has_error_assertion = fixture.assertions.iter().any(|a| a.assertion_type == "error");

    // Resolve Rust-specific overrides for argument shaping.
    let rust_overrides = call_config.overrides.get("rust");
    let wrap_options_in_some = rust_overrides.is_some_and(|o| o.wrap_options_in_some);
    let extra_args: Vec<String> = rust_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();

    // Emit input variable bindings from args config.
    let mut arg_exprs: Vec<String> = Vec::new();
    for arg in &call_config.args {
        let value = resolve_field(&fixture.input, &arg.field);
        let var_name = &arg.name;
        let (bindings, expr) = render_rust_arg(
            var_name,
            value,
            &arg.arg_type,
            arg.optional,
            &module,
            &fixture.id,
            if has_mock {
                Some("mock_server.url.as_str()")
            } else {
                None
            },
            arg.owned,
            arg.element_type.as_deref(),
        );
        for binding in &bindings {
            let _ = writeln!(out, "    {binding}");
        }
        // For functions whose options slot is owned `Option<T>` rather than `&T`,
        // wrap the json_object expression in `Some(...).clone()` so it matches
        // the parameter shape. Other arg types pass through unchanged.
        let final_expr = if wrap_options_in_some && arg.arg_type == "json_object" {
            if let Some(rest) = expr.strip_prefix('&') {
                format!("Some({rest}.clone())")
            } else {
                format!("Some({expr})")
            }
        } else {
            expr
        };
        arg_exprs.push(final_expr);
    }

    // Emit visitor if present in fixture.
    if let Some(visitor_spec) = &fixture.visitor {
        let _ = writeln!(out, "    struct _TestVisitor;");
        let _ = writeln!(out, "    impl {} for _TestVisitor {{", resolve_visitor_trait(&module));
        for (method_name, action) in &visitor_spec.callbacks {
            emit_rust_visitor_method(out, method_name, action);
        }
        let _ = writeln!(out, "    }}");
        let _ = writeln!(
            out,
            "    let visitor = std::rc::Rc::new(std::cell::RefCell::new(_TestVisitor));"
        );
        arg_exprs.push("Some(visitor)".to_string());
    } else {
        // No fixture-supplied visitor: append any extra positional args declared in
        // the rust override (e.g. trailing `None` for an Option<VisitorParam> slot).
        arg_exprs.extend(extra_args);
    }

    let args_str = arg_exprs.join(", ");

    let await_suffix = if is_async { ".await" } else { "" };

    let result_is_tree = call_config.result_var == "tree";
    // When the rust override sets result_is_simple, the function returns a plain type
    // (String, Vec<T>, etc.) — field-access assertions use the result var directly.
    let result_is_simple = rust_overrides.is_some_and(|o| o.result_is_simple);
    // When result_is_vec is set, the function returns Vec<T>. Field-path assertions
    // are wrapped in `.iter().all(|r| ...)` so every element is checked.
    let result_is_vec = rust_overrides.is_some_and(|o| o.result_is_vec);
    // When result_is_option is set, the function returns Option<T>. Field-path
    // assertions unwrap first via `.as_ref().expect("Option should be Some")`.
    let result_is_option = rust_overrides.is_some_and(|o| o.result_is_option);

    if has_error_assertion {
        let _ = writeln!(out, "    let {result_var} = {function_name}({args_str}){await_suffix};");
        // Render error assertions.
        for assertion in &fixture.assertions {
            render_assertion(
                out,
                assertion,
                result_var,
                &module,
                dep_name,
                true,
                &[],
                field_resolver,
                result_is_tree,
                result_is_simple,
                false,
                false,
            );
        }
        let _ = writeln!(out, "}}");
        return;
    }

    // Non-error path: unwrap the result.
    let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");

    // Check if any assertion actually uses the result variable.
    // If all assertions are skipped (field not on result type), use `_` to avoid
    // Rust's "variable never used" warning.
    let has_usable_assertion = fixture.assertions.iter().any(|a| {
        if a.assertion_type == "not_error" || a.assertion_type == "error" {
            return false;
        }
        if a.assertion_type == "method_result" {
            // method_result assertions that would generate only a TODO comment don't use the
            // result variable. These are: missing `method` field, or unsupported `check` type.
            let supported_checks = [
                "equals",
                "is_true",
                "is_false",
                "greater_than_or_equal",
                "count_min",
                "is_error",
                "contains",
                "not_empty",
                "is_empty",
            ];
            let check = a.check.as_deref().unwrap_or("is_true");
            if a.method.is_none() || !supported_checks.contains(&check) {
                return false;
            }
        }
        match &a.field {
            Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
            _ => true,
        }
    });

    let result_binding = if has_usable_assertion {
        result_var.to_string()
    } else {
        "_".to_string()
    };

    // Detect Option-returning functions: only skip unwrap when ALL assertions are
    // pure emptiness/bool checks with NO field access (is_none/is_some on the result itself).
    // If any assertion accesses a field (e.g. `html`), we need the inner value, so unwrap.
    let has_field_access = fixture
        .assertions
        .iter()
        .any(|a| a.field.as_ref().is_some_and(|f| !f.is_empty()));
    let only_emptiness_checks = !has_field_access
        && fixture.assertions.iter().all(|a| {
            matches!(
                a.assertion_type.as_str(),
                "is_empty" | "is_false" | "not_empty" | "is_true" | "not_error"
            )
        });

    // Per-rust override of the call-level `returns_result`. When set, takes
    // precedence over `CallConfig.returns_result` for the Rust generator only.
    let returns_result = rust_overrides
        .and_then(|o| o.returns_result)
        .unwrap_or(call_config.returns_result);

    let unwrap_suffix = if returns_result {
        ".expect(\"should succeed\")"
    } else {
        ""
    };
    if only_emptiness_checks || !returns_result {
        // Option-returning or non-Result-returning: bind raw value, no unwrap.
        let _ = writeln!(
            out,
            "    let {result_binding} = {function_name}({args_str}){await_suffix};"
        );
    } else if has_not_error || !fixture.assertions.is_empty() {
        let _ = writeln!(
            out,
            "    let {result_binding} = {function_name}({args_str}){await_suffix}{unwrap_suffix};"
        );
    } else {
        let _ = writeln!(
            out,
            "    let {result_binding} = {function_name}({args_str}){await_suffix};"
        );
    }

    // Emit Option field unwrap bindings for any fields accessed in assertions.
    // Use FieldResolver to handle optional fields, including nested/aliased paths.
    // Skipped when the call returns Vec<T>: per-element iteration is emitted by
    // `render_assertion` itself, so the call-site has no single result struct
    // to unwrap fields off of.
    let string_assertion_types = [
        "equals",
        "contains",
        "contains_all",
        "contains_any",
        "not_contains",
        "starts_with",
        "ends_with",
        "min_length",
        "max_length",
        "matches_regex",
    ];
    let mut unwrapped_fields: Vec<(String, String)> = Vec::new(); // (fixture_field, local_var)
    if !result_is_vec {
        for assertion in &fixture.assertions {
            if let Some(f) = &assertion.field {
                if !f.is_empty()
                    && string_assertion_types.contains(&assertion.assertion_type.as_str())
                    && !unwrapped_fields.iter().any(|(ff, _)| ff == f)
                {
                    // Only unwrap optional string fields — numeric optionals (u64, usize)
                    // don't support .as_deref() and should be compared directly.
                    let is_string_assertion = assertion.value.as_ref().is_none_or(|v| v.is_string());
                    if !is_string_assertion {
                        continue;
                    }
                    if let Some((binding, local_var)) = field_resolver.rust_unwrap_binding(f, result_var) {
                        let _ = writeln!(out, "    {binding}");
                        unwrapped_fields.push((f.clone(), local_var));
                    }
                }
            }
        }
    }

    // Render assertions.
    for assertion in &fixture.assertions {
        if assertion.assertion_type == "not_error" {
            // Already handled by .expect() above.
            continue;
        }
        render_assertion(
            out,
            assertion,
            result_var,
            &module,
            dep_name,
            false,
            &unwrapped_fields,
            field_resolver,
            result_is_tree,
            result_is_simple,
            result_is_vec,
            result_is_option,
        );
    }

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

// ---------------------------------------------------------------------------
// Argument rendering
// ---------------------------------------------------------------------------

#[allow(clippy::too_many_arguments)]
fn render_rust_arg(
    name: &str,
    value: &serde_json::Value,
    arg_type: &str,
    optional: bool,
    module: &str,
    fixture_id: &str,
    mock_base_url: Option<&str>,
    owned: bool,
    element_type: Option<&str>,
) -> (Vec<String>, String) {
    if arg_type == "mock_url" {
        let lines = vec![format!(
            "let {name} = format!(\"{{}}/fixtures/{{}}\", std::env::var(\"MOCK_SERVER_URL\").expect(\"MOCK_SERVER_URL not set\"), \"{fixture_id}\");"
        )];
        return (lines, format!("&{name}"));
    }
    // When the arg is a base_url and a mock server is running, use the mock server URL.
    if arg_type == "base_url" {
        if let Some(url_expr) = mock_base_url {
            return (vec![], url_expr.to_string());
        }
        // No mock server: fall through to string handling below.
    }
    if arg_type == "handle" {
        // Generate a create_engine (or equivalent) call and pass the config.
        // If the fixture has input.config, serialize it as a json_object and pass it;
        // otherwise pass None.
        use heck::ToSnakeCase;
        let constructor_name = format!("create_{}", name.to_snake_case());
        let mut lines = Vec::new();
        if value.is_null() || value.is_object() && value.as_object().unwrap().is_empty() {
            lines.push(format!(
                "let {name} = {constructor_name}(None).expect(\"handle creation should succeed\");"
            ));
        } else {
            // Serialize the config JSON and deserialize at runtime.
            let json_literal = serde_json::to_string(value).unwrap_or_default();
            let escaped = json_literal.replace('\\', "\\\\").replace('"', "\\\"");
            lines.push(format!(
                "let {name}_config: CrawlConfig = serde_json::from_str(\"{escaped}\").expect(\"config should parse\");"
            ));
            lines.push(format!(
                "let {name} = {constructor_name}(Some({name}_config)).expect(\"handle creation should succeed\");"
            ));
        }
        return (lines, format!("&{name}"));
    }
    if arg_type == "json_object" {
        return render_json_object_arg(name, value, optional, owned, element_type, module);
    }
    if value.is_null() && !optional {
        // Required arg with no fixture value: use a language-appropriate default.
        let default_val = match arg_type {
            "string" => "String::new()".to_string(),
            "int" | "integer" => "0".to_string(),
            "float" | "number" => "0.0_f64".to_string(),
            "bool" | "boolean" => "false".to_string(),
            _ => "Default::default()".to_string(),
        };
        // String args are passed by reference in Rust.
        let expr = if arg_type == "string" {
            format!("&{name}")
        } else {
            name.to_string()
        };
        return (vec![format!("let {name} = {default_val};")], expr);
    }
    let literal = json_to_rust_literal(value, arg_type);
    // String args are raw string literals (`r#"..."#`) — already `&str`, no extra `&` needed.
    // Bytes args are passed by reference using `.as_bytes()` in the `expr` closure below.
    let pass_by_ref = arg_type == "bytes";
    let optional_expr = |n: &str| {
        if arg_type == "string" {
            format!("{n}.as_deref()")
        } else if arg_type == "bytes" {
            format!("{n}.as_deref().map(|v| v.as_slice())")
        } else {
            // Owned numeric / bool / generic: pass the Option<T> by value.
            // Function signature shape `Option<T>` matches without `.as_ref()`,
            // which would produce `Option<&T>` and fail to coerce.
            n.to_string()
        }
    };
    let expr = |n: &str| {
        if arg_type == "bytes" {
            format!("{n}.as_bytes()")
        } else if pass_by_ref {
            format!("&{n}")
        } else {
            n.to_string()
        }
    };
    if optional && value.is_null() {
        let none_decl = match arg_type {
            "string" => format!("let {name}: Option<String> = None;"),
            "bytes" => format!("let {name}: Option<Vec<u8>> = None;"),
            _ => format!("let {name} = None;"),
        };
        (vec![none_decl], optional_expr(name))
    } else if optional {
        (vec![format!("let {name} = Some({literal});")], optional_expr(name))
    } else {
        (vec![format!("let {name} = {literal};")], expr(name))
    }
}

/// Render a `json_object` argument: serialize the fixture JSON as a `serde_json::json!` literal
/// and deserialize it through serde at runtime. Type inference from the function signature
/// determines the concrete type, keeping the generator generic.
///
/// `owned` — when true the binding is passed by value (no leading `&`); use for `Vec<T>` params.
/// `element_type` — when set, emits `Vec<element_type>` annotation to satisfy type inference for
///   `&[T]` parameters where `serde_json::from_value` cannot resolve the unsized slice type.
fn render_json_object_arg(
    name: &str,
    value: &serde_json::Value,
    optional: bool,
    owned: bool,
    element_type: Option<&str>,
    _module: &str,
) -> (Vec<String>, String) {
    // Owned params (Vec<T>) are passed by value; ref params (most configs) use &.
    let pass_by_ref = !owned;

    if value.is_null() && optional {
        // Use Default::default() — Rust functions take &T (or T for owned), not Option<T>.
        let expr = if pass_by_ref {
            format!("&{name}")
        } else {
            name.to_string()
        };
        return (vec![format!("let {name} = Default::default();")], expr);
    }

    // Fixture keys are camelCase; the Rust ConversionOptions type uses snake_case serde.
    // Normalize keys before building the json! literal so deserialization succeeds.
    let normalized = super::normalize_json_keys_to_snake_case(value);
    // Build the json! macro invocation from the fixture object.
    let json_literal = json_value_to_macro_literal(&normalized);
    let mut lines = Vec::new();
    lines.push(format!("let {name}_json = serde_json::json!({json_literal});"));

    // When an explicit element type is given, annotate with Vec<T> so that
    // serde_json::from_value can infer the element type for &[T] parameters (A4 fix).
    let deser_expr = if let Some(elem) = element_type {
        format!("serde_json::from_value::<Vec<{elem}>>({name}_json).unwrap()")
    } else {
        format!("serde_json::from_value({name}_json).unwrap()")
    };

    // A1 fix: always deser as T (never wrap in Some()); optional non-null args target
    // &T not &Option<T>. Pass as &T (ref) or T (owned) depending on the `owned` flag.
    lines.push(format!("let {name} = {deser_expr};"));
    let expr = if pass_by_ref {
        format!("&{name}")
    } else {
        name.to_string()
    };
    (lines, expr)
}

/// Convert a `serde_json::Value` into a string suitable for the `serde_json::json!()` macro.
fn json_value_to_macro_literal(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Bool(b) => format!("{b}"),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => {
            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
            format!("\"{escaped}\"")
        }
        serde_json::Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(json_value_to_macro_literal).collect();
            format!("[{}]", items.join(", "))
        }
        serde_json::Value::Object(obj) => {
            let entries: Vec<String> = obj
                .iter()
                .map(|(k, v)| {
                    let escaped_key = k.replace('\\', "\\\\").replace('"', "\\\"");
                    format!("\"{escaped_key}\": {}", json_value_to_macro_literal(v))
                })
                .collect();
            format!("{{{}}}", entries.join(", "))
        }
    }
}

fn json_to_rust_literal(value: &serde_json::Value, arg_type: &str) -> String {
    match value {
        serde_json::Value::Null => "None".to_string(),
        serde_json::Value::Bool(b) => format!("{b}"),
        serde_json::Value::Number(n) => {
            if arg_type.contains("float") || arg_type.contains("f64") || arg_type.contains("f32") {
                if let Some(f) = n.as_f64() {
                    return format!("{f}_f64");
                }
            }
            n.to_string()
        }
        serde_json::Value::String(s) => rust_raw_string(s),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
            let json_str = serde_json::to_string(value).unwrap_or_default();
            let literal = rust_raw_string(&json_str);
            format!("serde_json::from_str({literal}).unwrap()")
        }
    }
}

// ---------------------------------------------------------------------------
// Http integration test helpers
// ---------------------------------------------------------------------------

/// How to call a method on axum_test::TestServer in generated code.
enum ServerCall<'a> {
    /// Emit `server.get(path)` / `server.post(path)` etc.
    Shorthand(&'a str),
    /// Emit `server.method(axum::http::Method::OPTIONS, path)` etc.
    AxumMethod(&'a str),
}

/// How to register a route on a spikard App in generated code.
enum RouteRegistration<'a> {
    /// Emit `spikard::get(path)` / `spikard::post(path)` etc.
    Shorthand(&'a str),
    /// Emit `spikard::RouteBuilder::new(spikard::Method::Options, path)` etc.
    Explicit(&'a str),
}

/// Generate a complete integration test function for an http fixture.
///
/// Builds a real spikard `App` with a handler that returns the expected
/// response, then uses `axum_test::TestServer` to send the request and
/// assert the status code.
fn render_http_test_function(out: &mut String, fixture: &Fixture, dep_name: &str) {
    let http = match &fixture.http {
        Some(h) => h,
        None => return,
    };

    let fn_name = sanitize_ident(&fixture.id);
    let description = &fixture.description;

    let route = &http.handler.route;

    // spikard provides convenience functions for GET/POST/PUT/PATCH/DELETE.
    // All other methods (HEAD, OPTIONS, TRACE, etc.) must use RouteBuilder::new directly.
    let route_reg = match http.handler.method.to_lowercase().as_str() {
        "get" => RouteRegistration::Shorthand("get"),
        "post" => RouteRegistration::Shorthand("post"),
        "put" => RouteRegistration::Shorthand("put"),
        "patch" => RouteRegistration::Shorthand("patch"),
        "delete" => RouteRegistration::Shorthand("delete"),
        "head" => RouteRegistration::Explicit("Head"),
        "options" => RouteRegistration::Explicit("Options"),
        "trace" => RouteRegistration::Explicit("Trace"),
        _ => RouteRegistration::Shorthand("get"),
    };

    // axum_test::TestServer has shorthand methods for GET/POST/PUT/PATCH/DELETE.
    // For HEAD and other methods, use server.method(axum::http::Method::HEAD, path).
    let server_call = match http.request.method.to_uppercase().as_str() {
        "GET" => ServerCall::Shorthand("get"),
        "POST" => ServerCall::Shorthand("post"),
        "PUT" => ServerCall::Shorthand("put"),
        "PATCH" => ServerCall::Shorthand("patch"),
        "DELETE" => ServerCall::Shorthand("delete"),
        "HEAD" => ServerCall::AxumMethod("HEAD"),
        "OPTIONS" => ServerCall::AxumMethod("OPTIONS"),
        "TRACE" => ServerCall::AxumMethod("TRACE"),
        _ => ServerCall::Shorthand("get"),
    };

    let req_path = &http.request.path;
    let status = http.expected_response.status_code;

    // Serialize expected response body (if any).
    let body_str = match &http.expected_response.body {
        Some(b) => serde_json::to_string(b).unwrap_or_else(|_| "{}".to_string()),
        None => String::new(),
    };
    let body_literal = rust_raw_string(&body_str);

    // Serialize request body (if any).
    let req_body_str = match &http.request.body {
        Some(b) => serde_json::to_string(b).unwrap_or_else(|_| "{}".to_string()),
        None => String::new(),
    };
    let has_req_body = !req_body_str.is_empty();

    // Extract middleware from handler (if any).
    let middleware = http.handler.middleware.as_ref();
    let cors_cfg: Option<&CorsConfig> = middleware.and_then(|m| m.cors.as_ref());
    let static_files_cfgs: Option<&Vec<StaticFilesConfig>> = middleware.and_then(|m| m.static_files.as_ref());
    let has_static_files = static_files_cfgs.is_some_and(|v| !v.is_empty());

    let _ = writeln!(out, "#[tokio::test]");
    let _ = writeln!(out, "async fn test_{fn_name}() {{");
    let _ = writeln!(out, "    // {description}");

    // When static-files middleware is configured, serve from a temp dir via ServeDir.
    if has_static_files {
        render_static_files_test(out, fixture, static_files_cfgs.unwrap(), &server_call, req_path, status);
        return;
    }

    // Build handler that returns the expected response.
    let _ = writeln!(out, "    let expected_body = {body_literal}.to_string();");
    let _ = writeln!(out, "    let mut app = {dep_name}::App::new();");

    // Emit route registration.
    match &route_reg {
        RouteRegistration::Shorthand(method) => {
            let _ = writeln!(
                out,
                "    app.route({dep_name}::{method}({route:?}), move |_ctx: {dep_name}::RequestContext| {{"
            );
        }
        RouteRegistration::Explicit(variant) => {
            let _ = writeln!(
                out,
                "    app.route({dep_name}::RouteBuilder::new({dep_name}::Method::{variant}, {route:?}), move |_ctx: {dep_name}::RequestContext| {{"
            );
        }
    }
    let _ = writeln!(out, "        let body = expected_body.clone();");
    let _ = writeln!(out, "        async move {{");
    let _ = writeln!(out, "            Ok(axum::http::Response::builder()");
    let _ = writeln!(out, "                .status({status}u16)");
    let _ = writeln!(out, "                .header(\"content-type\", \"application/json\")");
    let _ = writeln!(out, "                .body(axum::body::Body::from(body))");
    let _ = writeln!(out, "                .unwrap())");
    let _ = writeln!(out, "        }}");
    let _ = writeln!(out, "    }}).unwrap();");

    // Build axum-test TestServer from the app router, optionally wrapping with CorsLayer.
    let _ = writeln!(out, "    let router = app.into_router().unwrap();");
    if let Some(cors) = cors_cfg {
        render_cors_layer(out, cors);
    }
    let _ = writeln!(out, "    let server = axum_test::TestServer::new(router);");

    // Build and send the request.
    match &server_call {
        ServerCall::Shorthand(method) => {
            let _ = writeln!(out, "    let response = server.{method}({req_path:?})");
        }
        ServerCall::AxumMethod(method) => {
            let _ = writeln!(
                out,
                "    let response = server.method(axum::http::Method::{method}, {req_path:?})"
            );
        }
    }

    // Add request headers (axum_test::TestRequest::add_header accepts &str via TryInto).
    for (name, value) in &http.request.headers {
        let n = rust_raw_string(name);
        let v = rust_raw_string(value);
        let _ = writeln!(out, "        .add_header({n}, {v})");
    }

    // Add request body if present (pass as a JSON string so axum-test's bytes() API gets a Bytes value).
    if has_req_body {
        let req_body_literal = rust_raw_string(&req_body_str);
        let _ = writeln!(
            out,
            "        .bytes(bytes::Bytes::copy_from_slice({req_body_literal}.as_bytes()))"
        );
    }

    let _ = writeln!(out, "        .await;");

    // Assert status code.
    // When a CorsLayer is applied and the fixture expects a 2xx status, tower-http may
    // return 200 instead of 204 for preflight. Accept any 2xx status in that case.
    if cors_cfg.is_some() && (200..300).contains(&status) {
        let _ = writeln!(
            out,
            "    assert!(response.status_code().is_success(), \"expected CORS success status, got {{}}\", response.status_code());"
        );
    } else {
        let _ = writeln!(out, "    assert_eq!(response.status_code().as_u16(), {status}u16);");
    }

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

/// Emit lines that wrap the axum router with a `tower_http::cors::CorsLayer`.
///
/// The CORS policy is derived from the fixture's `cors` middleware config.
/// After this function, `router` is reassigned to the layer-wrapped version.
fn render_cors_layer(out: &mut String, cors: &CorsConfig) {
    let _ = writeln!(
        out,
        "    // Apply CorsLayer from tower-http based on fixture CORS config."
    );
    let _ = writeln!(out, "    use tower_http::cors::CorsLayer;");
    let _ = writeln!(out, "    use axum::http::{{HeaderName, HeaderValue, Method}};");
    let _ = writeln!(out, "    let cors_layer = CorsLayer::new()");

    // allow_origins
    if cors.allow_origins.is_empty() {
        let _ = writeln!(out, "        .allow_origin(tower_http::cors::Any)");
    } else {
        let _ = writeln!(out, "        .allow_origin([");
        for origin in &cors.allow_origins {
            let _ = writeln!(out, "            \"{origin}\".parse::<HeaderValue>().unwrap(),");
        }
        let _ = writeln!(out, "        ])");
    }

    // allow_methods
    if cors.allow_methods.is_empty() {
        let _ = writeln!(out, "        .allow_methods(tower_http::cors::Any)");
    } else {
        let methods: Vec<String> = cors
            .allow_methods
            .iter()
            .map(|m| format!("Method::{}", m.to_uppercase()))
            .collect();
        let _ = writeln!(out, "        .allow_methods([{}])", methods.join(", "));
    }

    // allow_headers
    if cors.allow_headers.is_empty() {
        let _ = writeln!(out, "        .allow_headers(tower_http::cors::Any)");
    } else {
        let headers: Vec<String> = cors
            .allow_headers
            .iter()
            .map(|h| {
                let lower = h.to_lowercase();
                match lower.as_str() {
                    "content-type" => "axum::http::header::CONTENT_TYPE".to_string(),
                    "authorization" => "axum::http::header::AUTHORIZATION".to_string(),
                    "accept" => "axum::http::header::ACCEPT".to_string(),
                    _ => format!("HeaderName::from_static(\"{lower}\")"),
                }
            })
            .collect();
        let _ = writeln!(out, "        .allow_headers([{}])", headers.join(", "));
    }

    // max_age
    if let Some(secs) = cors.max_age {
        let _ = writeln!(out, "        .max_age(std::time::Duration::from_secs({secs}));");
    } else {
        let _ = writeln!(out, "        ;");
    }

    let _ = writeln!(out, "    let router = router.layer(cors_layer);");
}

/// Emit lines for a static-files integration test.
///
/// Writes fixture files to a temporary directory and serves them via
/// `tower_http::services::ServeDir`, bypassing the spikard App entirely.
fn render_static_files_test(
    out: &mut String,
    fixture: &Fixture,
    cfgs: &[StaticFilesConfig],
    server_call: &ServerCall<'_>,
    req_path: &str,
    status: u16,
) {
    let http = fixture.http.as_ref().unwrap();

    let _ = writeln!(out, "    use tower_http::services::ServeDir;");
    let _ = writeln!(out, "    use axum::Router;");
    let _ = writeln!(out, "    let tmp_dir = tempfile::tempdir().expect(\"tmp dir\");");

    // Build the router by nesting a ServeDir for each config entry.
    let _ = writeln!(out, "    let mut router = Router::new();");
    for cfg in cfgs {
        for file in &cfg.files {
            let file_path = file.path.replace('\\', "/");
            let content = rust_raw_string(&file.content);
            if file_path.contains('/') {
                let parent: String = file_path.rsplitn(2, '/').last().unwrap_or("").to_string();
                let _ = writeln!(
                    out,
                    "    std::fs::create_dir_all(tmp_dir.path().join(\"{parent}\")).unwrap();"
                );
            }
            let _ = writeln!(
                out,
                "    std::fs::write(tmp_dir.path().join(\"{file_path}\"), {content}).unwrap();"
            );
        }
        let prefix = &cfg.route_prefix;
        let serve_dir_expr = if cfg.index_file {
            "ServeDir::new(tmp_dir.path()).append_index_html_on_directories(true)".to_string()
        } else {
            "ServeDir::new(tmp_dir.path())".to_string()
        };
        let _ = writeln!(out, "    router = router.nest_service({prefix:?}, {serve_dir_expr});");
    }

    let _ = writeln!(out, "    let server = axum_test::TestServer::new(router);");

    // Build and send the request.
    match server_call {
        ServerCall::Shorthand(method) => {
            let _ = writeln!(out, "    let response = server.{method}({req_path:?})");
        }
        ServerCall::AxumMethod(method) => {
            let _ = writeln!(
                out,
                "    let response = server.method(axum::http::Method::{method}, {req_path:?})"
            );
        }
    }

    // Add request headers.
    for (name, value) in &http.request.headers {
        let n = rust_raw_string(name);
        let v = rust_raw_string(value);
        let _ = writeln!(out, "        .add_header({n}, {v})");
    }

    let _ = writeln!(out, "        .await;");
    let _ = writeln!(out, "    assert_eq!(response.status_code().as_u16(), {status}u16);");
    let _ = writeln!(out, "}}");
}

// ---------------------------------------------------------------------------
// Mock server helpers
// ---------------------------------------------------------------------------

/// Emit mock server setup lines into a test function body.
///
/// Builds `MockRoute` objects from the fixture's `mock_response` and starts
/// the server.  The resulting `mock_server` variable is in scope for the rest
/// of the test function.
fn render_mock_server_setup(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig) {
    let mock = match fixture.mock_response.as_ref() {
        Some(m) => m,
        None => return,
    };

    // Resolve the HTTP path and method from the call config.
    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
    let path = call_config.path.as_deref().unwrap_or("/");
    let method = call_config.method.as_deref().unwrap_or("POST");

    let status = mock.status;

    // Render headers map as a Vec<(String, String)> literal for stable iteration order.
    let mut header_entries: Vec<(&String, &String)> = mock.headers.iter().collect();
    header_entries.sort_by(|a, b| a.0.cmp(b.0));
    let render_headers = |out: &mut String| {
        let _ = writeln!(out, "        headers: vec![");
        for (name, value) in &header_entries {
            let n = rust_raw_string(name);
            let v = rust_raw_string(value);
            let _ = writeln!(out, "            ({n}.to_string(), {v}.to_string()),");
        }
        let _ = writeln!(out, "        ],");
    };

    if let Some(chunks) = &mock.stream_chunks {
        // Streaming SSE response.
        let _ = writeln!(out, "    let mock_route = MockRoute {{");
        let _ = writeln!(out, "        path: \"{path}\",");
        let _ = writeln!(out, "        method: \"{method}\",");
        let _ = writeln!(out, "        status: {status},");
        let _ = writeln!(out, "        body: String::new(),");
        let _ = writeln!(out, "        stream_chunks: vec![");
        for chunk in chunks {
            let chunk_str = match chunk {
                serde_json::Value::String(s) => rust_raw_string(s),
                other => {
                    let s = serde_json::to_string(other).unwrap_or_default();
                    rust_raw_string(&s)
                }
            };
            let _ = writeln!(out, "            {chunk_str}.to_string(),");
        }
        let _ = writeln!(out, "        ],");
        render_headers(out);
        let _ = writeln!(out, "    }};");
    } else {
        // Non-streaming JSON response.
        let body_str = match &mock.body {
            Some(b) => {
                let s = serde_json::to_string(b).unwrap_or_default();
                rust_raw_string(&s)
            }
            None => rust_raw_string("{}"),
        };
        let _ = writeln!(out, "    let mock_route = MockRoute {{");
        let _ = writeln!(out, "        path: \"{path}\",");
        let _ = writeln!(out, "        method: \"{method}\",");
        let _ = writeln!(out, "        status: {status},");
        let _ = writeln!(out, "        body: {body_str}.to_string(),");
        let _ = writeln!(out, "        stream_chunks: vec![],");
        render_headers(out);
        let _ = writeln!(out, "    }};");
    }

    let _ = writeln!(out, "    let mock_server = MockServer::start(vec![mock_route]).await;");
}

/// Generate the complete `mock_server.rs` module source.
pub fn render_mock_server_module() -> String {
    // This is parameterized Axum mock server code identical in structure to
    // liter-llm's mock_server.rs but without any project-specific imports.
    hash::header(CommentStyle::DoubleSlash)
        + r#"//
// Minimal axum-based mock HTTP server for e2e tests.

use std::net::SocketAddr;
use std::sync::Arc;

use axum::Router;
use axum::body::Body;
use axum::extract::State;
use axum::http::{Request, StatusCode};
use axum::response::{IntoResponse, Response};
use tokio::net::TcpListener;

/// A single mock route: match by path + method, return a configured response.
#[derive(Clone, Debug)]
pub struct MockRoute {
    /// URL path to match, e.g. `"/v1/chat/completions"`.
    pub path: &'static str,
    /// HTTP method to match, e.g. `"POST"` or `"GET"`.
    pub method: &'static str,
    /// HTTP status code to return.
    pub status: u16,
    /// Response body JSON string (used when `stream_chunks` is empty).
    pub body: String,
    /// Ordered SSE data payloads for streaming responses.
    /// Each entry becomes `data: <chunk>\n\n` in the response.
    /// A final `data: [DONE]\n\n` is always appended.
    pub stream_chunks: Vec<String>,
    /// Response headers to apply (name, value) pairs.
    /// Multiple entries with the same name produce multiple header lines.
    pub headers: Vec<(String, String)>,
}

struct ServerState {
    routes: Vec<MockRoute>,
}

pub struct MockServer {
    /// Base URL of the mock server, e.g. `"http://127.0.0.1:54321"`.
    pub url: String,
    handle: tokio::task::JoinHandle<()>,
}

impl MockServer {
    /// Start a mock server with the given routes.  Binds to a random port on
    /// localhost and returns immediately once the server is listening.
    pub async fn start(routes: Vec<MockRoute>) -> Self {
        let state = Arc::new(ServerState { routes });

        let app = Router::new().fallback(handle_request).with_state(state);

        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("Failed to bind mock server port");
        let addr: SocketAddr = listener.local_addr().expect("Failed to get local addr");
        let url = format!("http://{addr}");

        let handle = tokio::spawn(async move {
            axum::serve(listener, app).await.expect("Mock server failed");
        });

        MockServer { url, handle }
    }

    /// Stop the mock server.
    pub fn shutdown(self) {
        self.handle.abort();
    }
}

impl Drop for MockServer {
    fn drop(&mut self) {
        self.handle.abort();
    }
}

async fn handle_request(State(state): State<Arc<ServerState>>, req: Request<Body>) -> Response {
    let path = req.uri().path().to_owned();
    let method = req.method().as_str().to_uppercase();

    for route in &state.routes {
        if route.path == path && route.method.to_uppercase() == method {
            let status =
                StatusCode::from_u16(route.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

            if !route.stream_chunks.is_empty() {
                // Build SSE body: data: <chunk>\n\n ... data: [DONE]\n\n
                let mut sse = String::new();
                for chunk in &route.stream_chunks {
                    sse.push_str("data: ");
                    sse.push_str(chunk);
                    sse.push_str("\n\n");
                }
                sse.push_str("data: [DONE]\n\n");

                let mut builder = Response::builder()
                    .status(status)
                    .header("content-type", "text/event-stream")
                    .header("cache-control", "no-cache");
                for (name, value) in &route.headers {
                    builder = builder.header(name, value);
                }
                return builder.body(Body::from(sse)).unwrap().into_response();
            }

            let mut builder =
                Response::builder().status(status).header("content-type", "application/json");
            for (name, value) in &route.headers {
                builder = builder.header(name, value);
            }
            return builder.body(Body::from(route.body.clone())).unwrap().into_response();
        }
    }

    // No matching route → 404.
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(Body::from(format!("No mock route for {method} {path}")))
        .unwrap()
        .into_response()
}
"#
}

/// Generate the `src/main.rs` for the standalone mock server binary.
///
/// The binary:
/// - Reads all `*.json` fixture files from a fixtures directory (default `../../fixtures`).
/// - For each fixture that has a `mock_response` field, registers a route at
///   `/fixtures/{fixture_id}` returning the configured status/body/SSE chunks.
/// - Binds to `127.0.0.1:0` (random port), prints `MOCK_SERVER_URL=http://...`
///   to stdout, then waits until stdin is closed for clean teardown.
///
/// This binary is intended for cross-language e2e suites (WASM, Node) that
/// spawn it as a child process and read the URL from its stdout.
pub fn render_mock_server_binary() -> String {
    hash::header(CommentStyle::DoubleSlash)
        + r#"//
// Standalone mock HTTP server binary for cross-language e2e tests.
// Reads fixture JSON files and serves mock responses on /fixtures/{fixture_id}.
//
// Usage: mock-server [fixtures-dir]
//   fixtures-dir defaults to "../../fixtures"
//
// Prints `MOCK_SERVER_URL=http://127.0.0.1:<port>` to stdout once listening,
// then blocks until stdin is closed (parent process exit triggers cleanup).

use std::collections::HashMap;
use std::io::{self, BufRead};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;

use axum::Router;
use axum::body::Body;
use axum::extract::State;
use axum::http::{Request, StatusCode};
use axum::response::{IntoResponse, Response};
use serde::Deserialize;
use tokio::net::TcpListener;

// ---------------------------------------------------------------------------
// Fixture types (mirrors alef-e2e's fixture.rs for runtime deserialization)
// Supports both schemas:
//   liter-llm: mock_response: { status, body, stream_chunks }
//   spikard:   http.expected_response: { status_code, body, headers }
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct MockResponse {
    status: u16,
    #[serde(default)]
    body: Option<serde_json::Value>,
    #[serde(default)]
    stream_chunks: Option<Vec<serde_json::Value>>,
    #[serde(default)]
    headers: HashMap<String, String>,
}

#[derive(Debug, Deserialize)]
struct HttpExpectedResponse {
    status_code: u16,
    #[serde(default)]
    body: Option<serde_json::Value>,
    #[serde(default)]
    headers: HashMap<String, String>,
}

#[derive(Debug, Deserialize)]
struct HttpFixture {
    expected_response: HttpExpectedResponse,
}

#[derive(Debug, Deserialize)]
struct Fixture {
    id: String,
    #[serde(default)]
    mock_response: Option<MockResponse>,
    #[serde(default)]
    http: Option<HttpFixture>,
}

impl Fixture {
    /// Bridge both schemas into a unified MockResponse.
    fn as_mock_response(&self) -> Option<MockResponse> {
        if let Some(mock) = &self.mock_response {
            return Some(MockResponse {
                status: mock.status,
                body: mock.body.clone(),
                stream_chunks: mock.stream_chunks.clone(),
                headers: mock.headers.clone(),
            });
        }
        if let Some(http) = &self.http {
            return Some(MockResponse {
                status: http.expected_response.status_code,
                body: http.expected_response.body.clone(),
                stream_chunks: None,
                headers: http.expected_response.headers.clone(),
            });
        }
        None
    }
}

// ---------------------------------------------------------------------------
// Route table
// ---------------------------------------------------------------------------

#[derive(Clone, Debug)]
struct MockRoute {
    status: u16,
    body: String,
    stream_chunks: Vec<String>,
    headers: Vec<(String, String)>,
}

type RouteTable = Arc<HashMap<String, MockRoute>>;

// ---------------------------------------------------------------------------
// Axum handler
// ---------------------------------------------------------------------------

async fn handle_request(State(routes): State<RouteTable>, req: Request<Body>) -> Response {
    let path = req.uri().path().to_owned();

    // Try exact match first
    if let Some(route) = routes.get(&path) {
        return serve_route(route);
    }

    // Try prefix match: find a route that is a prefix of the request path
    // This allows /fixtures/basic_chat/v1/chat/completions to match /fixtures/basic_chat
    for (route_path, route) in routes.iter() {
        if path.starts_with(route_path) && (path.len() == route_path.len() || path.as_bytes()[route_path.len()] == b'/') {
            return serve_route(route);
        }
    }

    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(Body::from(format!("No mock route for {path}")))
        .unwrap()
        .into_response()
}

fn serve_route(route: &MockRoute) -> Response {
    let status = StatusCode::from_u16(route.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

    if !route.stream_chunks.is_empty() {
        let mut sse = String::new();
        for chunk in &route.stream_chunks {
            sse.push_str("data: ");
            sse.push_str(chunk);
            sse.push_str("\n\n");
        }
        sse.push_str("data: [DONE]\n\n");

        let mut builder = Response::builder()
            .status(status)
            .header("content-type", "text/event-stream")
            .header("cache-control", "no-cache");
        for (name, value) in &route.headers {
            builder = builder.header(name, value);
        }
        return builder.body(Body::from(sse)).unwrap().into_response();
    }

    // Only set the default content-type if the fixture does not override it.
    // Use application/json when the body looks like JSON (starts with { or [),
    // otherwise fall back to text/plain to avoid clients failing JSON-decode.
    let has_content_type = route.headers.iter().any(|(k, _)| k.to_lowercase() == "content-type");
    let mut builder = Response::builder().status(status);
    if !has_content_type {
        let trimmed = route.body.trim_start();
        let default_ct = if trimmed.starts_with('{') || trimmed.starts_with('[') {
            "application/json"
        } else {
            "text/plain"
        };
        builder = builder.header("content-type", default_ct);
    }
    for (name, value) in &route.headers {
        // Skip content-encoding headers — the mock server returns uncompressed bodies.
        // Sending a content-encoding without actually encoding the body would cause
        // clients to fail decompression.
        if name.to_lowercase() == "content-encoding" {
            continue;
        }
        // The <<absent>> sentinel means this header must NOT be present in the
        // real server response — do not emit it from the mock server either.
        if value == "<<absent>>" {
            continue;
        }
        // Replace the <<uuid>> sentinel with a real UUID v4 so clients can
        // assert the header value matches the UUID pattern.
        if value == "<<uuid>>" {
            let uuid = format!(
                "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
                rand_u32(),
                rand_u16(),
                rand_u16() & 0x0fff,
                (rand_u16() & 0x3fff) | 0x8000,
                rand_u48(),
            );
            builder = builder.header(name, uuid);
            continue;
        }
        builder = builder.header(name, value);
    }
    builder.body(Body::from(route.body.clone())).unwrap().into_response()
}

/// Generate a pseudo-random u32 using the current time nanoseconds.
fn rand_u32() -> u32 {
    use std::time::{SystemTime, UNIX_EPOCH};
    let ns = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    ns ^ (ns.wrapping_shl(13)) ^ (ns.wrapping_shr(17))
}

fn rand_u16() -> u16 {
    (rand_u32() & 0xffff) as u16
}

fn rand_u48() -> u64 {
    ((rand_u32() as u64) << 16) | (rand_u16() as u64)
}

// ---------------------------------------------------------------------------
// Fixture loading
// ---------------------------------------------------------------------------

fn load_routes(fixtures_dir: &Path) -> HashMap<String, MockRoute> {
    let mut routes = HashMap::new();
    load_routes_recursive(fixtures_dir, &mut routes);
    routes
}

fn load_routes_recursive(dir: &Path, routes: &mut HashMap<String, MockRoute>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(err) => {
            eprintln!("warning: cannot read directory {}: {err}", dir.display());
            return;
        }
    };

    let mut paths: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
    paths.sort();

    for path in paths {
        if path.is_dir() {
            load_routes_recursive(&path, routes);
        } else if path.extension().is_some_and(|ext| ext == "json") {
            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if filename == "schema.json" || filename.starts_with('_') {
                continue;
            }
            let content = match std::fs::read_to_string(&path) {
                Ok(c) => c,
                Err(err) => {
                    eprintln!("warning: cannot read {}: {err}", path.display());
                    continue;
                }
            };
            let fixtures: Vec<Fixture> = if content.trim_start().starts_with('[') {
                match serde_json::from_str(&content) {
                    Ok(v) => v,
                    Err(err) => {
                        eprintln!("warning: cannot parse {}: {err}", path.display());
                        continue;
                    }
                }
            } else {
                match serde_json::from_str::<Fixture>(&content) {
                    Ok(f) => vec![f],
                    Err(err) => {
                        eprintln!("warning: cannot parse {}: {err}", path.display());
                        continue;
                    }
                }
            };

            for fixture in fixtures {
                if let Some(mock) = fixture.as_mock_response() {
                    let route_path = format!("/fixtures/{}", fixture.id);
                    let body = mock
                        .body
                        .as_ref()
                        .map(|b| match b {
                            // Plain strings (e.g. text/plain bodies) are stored as JSON strings in
                            // fixtures. Return the raw value so clients receive the string itself,
                            // not its JSON-encoded form with extra surrounding quotes.
                            serde_json::Value::String(s) => s.clone(),
                            other => serde_json::to_string(other).unwrap_or_default(),
                        })
                        .unwrap_or_default();
                    let stream_chunks = mock
                        .stream_chunks
                        .unwrap_or_default()
                        .into_iter()
                        .map(|c| match c {
                            serde_json::Value::String(s) => s,
                            other => serde_json::to_string(&other).unwrap_or_default(),
                        })
                        .collect();
                    let mut headers: Vec<(String, String)> =
                        mock.headers.into_iter().collect();
                    headers.sort_by(|a, b| a.0.cmp(&b.0));
                    routes.insert(route_path, MockRoute { status: mock.status, body, stream_chunks, headers });
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

#[tokio::main]
async fn main() {
    let fixtures_dir_arg = std::env::args().nth(1).unwrap_or_else(|| "../../fixtures".to_string());
    let fixtures_dir = Path::new(&fixtures_dir_arg);

    let routes = load_routes(fixtures_dir);
    eprintln!("mock-server: loaded {} routes from {}", routes.len(), fixtures_dir.display());

    let route_table: RouteTable = Arc::new(routes);
    let app = Router::new().fallback(handle_request).with_state(route_table);

    let listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("mock-server: failed to bind port");
    let addr: SocketAddr = listener.local_addr().expect("mock-server: failed to get local addr");

    // Print the URL so the parent process can read it.
    println!("MOCK_SERVER_URL=http://{addr}");
    // Flush stdout explicitly so the parent does not block waiting.
    use std::io::Write;
    std::io::stdout().flush().expect("mock-server: failed to flush stdout");

    // Spawn the server in the background.
    tokio::spawn(async move {
        axum::serve(listener, app).await.expect("mock-server: server error");
    });

    // Block until stdin is closed — the parent process controls lifetime.
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    while lines.next().is_some() {}
}
"#
}

// ---------------------------------------------------------------------------
// Assertion rendering
// ---------------------------------------------------------------------------

#[allow(clippy::too_many_arguments)]
fn render_assertion(
    out: &mut String,
    assertion: &Assertion,
    result_var: &str,
    module: &str,
    dep_name: &str,
    is_error_context: bool,
    unwrapped_fields: &[(String, String)], // (fixture_field, local_var)
    field_resolver: &FieldResolver,
    result_is_tree: bool,
    result_is_simple: bool,
    result_is_vec: bool,
    result_is_option: bool,
) {
    // Vec<T> result: iterate per-element so each assertion checks every element.
    // Field-path assertions become `for r in &{result} { <assert using r> }`.
    // Length-style assertions on the Vec itself (no field path) operate on the
    // Vec directly.
    let has_field = assertion.field.as_ref().is_some_and(|f| !f.is_empty());
    if result_is_vec && has_field && !is_error_context {
        let _ = writeln!(out, "    for r in &{result_var} {{");
        render_assertion(
            out,
            assertion,
            "r",
            module,
            dep_name,
            is_error_context,
            unwrapped_fields,
            field_resolver,
            result_is_tree,
            result_is_simple,
            false, // already inside loop
            result_is_option,
        );
        let _ = writeln!(out, "    }}");
        return;
    }
    // Option<T> result: map `is_empty`/`not_empty` to `is_none()`/`is_some()`,
    // and unwrap the inner value before any other assertion runs.
    if result_is_option && !is_error_context {
        let assertion_type = assertion.assertion_type.as_str();
        if !has_field && (assertion_type == "is_empty" || assertion_type == "not_empty") {
            let check = if assertion_type == "is_empty" {
                "is_none"
            } else {
                "is_some"
            };
            let _ = writeln!(
                out,
                "    assert!({result_var}.{check}(), \"expected Option to be {check}\");"
            );
            return;
        }
        // For any other assertion shape, unwrap the Option and recurse with a
        // bare reference variable so the rest of the renderer treats the inner
        // value as the result.
        let _ = writeln!(
            out,
            "    let r = {result_var}.as_ref().expect(\"Option<T> should be Some\");"
        );
        render_assertion(
            out,
            assertion,
            "r",
            module,
            dep_name,
            is_error_context,
            unwrapped_fields,
            field_resolver,
            result_is_tree,
            result_is_simple,
            result_is_vec,
            false, // already unwrapped
        );
        return;
    }
    let _ = dep_name;
    // Handle synthetic fields like chunks_have_content (derived assertions).
    // These are computed expressions, not real struct fields — intercept before
    // the is_valid_for_result check so they are never treated as field accesses.
    if let Some(f) = &assertion.field {
        match f.as_str() {
            "chunks_have_content" => {
                match assertion.assertion_type.as_str() {
                    "is_true" => {
                        let _ = writeln!(
                            out,
                            "    assert!({result_var}.chunks.as_ref().is_some_and(|chunks| !chunks.is_empty() && chunks.iter().all(|c| !c.content.is_empty())), \"expected all chunks to have content\");"
                        );
                    }
                    "is_false" => {
                        let _ = writeln!(
                            out,
                            "    assert!({result_var}.chunks.as_ref().is_none() || {result_var}.chunks.as_ref().unwrap().iter().any(|c| c.content.is_empty()), \"expected some chunks to be empty\");"
                        );
                    }
                    _ => {
                        let _ = writeln!(
                            out,
                            "    // unsupported assertion type on synthetic field chunks_have_content"
                        );
                    }
                }
                return;
            }
            "chunks_have_embeddings" => {
                match assertion.assertion_type.as_str() {
                    "is_true" => {
                        let _ = writeln!(
                            out,
                            "    assert!({result_var}.chunks.as_ref().is_some_and(|c| c.iter().all(|ch| ch.embedding.as_ref().is_some_and(|e| !e.is_empty()))), \"expected all chunks to have embeddings\");"
                        );
                    }
                    "is_false" => {
                        let _ = writeln!(
                            out,
                            "    assert!({result_var}.chunks.as_ref().is_none_or(|c| c.iter().any(|ch| ch.embedding.as_ref().is_none_or(|e| e.is_empty()))), \"expected some chunks to lack embeddings\");"
                        );
                    }
                    _ => {
                        let _ = writeln!(
                            out,
                            "    // unsupported assertion type on synthetic field chunks_have_embeddings"
                        );
                    }
                }
                return;
            }
            // ---- EmbedResponse virtual fields ----
            // embed_texts returns Vec<Vec<f32>> in Rust (no wrapper struct).
            // result_var is the embedding matrix — use it directly.
            "embeddings" => {
                // "embeddings" as a field in count_equals/count_min means the outer list.
                // embed_texts returns Vec<Vec<f32>> directly; result_var IS the embedding matrix.
                let embed_list = result_var.to_string();
                match assertion.assertion_type.as_str() {
                    "count_equals" => {
                        if let Some(val) = &assertion.value {
                            if let Some(n) = val.as_u64() {
                                let _ = writeln!(
                                    out,
                                    "    assert_eq!({embed_list}.len(), {n}, \"expected exactly {n} elements, got {{}}\", {embed_list}.len());"
                                );
                            }
                        }
                    }
                    "count_min" => {
                        if let Some(val) = &assertion.value {
                            if let Some(n) = val.as_u64() {
                                if n <= 1 {
                                    let _ =
                                        writeln!(out, "    assert!(!{embed_list}.is_empty(), \"expected >= {n}\");");
                                } else {
                                    let _ = writeln!(
                                        out,
                                        "    assert!({embed_list}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {embed_list}.len());"
                                    );
                                }
                            }
                        }
                    }
                    "not_empty" => {
                        let _ = writeln!(
                            out,
                            "    assert!(!{embed_list}.is_empty(), \"expected non-empty embeddings\");"
                        );
                    }
                    "is_empty" => {
                        let _ = writeln!(
                            out,
                            "    assert!({embed_list}.is_empty(), \"expected empty embeddings\");"
                        );
                    }
                    _ => {
                        let _ = writeln!(
                            out,
                            "    // skipped: unsupported assertion type on synthetic field 'embeddings'"
                        );
                    }
                }
                return;
            }
            "embedding_dimensions" => {
                let embed_list = result_var;
                let expr = format!("{embed_list}.first().map_or(0, |e| e.len())");
                match assertion.assertion_type.as_str() {
                    "equals" => {
                        if let Some(val) = &assertion.value {
                            let lit = numeric_literal(val);
                            let _ = writeln!(
                                out,
                                "    assert_eq!({expr}, {lit} as usize, \"equals assertion failed\");"
                            );
                        }
                    }
                    "greater_than" => {
                        if let Some(val) = &assertion.value {
                            let lit = numeric_literal(val);
                            let _ = writeln!(out, "    assert!({expr} > {lit} as usize, \"expected > {lit}\");");
                        }
                    }
                    _ => {
                        let _ = writeln!(
                            out,
                            "    // skipped: unsupported assertion type on synthetic field 'embedding_dimensions'"
                        );
                    }
                }
                return;
            }
            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
                let embed_list = result_var;
                let pred = match f.as_str() {
                    "embeddings_valid" => {
                        format!("{embed_list}.iter().all(|e| !e.is_empty())")
                    }
                    "embeddings_finite" => {
                        format!("{embed_list}.iter().all(|e| e.iter().all(|v| v.is_finite()))")
                    }
                    "embeddings_non_zero" => {
                        format!("{embed_list}.iter().all(|e| e.iter().any(|v| *v != 0.0_f32))")
                    }
                    "embeddings_normalized" => {
                        format!(
                            "{embed_list}.iter().all(|e| {{ let n: f64 = e.iter().map(|v| f64::from(*v) * f64::from(*v)).sum(); (n - 1.0_f64).abs() < 1e-3 }})"
                        )
                    }
                    _ => unreachable!(),
                };
                match assertion.assertion_type.as_str() {
                    "is_true" => {
                        let _ = writeln!(out, "    assert!({pred}, \"expected true\");");
                    }
                    "is_false" => {
                        let _ = writeln!(out, "    assert!(!({pred}), \"expected false\");");
                    }
                    _ => {
                        let _ = writeln!(
                            out,
                            "    // skipped: unsupported assertion type on synthetic field '{f}'"
                        );
                    }
                }
                return;
            }
            // ---- keywords / keywords_count ----
            // ExtractionResult has `extracted_keywords: Option<Vec<Keyword>>`.
            // Translate fixture virtual fields to that real accessor.
            "keywords" => {
                let accessor = format!("{result_var}.extracted_keywords");
                match assertion.assertion_type.as_str() {
                    "not_empty" => {
                        let _ = writeln!(
                            out,
                            "    assert!({accessor}.as_ref().is_some_and(|v| !v.is_empty()), \"expected keywords to be present and non-empty\");"
                        );
                    }
                    "is_empty" => {
                        let _ = writeln!(
                            out,
                            "    assert!({accessor}.as_ref().is_none_or(|v| v.is_empty()), \"expected keywords to be empty or absent\");"
                        );
                    }
                    "count_min" => {
                        if let Some(val) = &assertion.value {
                            if let Some(n) = val.as_u64() {
                                if n <= 1 {
                                    let _ = writeln!(
                                        out,
                                        "    assert!({accessor}.as_ref().is_some_and(|v| !v.is_empty()), \"expected >= {n}\");"
                                    );
                                } else {
                                    let _ = writeln!(
                                        out,
                                        "    assert!({accessor}.as_ref().is_some_and(|v| v.len() >= {n}), \"expected at least {n} keywords\");"
                                    );
                                }
                            }
                        }
                    }
                    "count_equals" => {
                        if let Some(val) = &assertion.value {
                            if let Some(n) = val.as_u64() {
                                let _ = writeln!(
                                    out,
                                    "    assert!({accessor}.as_ref().is_some_and(|v| v.len() == {n}), \"expected exactly {n} keywords\");"
                                );
                            }
                        }
                    }
                    _ => {
                        let _ = writeln!(
                            out,
                            "    // skipped: unsupported assertion type on synthetic field 'keywords'"
                        );
                    }
                }
                return;
            }
            "keywords_count" => {
                let expr = format!("{result_var}.extracted_keywords.as_ref().map_or(0, |v| v.len())");
                match assertion.assertion_type.as_str() {
                    "equals" => {
                        if let Some(val) = &assertion.value {
                            let lit = numeric_literal(val);
                            let _ = writeln!(
                                out,
                                "    assert_eq!({expr}, {lit} as usize, \"equals assertion failed\");"
                            );
                        }
                    }
                    "less_than_or_equal" => {
                        if let Some(val) = &assertion.value {
                            let lit = numeric_literal(val);
                            let _ = writeln!(out, "    assert!({expr} <= {lit} as usize, \"expected <= {lit}\");");
                        }
                    }
                    "greater_than_or_equal" => {
                        if let Some(val) = &assertion.value {
                            let lit = numeric_literal(val);
                            let _ = writeln!(out, "    assert!({expr} >= {lit} as usize, \"expected >= {lit}\");");
                        }
                    }
                    "greater_than" => {
                        if let Some(val) = &assertion.value {
                            let lit = numeric_literal(val);
                            let _ = writeln!(out, "    assert!({expr} > {lit} as usize, \"expected > {lit}\");");
                        }
                    }
                    "less_than" => {
                        if let Some(val) = &assertion.value {
                            let lit = numeric_literal(val);
                            let _ = writeln!(out, "    assert!({expr} < {lit} as usize, \"expected < {lit}\");");
                        }
                    }
                    _ => {
                        let _ = writeln!(
                            out,
                            "    // skipped: unsupported assertion type on synthetic field 'keywords_count'"
                        );
                    }
                }
                return;
            }
            _ => {}
        }
    }

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

    // Determine field access expression:
    // 1. If the field was unwrapped to a local var, use that local var name.
    // 2. When result_is_simple, the function returns a plain type (String etc.) — use result_var.
    // 3. When the field path is exactly the result var name (sentinel: `field: "result"`),
    //    refer to the result variable directly to avoid emitting `result.result`.
    // 4. When the result is a Tree, map pseudo-field names to correct Rust expressions.
    // 5. Otherwise, use the field resolver to generate the accessor.
    let field_access = match &assertion.field {
        Some(f) if !f.is_empty() => {
            if let Some((_, local_var)) = unwrapped_fields.iter().find(|(ff, _)| ff == f) {
                local_var.clone()
            } else if result_is_simple {
                // Plain return type (String, Vec<T>, etc.) has no struct fields.
                // Use the result variable directly so assertions operate on the value itself.
                result_var.to_string()
            } else if f == result_var {
                // Sentinel: fixture uses `field: "result"` (or matches the result variable name)
                // to refer to the whole return value, not a struct field named "result".
                result_var.to_string()
            } else if result_is_tree {
                // Tree is an opaque type — its "fields" are accessed via root_node() or
                // free functions. Map known pseudo-field names to correct Rust expressions.
                tree_field_access_expr(f, result_var, module)
            } else {
                field_resolver.accessor(f, "rust", result_var)
            }
        }
        _ => result_var.to_string(),
    };

    // Check if this field was unwrapped (i.e., it is optional and was bound to a local).
    let is_unwrapped = assertion
        .field
        .as_ref()
        .is_some_and(|f| unwrapped_fields.iter().any(|(ff, _)| ff == f));

    match assertion.assertion_type.as_str() {
        "error" => {
            let _ = writeln!(out, "    assert!({result_var}.is_err(), \"expected call to fail\");");
            if let Some(serde_json::Value::String(msg)) = &assertion.value {
                let escaped = escape_rust(msg);
                let _ = writeln!(
                    out,
                    "    assert!({result_var}.as_ref().unwrap_err().to_string().contains(\"{escaped}\"), \"error message mismatch\");"
                );
            }
        }
        "not_error" => {
            // Handled at call site; nothing extra needed here.
        }
        "equals" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_rust_string(val);
                if is_error_context {
                    return;
                }
                // For string equality, trim trailing whitespace to handle trailing newlines
                // from the converter.
                if val.is_string() {
                    // When the field is Optional<String> and was NOT pre-unwrapped to a local
                    // var (e.g. inside a result_is_vec iteration where the call-site unwrap
                    // pass is skipped), emit `.as_deref().unwrap_or("").trim()` so the
                    // expression is `&str` rather than `Option<String>`.
                    let is_opt_str_not_unwrapped = assertion.field.as_ref().is_some_and(|f| {
                        let resolved = field_resolver.resolve(f);
                        let is_opt = field_resolver.is_optional(resolved);
                        let is_arr = field_resolver.is_array(resolved);
                        is_opt && !is_arr && !is_unwrapped
                    });
                    let field_expr = if is_opt_str_not_unwrapped {
                        format!("{field_access}.as_deref().unwrap_or(\"\").trim()")
                    } else {
                        format!("{field_access}.trim()")
                    };
                    let _ = writeln!(
                        out,
                        "    assert_eq!({field_expr}, {expected}, \"equals assertion failed\");"
                    );
                } else if val.is_boolean() {
                    // Use assert!/assert!(!...) for booleans — clippy prefers this over assert_eq!(_, true/false).
                    if val.as_bool() == Some(true) {
                        let _ = writeln!(out, "    assert!({field_access}, \"equals assertion failed\");");
                    } else {
                        let _ = writeln!(out, "    assert!(!{field_access}, \"equals assertion failed\");");
                    }
                } else {
                    // Wrap expected value in Some() for optional fields.
                    let is_opt = assertion.field.as_ref().is_some_and(|f| {
                        let resolved = field_resolver.resolve(f);
                        field_resolver.is_optional(resolved)
                    });
                    if is_opt
                        && !unwrapped_fields
                            .iter()
                            .any(|(ff, _)| assertion.field.as_ref() == Some(ff))
                    {
                        let _ = writeln!(
                            out,
                            "    assert_eq!({field_access}, Some({expected}), \"equals assertion failed\");"
                        );
                    } else {
                        let _ = writeln!(
                            out,
                            "    assert_eq!({field_access}, {expected}, \"equals assertion failed\");"
                        );
                    }
                }
            }
        }
        "contains" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_rust_string(val);
                let line = format!(
                    "    assert!(format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected to contain: {{}}\", {expected});"
                );
                let _ = writeln!(out, "{line}");
            }
        }
        "contains_all" => {
            if let Some(values) = &assertion.values {
                for val in values {
                    let expected = value_to_rust_string(val);
                    let line = format!(
                        "    assert!(format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected to contain: {{}}\", {expected});"
                    );
                    let _ = writeln!(out, "{line}");
                }
            }
        }
        "not_contains" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_rust_string(val);
                let line = format!(
                    "    assert!(!format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected NOT to contain: {{}}\", {expected});"
                );
                let _ = writeln!(out, "{line}");
            }
        }
        "not_empty" => {
            if let Some(f) = &assertion.field {
                let resolved = field_resolver.resolve(f);
                let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
                let is_arr = field_resolver.is_array(resolved);
                if is_opt && is_arr {
                    // Option<Vec<T>>: must be Some AND inner non-empty.
                    let accessor = field_resolver.accessor(f, "rust", result_var);
                    let _ = writeln!(
                        out,
                        "    assert!({accessor}.as_ref().is_some_and(|v| !v.is_empty()), \"expected {f} to be present and non-empty\");"
                    );
                } else if is_opt {
                    // Non-collection optional field (e.g., Option<Struct>): use is_some().
                    let accessor = field_resolver.accessor(f, "rust", result_var);
                    let _ = writeln!(
                        out,
                        "    assert!({accessor}.is_some(), \"expected {f} to be present\");"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "    assert!(!{field_access}.is_empty(), \"expected non-empty value\");"
                    );
                }
            } else if result_is_option {
                // Bare result is Option<T>: not_empty == is_some().
                let _ = writeln!(
                    out,
                    "    assert!({field_access}.is_some(), \"expected non-empty value\");"
                );
            } else {
                // Bare result is a struct/string/collection — non-empty via is_empty().
                let _ = writeln!(
                    out,
                    "    assert!(!{field_access}.is_empty(), \"expected non-empty value\");"
                );
            }
        }
        "is_empty" => {
            if let Some(f) = &assertion.field {
                let resolved = field_resolver.resolve(f);
                let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
                let is_arr = field_resolver.is_array(resolved);
                if is_opt && is_arr {
                    // Option<Vec<T>>: empty means None or empty vec.
                    let accessor = field_resolver.accessor(f, "rust", result_var);
                    let _ = writeln!(
                        out,
                        "    assert!({accessor}.as_ref().is_none_or(|v| v.is_empty()), \"expected {f} to be empty or absent\");"
                    );
                } else if is_opt {
                    let accessor = field_resolver.accessor(f, "rust", result_var);
                    let _ = writeln!(out, "    assert!({accessor}.is_none(), \"expected {f} to be absent\");");
                } else {
                    let _ = writeln!(out, "    assert!({field_access}.is_empty(), \"expected empty value\");");
                }
            } else {
                let _ = writeln!(out, "    assert!({field_access}.is_none(), \"expected empty value\");");
            }
        }
        "contains_any" => {
            if let Some(values) = &assertion.values {
                let checks: Vec<String> = values
                    .iter()
                    .map(|v| {
                        let expected = value_to_rust_string(v);
                        format!("{field_access}.contains({expected})")
                    })
                    .collect();
                let joined = checks.join(" || ");
                let _ = writeln!(
                    out,
                    "    assert!({joined}, \"expected to contain at least one of the specified values\");"
                );
            }
        }
        "greater_than" => {
            if let Some(val) = &assertion.value {
                // Skip comparisons with negative values against unsigned types (.len() etc.)
                if val.as_f64().is_some_and(|n| n < 0.0) {
                    let _ = writeln!(
                        out,
                        "    // skipped: greater_than with negative value is always true for unsigned types"
                    );
                } else if val.as_u64() == Some(0) {
                    // Clippy prefers !is_empty() over len() > 0
                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
                    let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected > 0\");");
                } else {
                    let lit = numeric_literal(val);
                    let _ = writeln!(out, "    assert!({field_access} > {lit}, \"expected > {lit}\");");
                }
            }
        }
        "less_than" => {
            if let Some(val) = &assertion.value {
                let lit = numeric_literal(val);
                let _ = writeln!(out, "    assert!({field_access} < {lit}, \"expected < {lit}\");");
            }
        }
        "greater_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let lit = numeric_literal(val);
                // Check whether this field is optional but not an array — e.g. Option<usize>.
                // Directly comparing Option<usize> >= N is a type error; wrap with unwrap_or(0).
                let is_opt_numeric = assertion.field.as_ref().is_some_and(|f| {
                    let resolved = field_resolver.resolve(f);
                    let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
                    let is_arr = field_resolver.is_array(resolved);
                    is_opt && !is_arr
                });
                if val.as_u64() == Some(1) && field_access.ends_with(".len()") {
                    // Clippy prefers !is_empty() over len() >= 1 for collections.
                    // Only apply when the expression is already a `.len()` call so we
                    // don't mistakenly call `.is_empty()` on numeric (usize) fields.
                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
                    let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected >= 1\");");
                } else if is_opt_numeric {
                    // Option<usize> / Option<u64>: unwrap to 0 before comparing.
                    let _ = writeln!(
                        out,
                        "    assert!({field_access}.unwrap_or(0) >= {lit}, \"expected >= {lit}\");"
                    );
                } else {
                    let _ = writeln!(out, "    assert!({field_access} >= {lit}, \"expected >= {lit}\");");
                }
            }
        }
        "less_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let lit = numeric_literal(val);
                let _ = writeln!(out, "    assert!({field_access} <= {lit}, \"expected <= {lit}\");");
            }
        }
        "starts_with" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_rust_string(val);
                let _ = writeln!(
                    out,
                    "    assert!({field_access}.starts_with({expected}), \"expected to start with: {{}}\", {expected});"
                );
            }
        }
        "ends_with" => {
            if let Some(val) = &assertion.value {
                let expected = value_to_rust_string(val);
                let _ = writeln!(
                    out,
                    "    assert!({field_access}.ends_with({expected}), \"expected to end with: {{}}\", {expected});"
                );
            }
        }
        "min_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(
                        out,
                        "    assert!({field_access}.len() >= {n}, \"expected length >= {n}, got {{}}\", {field_access}.len());"
                    );
                }
            }
        }
        "max_length" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let _ = writeln!(
                        out,
                        "    assert!({field_access}.len() <= {n}, \"expected length <= {n}, got {{}}\", {field_access}.len());"
                    );
                }
            }
        }
        "count_min" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let opt_arr_field = assertion.field.as_ref().is_some_and(|f| {
                        let resolved = field_resolver.resolve(f);
                        let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
                        let is_arr = field_resolver.is_array(resolved);
                        is_opt && is_arr
                    });
                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
                    if opt_arr_field {
                        // Option<Vec<T>>: must be Some AND inner len >= n.
                        if n <= 1 {
                            let _ = writeln!(
                                out,
                                "    assert!({base}.as_ref().is_some_and(|v| !v.is_empty()), \"expected >= {n}\");"
                            );
                        } else {
                            let _ = writeln!(
                                out,
                                "    assert!({base}.as_ref().is_some_and(|v| v.len() >= {n}), \"expected at least {n} elements\");"
                            );
                        }
                    } else if n <= 1 {
                        let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected >= {n}\");");
                    } else {
                        let _ = writeln!(
                            out,
                            "    assert!({field_access}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {field_access}.len());"
                        );
                    }
                }
            }
        }
        "count_equals" => {
            if let Some(val) = &assertion.value {
                if let Some(n) = val.as_u64() {
                    let opt_arr_field = assertion.field.as_ref().is_some_and(|f| {
                        let resolved = field_resolver.resolve(f);
                        let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
                        let is_arr = field_resolver.is_array(resolved);
                        is_opt && is_arr
                    });
                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
                    if opt_arr_field {
                        let _ = writeln!(
                            out,
                            "    assert!({base}.as_ref().is_some_and(|v| v.len() == {n}), \"expected exactly {n} elements\");"
                        );
                    } else {
                        let _ = writeln!(
                            out,
                            "    assert_eq!({field_access}.len(), {n}, \"expected exactly {n} elements, got {{}}\", {field_access}.len());"
                        );
                    }
                }
            }
        }
        "is_true" => {
            let _ = writeln!(out, "    assert!({field_access}, \"expected true\");");
        }
        "is_false" => {
            let _ = writeln!(out, "    assert!(!{field_access}, \"expected false\");");
        }
        "method_result" => {
            if let Some(method_name) = &assertion.method {
                // Build the call expression. When the result is a tree-sitter Tree (an opaque
                // type), methods like `root_child_count` do not exist on `Tree` directly —
                // they are free functions in the crate or are accessed via `root_node()`.
                let call_expr = if result_is_tree {
                    build_tree_call_expr(field_access.as_str(), method_name, assertion.args.as_ref(), module)
                } else if let Some(args) = &assertion.args {
                    let arg_lit = json_to_rust_literal(args, "");
                    format!("{field_access}.{method_name}({arg_lit})")
                } else {
                    format!("{field_access}.{method_name}()")
                };

                // Determine whether the call expression returns a numeric type so we can
                // choose the right comparison strategy for `greater_than_or_equal`.
                let returns_numeric = result_is_tree && is_tree_numeric_method(method_name);

                let check = assertion.check.as_deref().unwrap_or("is_true");
                match check {
                    "equals" => {
                        if let Some(val) = &assertion.value {
                            if val.is_boolean() {
                                if val.as_bool() == Some(true) {
                                    let _ = writeln!(
                                        out,
                                        "    assert!({call_expr}, \"method_result equals assertion failed\");"
                                    );
                                } else {
                                    let _ = writeln!(
                                        out,
                                        "    assert!(!{call_expr}, \"method_result equals assertion failed\");"
                                    );
                                }
                            } else {
                                let expected = value_to_rust_string(val);
                                let _ = writeln!(
                                    out,
                                    "    assert_eq!({call_expr}, {expected}, \"method_result equals assertion failed\");"
                                );
                            }
                        }
                    }
                    "is_true" => {
                        let _ = writeln!(
                            out,
                            "    assert!({call_expr}, \"method_result is_true assertion failed\");"
                        );
                    }
                    "is_false" => {
                        let _ = writeln!(
                            out,
                            "    assert!(!{call_expr}, \"method_result is_false assertion failed\");"
                        );
                    }
                    "greater_than_or_equal" => {
                        if let Some(val) = &assertion.value {
                            let lit = numeric_literal(val);
                            if returns_numeric {
                                // Numeric return (e.g., child_count()) — always use >= comparison.
                                let _ = writeln!(out, "    assert!({call_expr} >= {lit}, \"expected >= {lit}\");");
                            } else if val.as_u64() == Some(1) {
                                // Clippy prefers !is_empty() over len() >= 1 for collections.
                                let _ = writeln!(out, "    assert!(!{call_expr}.is_empty(), \"expected >= 1\");");
                            } else {
                                let _ = writeln!(out, "    assert!({call_expr} >= {lit}, \"expected >= {lit}\");");
                            }
                        }
                    }
                    "count_min" => {
                        if let Some(val) = &assertion.value {
                            let n = val.as_u64().unwrap_or(0);
                            if n <= 1 {
                                let _ = writeln!(out, "    assert!(!{call_expr}.is_empty(), \"expected >= {n}\");");
                            } else {
                                let _ = writeln!(
                                    out,
                                    "    assert!({call_expr}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {call_expr}.len());"
                                );
                            }
                        }
                    }
                    "is_error" => {
                        // For is_error we need the raw Result without .unwrap().
                        let raw_call = call_expr.strip_suffix(".unwrap()").unwrap_or(&call_expr);
                        let _ = writeln!(
                            out,
                            "    assert!({raw_call}.is_err(), \"expected method to return error\");"
                        );
                    }
                    "contains" => {
                        if let Some(val) = &assertion.value {
                            let expected = value_to_rust_string(val);
                            let _ = writeln!(
                                out,
                                "    assert!({call_expr}.contains({expected}), \"expected result to contain {{}}\", {expected});"
                            );
                        }
                    }
                    "not_empty" => {
                        let _ = writeln!(
                            out,
                            "    assert!(!{call_expr}.is_empty(), \"expected non-empty result\");"
                        );
                    }
                    "is_empty" => {
                        let _ = writeln!(out, "    assert!({call_expr}.is_empty(), \"expected empty result\");");
                    }
                    other_check => {
                        panic!("Rust e2e generator: unsupported method_result check type: {other_check}");
                    }
                }
            } else {
                panic!("Rust e2e generator: method_result assertion missing 'method' field");
            }
        }
        other => {
            panic!("Rust e2e generator: unsupported assertion type: {other}");
        }
    }
}

/// Translate a fixture pseudo-field name on a `tree_sitter::Tree` into the
/// correct Rust accessor expression.
///
/// When an assertion uses `field: "root_child_count"` on a tree result, the
/// field resolver would naively emit `tree.root_child_count` — which is invalid
/// because `Tree` is an opaque type with no such field.  This function maps the
/// pseudo-field to the correct Rust expression instead.
fn tree_field_access_expr(field: &str, result_var: &str, module: &str) -> String {
    match field {
        "root_child_count" => format!("{result_var}.root_node().child_count()"),
        "root_node_type" => format!("{result_var}.root_node().kind()"),
        "named_children_count" => format!("{result_var}.root_node().named_child_count()"),
        "has_error_nodes" => format!("{module}::tree_has_error_nodes(&{result_var})"),
        "error_count" | "tree_error_count" => format!("{module}::tree_error_count(&{result_var})"),
        "tree_to_sexp" => format!("{module}::tree_to_sexp(&{result_var})"),
        // Unknown pseudo-field: fall back to direct field access (will likely fail to compile,
        // but gives the developer a useful error pointing to the fixture).
        other => format!("{result_var}.{other}"),
    }
}

/// Build a Rust call expression for a logical "method" on a `tree_sitter::Tree`.
///
/// `Tree` is an opaque type — it does not expose methods like `root_child_count`.
/// Instead, these are either free functions in the crate or are accessed via
/// `tree.root_node().<method>()`. This function translates the fixture-level
/// method name into the correct Rust expression.
fn build_tree_call_expr(
    field_access: &str,
    method_name: &str,
    args: Option<&serde_json::Value>,
    module: &str,
) -> String {
    match method_name {
        "root_child_count" => format!("{field_access}.root_node().child_count()"),
        "root_node_type" => format!("{field_access}.root_node().kind()"),
        "named_children_count" => format!("{field_access}.root_node().named_child_count()"),
        "has_error_nodes" => format!("{module}::tree_has_error_nodes(&{field_access})"),
        "error_count" | "tree_error_count" => format!("{module}::tree_error_count(&{field_access})"),
        "tree_to_sexp" => format!("{module}::tree_to_sexp(&{field_access})"),
        "contains_node_type" => {
            let node_type = args
                .and_then(|a| a.get("node_type"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            format!("{module}::tree_contains_node_type(&{field_access}, \"{node_type}\")")
        }
        "find_nodes_by_type" => {
            let node_type = args
                .and_then(|a| a.get("node_type"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            format!("{module}::find_nodes_by_type(&{field_access}, \"{node_type}\")")
        }
        "run_query" => {
            let query_source = args
                .and_then(|a| a.get("query_source"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let language = args
                .and_then(|a| a.get("language"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            // Use a raw string for the query to avoid escaping issues.
            // run_query returns Result — unwrap it for assertion access.
            format!(
                "{module}::run_query(&{field_access}, \"{language}\", r#\"{query_source}\"#, source.as_bytes()).unwrap()"
            )
        }
        // Fallback: try as a plain method call.
        _ => {
            if let Some(args) = args {
                let arg_lit = json_to_rust_literal(args, "");
                format!("{field_access}.{method_name}({arg_lit})")
            } else {
                format!("{field_access}.{method_name}()")
            }
        }
    }
}

/// Returns `true` when the tree method name produces a numeric result (usize/u64),
/// meaning `>= N` comparisons should use direct numeric comparison rather than
/// `.is_empty()` (which only works for collections).
fn is_tree_numeric_method(method_name: &str) -> bool {
    matches!(
        method_name,
        "root_child_count" | "named_children_count" | "error_count" | "tree_error_count"
    )
}

/// Convert a JSON numeric value to a Rust literal suitable for comparisons.
///
/// Whole numbers (no fractional part) are emitted as bare integer literals so
/// they are compatible with `usize`, `u64`, etc. (e.g., `.len()` results).
/// Numbers with a fractional component get the `_f64` suffix.
fn numeric_literal(value: &serde_json::Value) -> String {
    if let Some(n) = value.as_f64() {
        if n.fract() == 0.0 {
            // Whole number — emit without a type suffix so Rust can infer the
            // correct integer type from context (usize, u64, i64, …).
            return format!("{}", n as i64);
        }
        return format!("{n}_f64");
    }
    // Fallback: use the raw JSON representation.
    value.to_string()
}

fn value_to_rust_string(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => rust_raw_string(s),
        serde_json::Value::Bool(b) => format!("{b}"),
        serde_json::Value::Number(n) => n.to_string(),
        other => {
            let s = other.to_string();
            format!("\"{s}\"")
        }
    }
}

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

/// Resolve the visitor trait name based on module.
fn resolve_visitor_trait(module: &str) -> String {
    // For html_to_markdown modules, use HtmlVisitor
    if module.contains("html_to_markdown") {
        "HtmlVisitor".to_string()
    } else {
        // Default fallback for other modules
        "Visitor".to_string()
    }
}

/// Emit a Rust visitor method for a callback action.
///
/// The parameter type list mirrors the `HtmlVisitor` trait in
/// `kreuzberg-dev/html-to-markdown`. Param names are bound to `_` because the
/// generated visitor body never references them — the body always returns a
/// fixed `VisitResult` variant — so we'd otherwise hit `unused_variables`
/// warnings that fail prek's `cargo clippy -D warnings` hook.
fn emit_rust_visitor_method(out: &mut String, method_name: &str, action: &CallbackAction) {
    // Each entry: parameters typed exactly as `HtmlVisitor` expects them,
    // bound to `_` patterns so the generated body needn't introduce unused
    // bindings. Receiver is `&mut self` to match the trait.
    let params = match method_name {
        "visit_link" => "_: &NodeContext, _: &str, _: &str, _: &str",
        "visit_image" => "_: &NodeContext, _: &str, _: &str, _: &str",
        "visit_heading" => "_: &NodeContext, _: u8, _: &str, _: Option<&str>",
        "visit_code_block" => "_: &NodeContext, _: Option<&str>, _: &str",
        "visit_code_inline"
        | "visit_strong"
        | "visit_emphasis"
        | "visit_strikethrough"
        | "visit_underline"
        | "visit_subscript"
        | "visit_superscript"
        | "visit_mark"
        | "visit_button"
        | "visit_summary"
        | "visit_figcaption"
        | "visit_definition_term"
        | "visit_definition_description" => "_: &NodeContext, _: &str",
        "visit_text" => "_: &NodeContext, _: &str",
        "visit_list_item" => "_: &NodeContext, _: bool, _: &str, _: &str",
        "visit_blockquote" => "_: &NodeContext, _: &str, _: u32",
        "visit_table_row" => "_: &NodeContext, _: &[String], _: bool",
        "visit_custom_element" => "_: &NodeContext, _: &str, _: &str",
        "visit_form" => "_: &NodeContext, _: &str, _: &str",
        "visit_input" => "_: &NodeContext, _: &str, _: &str, _: &str",
        "visit_audio" | "visit_video" | "visit_iframe" => "_: &NodeContext, _: &str",
        "visit_details" => "_: &NodeContext, _: bool",
        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
            "_: &NodeContext, _: &str"
        }
        "visit_list_start" => "_: &NodeContext, _: bool",
        "visit_list_end" => "_: &NodeContext, _: bool, _: &str",
        _ => "_: &NodeContext",
    };

    let _ = writeln!(out, "        fn {method_name}(&mut self, {params}) -> VisitResult {{");
    match action {
        CallbackAction::Skip => {
            let _ = writeln!(out, "            VisitResult::Skip");
        }
        CallbackAction::Continue => {
            let _ = writeln!(out, "            VisitResult::Continue");
        }
        CallbackAction::PreserveHtml => {
            let _ = writeln!(out, "            VisitResult::PreserveHtml");
        }
        CallbackAction::Custom { output } => {
            let escaped = escape_rust(output);
            let _ = writeln!(out, "            VisitResult::Custom(\"{escaped}\".to_string())");
        }
        CallbackAction::CustomTemplate { template } => {
            let escaped = escape_rust(template);
            let _ = writeln!(out, "            VisitResult::Custom(format!(\"{escaped}\"))");
        }
    }
    let _ = writeln!(out, "        }}");
}