openapi-to-rust 0.2.1

Generate strongly-typed Rust structs, HTTP clients, and SSE streaming clients from OpenAPI 3.1 specifications
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
use crate::{GeneratorError, Result, analysis::SchemaAnalysis, streaming::StreamingConfig};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::BTreeMap;
use std::path::PathBuf;

/// Info about schemas that are variants in discriminated unions
#[derive(Clone)]
struct DiscriminatedVariantInfo {
    /// The discriminator field name (e.g., "type")
    discriminator_field: String,
    /// The const value of the discriminator (e.g., "text")
    discriminator_value: String,
    /// Whether the parent union is untagged
    is_parent_untagged: bool,
}

#[derive(Debug, Clone)]
pub struct GeneratorConfig {
    /// Path to OpenAPI specification file
    pub spec_path: PathBuf,
    /// Output directory for generated code (e.g., "src/gen")
    pub output_dir: PathBuf,
    /// Name of the generated module
    pub module_name: String,
    /// Enable SSE streaming client generation
    pub enable_sse_client: bool,
    /// Enable async HTTP client generation
    pub enable_async_client: bool,
    /// Enable Specta type derives for frontend integration
    pub enable_specta: bool,
    /// Custom type mappings
    pub type_mappings: BTreeMap<String, String>,
    /// Optional streaming configuration for SSE client generation
    pub streaming_config: Option<StreamingConfig>,
    /// Fields that should be treated as nullable even if not marked in the spec
    /// Format: "SchemaName.fieldName" -> true
    pub nullable_field_overrides: BTreeMap<String, bool>,
    /// Additional schema extension files to merge into the main spec
    /// These files will be merged additively using simple JSON object merging
    pub schema_extensions: Vec<PathBuf>,
    /// HTTP client configuration
    pub http_client_config: Option<crate::http_config::HttpClientConfig>,
    /// Retry configuration for HTTP requests
    pub retry_config: Option<crate::http_config::RetryConfig>,
    /// Enable request/response tracing
    pub tracing_enabled: bool,
    /// Authentication configuration
    pub auth_config: Option<crate::http_config::AuthConfig>,
    /// Enable operation registry generation (static metadata for CLI/proxy routing)
    pub enable_registry: bool,
    /// Generate only the operation registry (skip types, client, streaming)
    pub registry_only: bool,
}

impl Default for GeneratorConfig {
    fn default() -> Self {
        Self {
            spec_path: "openapi.json".into(),
            output_dir: "src/gen".into(),
            module_name: "api_types".to_string(),
            enable_sse_client: true,
            enable_async_client: true,
            enable_specta: false,
            type_mappings: default_type_mappings(),
            streaming_config: None,
            nullable_field_overrides: BTreeMap::new(),
            schema_extensions: Vec::new(),
            http_client_config: None,
            retry_config: None,
            tracing_enabled: true,
            auth_config: None,
            enable_registry: false,
            registry_only: false,
        }
    }
}

pub fn default_type_mappings() -> BTreeMap<String, String> {
    let mut mappings = BTreeMap::new();
    mappings.insert("integer".to_string(), "i64".to_string());
    mappings.insert("number".to_string(), "f64".to_string());
    mappings.insert("string".to_string(), "String".to_string());
    mappings.insert("boolean".to_string(), "bool".to_string());
    mappings
}

/// Represents a generated file
#[derive(Debug, Clone)]
pub struct GeneratedFile {
    /// Relative path from output directory (e.g., "types.rs", "streaming.rs")
    pub path: PathBuf,
    /// Generated Rust code content
    pub content: String,
}

/// Result of code generation containing multiple files
#[derive(Debug, Clone)]
pub struct GenerationResult {
    /// All generated files
    pub files: Vec<GeneratedFile>,
    /// Generated mod.rs content that exports all modules
    pub mod_file: GeneratedFile,
}

pub struct CodeGenerator {
    config: GeneratorConfig,
}

impl CodeGenerator {
    pub fn new(config: GeneratorConfig) -> Self {
        Self { config }
    }

    /// Get reference to the generator configuration
    pub fn config(&self) -> &GeneratorConfig {
        &self.config
    }

    /// Generate all files for the API
    pub fn generate_all(&self, analysis: &mut SchemaAnalysis) -> Result<GenerationResult> {
        let mut files = Vec::new();

        if !self.config.registry_only {
            // Generate types file
            let types_content = self.generate_types(analysis)?;
            files.push(GeneratedFile {
                path: "types.rs".into(),
                content: types_content,
            });

            // Generate streaming client if configured
            if let Some(ref streaming_config) = self.config.streaming_config {
                let streaming_content =
                    self.generate_streaming_client(streaming_config, analysis)?;
                files.push(GeneratedFile {
                    path: "streaming.rs".into(),
                    content: streaming_content,
                });
            }

            // Generate HTTP client if enabled
            if self.config.enable_async_client {
                let http_content = self.generate_http_client(analysis)?;
                files.push(GeneratedFile {
                    path: "client.rs".into(),
                    content: http_content,
                });
            }
        }

        // Generate operation registry if enabled
        if self.config.enable_registry || self.config.registry_only {
            let registry_content = self.generate_registry(analysis)?;
            files.push(GeneratedFile {
                path: "registry.rs".into(),
                content: registry_content,
            });
        }

        // Generate mod.rs file
        let mod_content = self.generate_mod_file(&files)?;
        let mod_file = GeneratedFile {
            path: "mod.rs".into(),
            content: mod_content,
        };

        Ok(GenerationResult { files, mod_file })
    }

    /// Generate just the types (legacy single-file interface)
    pub fn generate(&self, analysis: &mut SchemaAnalysis) -> Result<String> {
        self.generate_types(analysis)
    }

    /// Generate the types.rs file content
    fn generate_types(&self, analysis: &mut SchemaAnalysis) -> Result<String> {
        let mut type_definitions = TokenStream::new();

        // Collect all schemas that are used as variants in discriminated unions
        // Only include direct references, not schemas wrapped in allOf
        let mut discriminated_variant_info: BTreeMap<String, DiscriminatedVariantInfo> =
            BTreeMap::new();

        // Sort schemas for deterministic processing
        let mut sorted_schemas: Vec<_> = analysis.schemas.iter().collect();
        sorted_schemas.sort_by_key(|(name, _)| name.as_str());

        for (_parent_name, schema) in sorted_schemas {
            if let crate::analysis::SchemaType::DiscriminatedUnion {
                variants,
                discriminator_field,
            } = &schema.schema_type
            {
                // Check if this discriminated union will be generated as untagged
                let is_parent_untagged =
                    self.should_use_untagged_discriminated_union(schema, analysis);

                for variant in variants {
                    // Only add if it's a direct reference to a schema that will have the discriminator field
                    // Check if the schema exists and has the discriminator field as a property
                    if let Some(variant_schema) = analysis.schemas.get(&variant.type_name) {
                        if let crate::analysis::SchemaType::Object { properties, .. } =
                            &variant_schema.schema_type
                        {
                            if properties.contains_key(discriminator_field) {
                                discriminated_variant_info.insert(
                                    variant.type_name.clone(),
                                    DiscriminatedVariantInfo {
                                        discriminator_field: discriminator_field.clone(),
                                        discriminator_value: variant.discriminator_value.clone(),
                                        is_parent_untagged,
                                    },
                                );
                            }
                        }
                    }
                }
            }
        }

        // Generate types based on dependency order
        let generation_order = analysis.dependencies.topological_sort()?;

        // Generate all schemas, including those not in dependency graph
        let mut processed = std::collections::HashSet::new();

        // First, generate schemas in dependency order
        for schema_name in generation_order {
            if let Some(schema) = analysis.schemas.get(&schema_name) {
                let type_def =
                    self.generate_type_definition(schema, analysis, &discriminated_variant_info)?;
                if !type_def.is_empty() {
                    type_definitions.extend(type_def);
                }
                processed.insert(schema_name);
            }
        }

        // Then generate any remaining schemas not in dependency graph
        // Sort by name for deterministic output
        let mut remaining_schemas: Vec<_> = analysis
            .schemas
            .iter()
            .filter(|(name, _)| !processed.contains(*name))
            .collect();
        remaining_schemas.sort_by_key(|(name, _)| name.as_str());

        for (_schema_name, schema) in remaining_schemas {
            let type_def =
                self.generate_type_definition(schema, analysis, &discriminated_variant_info)?;
            if !type_def.is_empty() {
                type_definitions.extend(type_def);
            }
        }

        // Generate file with imports and types (no module wrapper)
        let generated = quote! {
            //! Generated types from OpenAPI specification
            //!
            //! This file contains all the generated types for the API.
            //! Do not edit manually - regenerate using the appropriate script.

            #![allow(clippy::large_enum_variant)]
            #![allow(clippy::format_in_format_args)]
            #![allow(clippy::let_unit_value)]
            #![allow(unreachable_patterns)]

            use serde::{Deserialize, Serialize};

            #type_definitions
        };

        // Format the generated code
        let syntax_tree = syn::parse2::<syn::File>(generated).map_err(|e| {
            GeneratorError::CodeGenError(format!("Failed to parse generated code: {e}"))
        })?;

        let formatted = prettyplease::unparse(&syntax_tree);

        Ok(formatted)
    }

    /// Generate streaming client code
    fn generate_streaming_client(
        &self,
        streaming_config: &StreamingConfig,
        analysis: &SchemaAnalysis,
    ) -> Result<String> {
        let mut client_code = TokenStream::new();

        // Generate imports
        let imports = quote! {
            //! Generated streaming client for SSE (Server-Sent Events)
            //!
            //! This file contains the streaming client implementation.
            //! Do not edit manually - regenerate using the appropriate script.
            #![allow(clippy::format_in_format_args)]
            #![allow(clippy::let_unit_value)]
            #![allow(unused_mut)]

            use super::types::*;
            use async_trait::async_trait;
            use futures_util::{Stream, StreamExt};
            use std::pin::Pin;
            use std::time::Duration;
            use reqwest::header::{HeaderMap, HeaderValue};
            use tracing::{debug, error, info, warn, instrument};
        };
        client_code.extend(imports);

        // Generate error types
        if streaming_config.generate_client {
            let error_types = self.generate_streaming_error_types()?;
            client_code.extend(error_types);
        }

        // Generate client trait for each endpoint
        for endpoint in &streaming_config.endpoints {
            let trait_code = self.generate_endpoint_trait(endpoint, analysis)?;
            client_code.extend(trait_code);
        }

        // Generate client implementation
        if streaming_config.generate_client {
            let client_impl = self.generate_streaming_client_impl(streaming_config, analysis)?;
            client_code.extend(client_impl);
        }

        // Generate SSE parsing utilities
        if streaming_config.event_parser_helpers {
            let parser_code = self.generate_sse_parser_utilities(streaming_config)?;
            client_code.extend(parser_code);
        }

        // Generate reconnection utilities if configured
        if let Some(reconnect_config) = &streaming_config.reconnection_config {
            let reconnect_code = self.generate_reconnection_utilities(reconnect_config)?;
            client_code.extend(reconnect_code);
        }

        let syntax_tree = syn::parse2::<syn::File>(client_code).map_err(|e| {
            GeneratorError::CodeGenError(format!("Failed to parse streaming client code: {e}"))
        })?;

        Ok(prettyplease::unparse(&syntax_tree))
    }

    /// Generate HTTP client code for regular (non-streaming) requests
    pub fn generate_http_client(&self, analysis: &SchemaAnalysis) -> Result<String> {
        let error_types = self.generate_http_error_types();
        let client_struct = self.generate_http_client_struct();
        let operation_methods = self.generate_operation_methods(analysis);

        let generated = quote! {
            //! Generated HTTP client for regular API requests
            //!
            //! This file contains the HTTP client implementation for GET, POST, etc.
            //! Do not edit manually - regenerate using the appropriate script.
            #![allow(clippy::format_in_format_args)]
            #![allow(clippy::let_unit_value)]

            use super::types::*;

            #error_types

            #client_struct

            #operation_methods
        };

        let syntax_tree = syn::parse2::<syn::File>(generated).map_err(|e| {
            GeneratorError::CodeGenError(format!("Failed to parse HTTP client code: {e}"))
        })?;

        Ok(prettyplease::unparse(&syntax_tree))
    }

    /// Generate HTTP error type and result alias
    fn generate_http_error_types(&self) -> TokenStream {
        quote! {
            use thiserror::Error;

            /// Transport-level errors: failures where we never received an
            /// inspectable HTTP response from the server.
            ///
            /// HTTP responses with non-2xx status codes are surfaced as
            /// [`ApiError`] inside [`ApiOpError::Api`], not here, so callers can
            /// always inspect status, headers, and the raw body when the server
            /// actually responded.
            #[derive(Error, Debug)]
            pub enum HttpError {
                /// Network or connection error (from reqwest)
                #[error("Network error: {0}")]
                Network(#[from] reqwest::Error),

                /// Middleware error (from reqwest-middleware)
                #[error("Middleware error: {0}")]
                Middleware(#[from] reqwest_middleware::Error),

                /// Request serialization error
                #[error("Failed to serialize request: {0}")]
                Serialization(String),

                /// Authentication error
                #[error("Authentication error: {0}")]
                Auth(String),

                /// Request timeout
                #[error("Request timeout")]
                Timeout,

                /// Invalid configuration
                #[error("Configuration error: {0}")]
                Config(String),

                /// Generic error
                #[error("{0}")]
                Other(String),
            }

            impl HttpError {
                /// Create a serialization error
                pub fn serialization_error(error: impl std::fmt::Display) -> Self {
                    Self::Serialization(error.to_string())
                }

                /// Check if this transport error is retryable
                pub fn is_retryable(&self) -> bool {
                    matches!(self, Self::Network(_) | Self::Middleware(_) | Self::Timeout)
                }
            }

            /// Envelope returned for any HTTP response that we received but
            /// couldn't (or didn't) treat as a successful typed result.
            ///
            /// Includes both non-2xx responses and 2xx responses whose body
            /// failed to deserialize into the expected success type. `status`,
            /// `headers`, and `body` are always populated so callers can
            /// inspect what the server sent without modifying the generated
            /// code. `typed` carries the parsed per-operation error variant
            /// when the body matched a declared schema.
            #[derive(Debug, Clone)]
            pub struct ApiError<E> {
                pub status: u16,
                pub headers: reqwest::header::HeaderMap,
                pub body: String,
                pub typed: Option<E>,
                pub parse_error: Option<String>,
            }

            impl<E> ApiError<E> {
                pub fn is_client_error(&self) -> bool {
                    (400..500).contains(&self.status)
                }

                pub fn is_server_error(&self) -> bool {
                    (500..600).contains(&self.status)
                }

                /// Retry guidance for the response. Mirrors the previous
                /// HttpError logic for backwards-compatible retry middleware.
                pub fn is_retryable(&self) -> bool {
                    matches!(self.status, 429 | 500 | 502 | 503 | 504)
                }
            }

            impl<E: std::fmt::Debug> std::fmt::Display for ApiError<E> {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    write!(f, "API error {}: {}", self.status, self.body)
                }
            }

            impl<E: std::fmt::Debug> std::error::Error for ApiError<E> {}

            /// Result error type returned by every generated operation method.
            ///
            /// `Transport` covers failures where we never got an inspectable
            /// response (network, timeout, middleware, request-side
            /// serialization). `Api` covers any case where the server *did*
            /// respond — the envelope always carries status + headers + raw
            /// body even when the typed deserialize fails.
            #[derive(Debug, Error)]
            pub enum ApiOpError<E: std::fmt::Debug> {
                #[error(transparent)]
                Transport(#[from] HttpError),

                #[error(transparent)]
                Api(ApiError<E>),
            }

            impl<E: std::fmt::Debug> ApiOpError<E> {
                /// Returns the API envelope when this is an `Api` variant.
                pub fn api(&self) -> Option<&ApiError<E>> {
                    match self {
                        Self::Api(e) => Some(e),
                        Self::Transport(_) => None,
                    }
                }

                /// True when the underlying error came from the server (i.e.
                /// any `Api` variant) rather than the transport layer.
                pub fn is_api_error(&self) -> bool {
                    matches!(self, Self::Api(_))
                }
            }

            // Direct From impls so `?` works without going through HttpError
            // first. Rust's `?` only chains a single `From` conversion.
            impl<E: std::fmt::Debug> From<reqwest::Error> for ApiOpError<E> {
                fn from(e: reqwest::Error) -> Self {
                    Self::Transport(HttpError::Network(e))
                }
            }

            impl<E: std::fmt::Debug> From<reqwest_middleware::Error> for ApiOpError<E> {
                fn from(e: reqwest_middleware::Error) -> Self {
                    Self::Transport(HttpError::Middleware(e))
                }
            }

            /// Result alias for transport-only error paths (e.g. helpers that
            /// don't have a per-operation error type). Generated operation
            /// methods use [`ApiOpError`] directly.
            pub type HttpResult<T> = Result<T, HttpError>;
        }
    }

    /// Generate mod.rs file that exports all modules
    fn generate_mod_file(&self, files: &[GeneratedFile]) -> Result<String> {
        let mut module_declarations = Vec::new();
        let mut pub_uses = Vec::new();

        for file in files {
            if let Some(module_name) = file.path.file_stem().and_then(|s| s.to_str()) {
                if module_name != "mod" {
                    module_declarations.push(format!("pub mod {module_name};"));
                    pub_uses.push(format!("pub use {module_name}::*;"));
                }
            }
        }

        let content = format!(
            r#"//! Generated API modules
//!
//! This module exports all generated API types and clients.
//! Do not edit manually - regenerate using the appropriate script.

#![allow(unused_imports)]

{}

{}
"#,
            module_declarations.join("\n"),
            pub_uses.join("\n")
        );

        Ok(content)
    }

    /// Helper method to write all generated files to disk
    pub fn write_files(&self, result: &GenerationResult) -> Result<()> {
        use std::fs;

        // Create output directory if it doesn't exist
        fs::create_dir_all(&self.config.output_dir)?;

        // Write all files
        for file in &result.files {
            let file_path = self.config.output_dir.join(&file.path);
            fs::write(&file_path, &file.content)?;
        }

        // Write mod.rs
        let mod_path = self.config.output_dir.join(&result.mod_file.path);
        fs::write(&mod_path, &result.mod_file.content)?;

        Ok(())
    }

    fn generate_type_definition(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        analysis: &crate::analysis::SchemaAnalysis,
        discriminated_variant_info: &BTreeMap<String, DiscriminatedVariantInfo>,
    ) -> Result<TokenStream> {
        use crate::analysis::SchemaType;

        match &schema.schema_type {
            SchemaType::Primitive { rust_type } => {
                // Generate type alias for primitives that are referenced by other schemas
                self.generate_type_alias(schema, rust_type)
            }
            SchemaType::StringEnum { values } => self.generate_string_enum(schema, values),
            SchemaType::ExtensibleEnum { known_values } => {
                self.generate_extensible_enum(schema, known_values)
            }
            SchemaType::Object {
                properties,
                required,
                additional_properties,
            } => self.generate_struct(
                schema,
                properties,
                required,
                *additional_properties,
                analysis,
                discriminated_variant_info.get(&schema.name),
            ),
            SchemaType::DiscriminatedUnion {
                discriminator_field,
                variants,
            } => {
                // Check if this discriminated union should be untagged due to being nested
                if self.should_use_untagged_discriminated_union(schema, analysis) {
                    // Convert variants to SchemaRef format for union enum generation
                    let schema_refs: Vec<crate::analysis::SchemaRef> = variants
                        .iter()
                        .map(|v| crate::analysis::SchemaRef {
                            target: v.type_name.clone(),
                            nullable: false,
                        })
                        .collect();
                    self.generate_union_enum(schema, &schema_refs)
                } else {
                    self.generate_discriminated_enum(
                        schema,
                        discriminator_field,
                        variants,
                        analysis,
                    )
                }
            }
            SchemaType::Union { variants } => self.generate_union_enum(schema, variants),
            SchemaType::Reference { target } => {
                // For references, check if we need to generate a type alias
                // This handles cases like nullable patterns
                if schema.name != *target {
                    // Generate a type alias
                    let alias_name = format_ident!("{}", self.to_rust_type_name(&schema.name));
                    let target_type = format_ident!("{}", self.to_rust_type_name(target));

                    let doc_comment = if let Some(desc) = &schema.description {
                        quote! { #[doc = #desc] }
                    } else {
                        TokenStream::new()
                    };

                    Ok(quote! {
                        #doc_comment
                        pub type #alias_name = #target_type;
                    })
                } else {
                    // Same name as target, no need for alias
                    Ok(TokenStream::new())
                }
            }
            SchemaType::Array { item_type } => {
                // Generate type alias for named array schemas.
                //
                // Special case: if the array item is a struct whose discriminator
                // field was stripped (because it's used in a tagged enum), the bare
                // struct won't serialize the discriminator in standalone contexts.
                // Generate a single-variant tagged wrapper enum so the discriminator
                // field is re-added by serde's tag attribute.
                let array_name = format_ident!("{}", self.to_rust_type_name(&schema.name));

                // Check if the item type is a Reference to a discriminator-stripped struct
                if let SchemaType::Reference { target } = item_type.as_ref() {
                    if let Some(info) = discriminated_variant_info.get(target) {
                        if !info.is_parent_untagged {
                            // Generate a wrapper enum that re-adds the discriminator tag
                            let wrapper_name =
                                format_ident!("{}Item", self.to_rust_type_name(&schema.name));
                            let variant_type = format_ident!("{}", self.to_rust_type_name(target));
                            let disc_field = &info.discriminator_field;
                            let disc_value = &info.discriminator_value;

                            let doc_comment = if let Some(desc) = &schema.description {
                                quote! { #[doc = #desc] }
                            } else {
                                TokenStream::new()
                            };

                            return Ok(quote! {
                                /// Wrapper enum that re-adds the discriminator tag
                                /// for array contexts where the inner struct had its
                                /// discriminator field stripped for tagged enum use.
                                #[derive(Debug, Clone, Deserialize, Serialize)]
                                #[serde(tag = #disc_field)]
                                pub enum #wrapper_name {
                                    #[serde(rename = #disc_value)]
                                    #variant_type(#variant_type),
                                }
                                #doc_comment
                                pub type #array_name = Vec<#wrapper_name>;
                            });
                        }
                    }
                }

                let inner_type = self.generate_array_item_type(item_type, analysis);

                let doc_comment = if let Some(desc) = &schema.description {
                    quote! { #[doc = #desc] }
                } else {
                    TokenStream::new()
                };

                Ok(quote! {
                    #doc_comment
                    pub type #array_name = Vec<#inner_type>;
                })
            }
            SchemaType::Composition { schemas } => {
                self.generate_composition_struct(schema, schemas)
            }
        }
    }

    fn generate_type_alias(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        rust_type: &str,
    ) -> Result<TokenStream> {
        let type_name = format_ident!("{}", self.to_rust_type_name(&schema.name));

        // Parse the rust type into tokens
        let base_type = if rust_type.contains("::") {
            let parts: Vec<&str> = rust_type.split("::").collect();
            if parts.len() == 2 {
                let module = format_ident!("{}", parts[0]);
                let type_name_part = format_ident!("{}", parts[1]);
                quote! { #module::#type_name_part }
            } else {
                // More complex path
                let path_parts: Vec<_> = parts.iter().map(|p| format_ident!("{}", p)).collect();
                quote! { #(#path_parts)::* }
            }
        } else {
            let simple_type = format_ident!("{}", rust_type);
            quote! { #simple_type }
        };

        let doc_comment = if let Some(desc) = &schema.description {
            let sanitized_desc = self.sanitize_doc_comment(desc);
            quote! { #[doc = #sanitized_desc] }
        } else {
            TokenStream::new()
        };

        Ok(quote! {
            #doc_comment
            pub type #type_name = #base_type;
        })
    }

    fn generate_extensible_enum(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        known_values: &[String],
    ) -> Result<TokenStream> {
        let enum_name = format_ident!("{}", self.to_rust_type_name(&schema.name));

        let doc_comment = if let Some(desc) = &schema.description {
            quote! { #[doc = #desc] }
        } else {
            TokenStream::new()
        };

        // For extensible enums, we need a different approach:
        // 1. Create a regular enum with known variants + Custom
        // 2. Implement custom serialization/deserialization

        let known_variants = known_values.iter().map(|value| {
            let variant_name = self.to_rust_enum_variant(value);
            let variant_ident = format_ident!("{}", variant_name);
            quote! {
                #variant_ident,
            }
        });

        let match_arms_de = known_values.iter().map(|value| {
            let variant_name = self.to_rust_enum_variant(value);
            let variant_ident = format_ident!("{}", variant_name);
            quote! {
                #value => Ok(#enum_name::#variant_ident),
            }
        });

        let match_arms_ser = known_values.iter().map(|value| {
            let variant_name = self.to_rust_enum_variant(value);
            let variant_ident = format_ident!("{}", variant_name);
            quote! {
                #enum_name::#variant_ident => #value,
            }
        });

        let derives = if self.config.enable_specta {
            quote! {
                #[derive(Debug, Clone, PartialEq, Eq)]
                #[cfg_attr(feature = "specta", derive(specta::Type))]
            }
        } else {
            quote! {
                #[derive(Debug, Clone, PartialEq, Eq)]
            }
        };

        Ok(quote! {
            #doc_comment
            #derives
            pub enum #enum_name {
                #(#known_variants)*
                /// Custom or unknown model identifier
                Custom(String),
            }

            impl<'de> serde::Deserialize<'de> for #enum_name {
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                    D: serde::Deserializer<'de>,
                {
                    let value = String::deserialize(deserializer)?;
                    match value.as_str() {
                        #(#match_arms_de)*
                        _ => Ok(#enum_name::Custom(value)),
                    }
                }
            }

            impl serde::Serialize for #enum_name {
                fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                where
                    S: serde::Serializer,
                {
                    let value = match self {
                        #(#match_arms_ser)*
                        #enum_name::Custom(s) => s.as_str(),
                    };
                    serializer.serialize_str(value)
                }
            }
        })
    }

    fn generate_string_enum(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        values: &[String],
    ) -> Result<TokenStream> {
        let enum_name = format_ident!("{}", self.to_rust_type_name(&schema.name));

        // Determine which variant should be the default
        let default_value = schema
            .default
            .as_ref()
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let variants = values.iter().enumerate().map(|(i, value)| {
            // Convert string value to valid Rust enum variant (PascalCase)
            let variant_name = self.to_rust_enum_variant(value);
            let variant_ident = format_ident!("{}", variant_name);

            // Check if this variant should be the default
            let is_default = if let Some(ref default) = default_value {
                value == default
            } else {
                i == 0 // Fall back to first variant if no default specified
            };

            if is_default {
                quote! {
                    #[default]
                    #[serde(rename = #value)]
                    #variant_ident,
                }
            } else {
                quote! {
                    #[serde(rename = #value)]
                    #variant_ident,
                }
            }
        });

        let doc_comment = if let Some(desc) = &schema.description {
            quote! { #[doc = #desc] }
        } else {
            TokenStream::new()
        };

        // Generate derives with optional Specta support
        let derives = if self.config.enable_specta {
            quote! {
                #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Default)]
                #[cfg_attr(feature = "specta", derive(specta::Type))]
            }
        } else {
            quote! {
                #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Default)]
            }
        };

        Ok(quote! {
            #doc_comment
            #derives
            pub enum #enum_name {
                #(#variants)*
            }
        })
    }

    fn generate_struct(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        properties: &BTreeMap<String, crate::analysis::PropertyInfo>,
        required: &std::collections::HashSet<String>,
        additional_properties: bool,
        analysis: &crate::analysis::SchemaAnalysis,
        discriminator_info: Option<&DiscriminatedVariantInfo>,
    ) -> Result<TokenStream> {
        let struct_name = format_ident!("{}", self.to_rust_type_name(&schema.name));

        // Sort properties by name for deterministic output
        let mut sorted_properties: Vec<_> = properties.iter().collect();
        sorted_properties.sort_by_key(|(name, _)| name.as_str());

        let mut fields: Vec<TokenStream> = sorted_properties
            .into_iter()
            .filter(|(field_name, _)| {
                // Skip the discriminator field ONLY if:
                // 1. This struct is a variant in a discriminated union, AND
                // 2. The parent union is tagged (not untagged)
                if let Some(info) = discriminator_info {
                    if !info.is_parent_untagged
                        && field_name.as_str() == info.discriminator_field.as_str()
                    {
                        false // Skip the field
                    } else {
                        true // Keep the field
                    }
                } else {
                    true // No discriminator info, keep all fields
                }
            })
            .map(|(field_name, prop)| {
                let field_ident = Self::to_field_ident(&self.to_rust_field_name(field_name));
                let is_required = required.contains(field_name);
                let field_type =
                    self.generate_field_type(&schema.name, field_name, prop, is_required, analysis);

                let serde_attrs =
                    self.generate_serde_field_attrs(field_name, prop, is_required, analysis);
                let specta_attrs = self.generate_specta_field_attrs(field_name);

                let doc_comment = if let Some(desc) = &prop.description {
                    let sanitized_desc = self.sanitize_doc_comment(desc);
                    quote! { #[doc = #sanitized_desc] }
                } else {
                    TokenStream::new()
                };

                quote! {
                    #doc_comment
                    #serde_attrs
                    #specta_attrs
                    pub #field_ident: #field_type,
                }
            })
            .collect();

        // Add additional properties field if enabled
        if additional_properties {
            fields.push(quote! {
                /// Additional properties not explicitly defined in the schema
                #[serde(flatten)]
                pub additional_properties: std::collections::BTreeMap<String, serde_json::Value>,
            });
        }

        let doc_comment = if let Some(desc) = &schema.description {
            quote! { #[doc = #desc] }
        } else {
            TokenStream::new()
        };

        // Generate derives with optional Specta support
        // Note: We use snake_case everywhere (matching the OpenAPI spec) for consistency
        // between Rust, JSON API, and TypeScript
        let derives = if self.config.enable_specta {
            quote! {
                #[derive(Debug, Clone, Deserialize, Serialize)]
                #[cfg_attr(feature = "specta", derive(specta::Type))]
            }
        } else {
            quote! {
                #[derive(Debug, Clone, Deserialize, Serialize)]
            }
        };

        Ok(quote! {
            #doc_comment
            #derives
            pub struct #struct_name {
                #(#fields)*
            }
        })
    }

    fn generate_discriminated_enum(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        discriminator_field: &str,
        variants: &[crate::analysis::UnionVariant],
        analysis: &crate::analysis::SchemaAnalysis,
    ) -> Result<TokenStream> {
        let enum_name = format_ident!("{}", self.to_rust_type_name(&schema.name));

        // Check if any variant references another discriminated union
        let has_nested_discriminated_union = variants.iter().any(|variant| {
            if let Some(variant_schema) = analysis.schemas.get(&variant.type_name) {
                matches!(
                    variant_schema.schema_type,
                    crate::analysis::SchemaType::DiscriminatedUnion { .. }
                )
            } else {
                false
            }
        });

        // If we have a nested discriminated union, make this enum untagged
        if has_nested_discriminated_union {
            // Generate as untagged union
            let schema_refs: Vec<crate::analysis::SchemaRef> = variants
                .iter()
                .map(|v| crate::analysis::SchemaRef {
                    target: v.type_name.clone(),
                    nullable: false,
                })
                .collect();
            return self.generate_union_enum(schema, &schema_refs);
        }

        let enum_variants = variants.iter().map(|variant| {
            let variant_name = format_ident!("{}", variant.rust_name);
            let variant_value = &variant.discriminator_value;

            // Always use tuple variant that references the existing type
            // This ensures the standalone event types are actually used
            let variant_type = format_ident!("{}", self.to_rust_type_name(&variant.type_name));
            quote! {
                #[serde(rename = #variant_value)]
                #variant_name(#variant_type),
            }
        });

        let doc_comment = if let Some(desc) = &schema.description {
            quote! { #[doc = #desc] }
        } else {
            TokenStream::new()
        };

        // Generate derives with optional Specta support
        let derives = if self.config.enable_specta {
            quote! {
                #[derive(Debug, Clone, Deserialize, Serialize)]
                #[cfg_attr(feature = "specta", derive(specta::Type))]
                #[serde(tag = #discriminator_field)]
            }
        } else {
            quote! {
                #[derive(Debug, Clone, Deserialize, Serialize)]
                #[serde(tag = #discriminator_field)]
            }
        };

        Ok(quote! {
            #doc_comment
            #derives
            pub enum #enum_name {
                #(#enum_variants)*
            }
        })
    }

    /// Check if a discriminated union should be generated as untagged due to being nested
    fn should_use_untagged_discriminated_union(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        analysis: &crate::analysis::SchemaAnalysis,
    ) -> bool {
        // Only make discriminated unions untagged if they are nested AND their variants
        // don't need the discriminator field for API compatibility

        // Check if this schema is used as a variant in another discriminated union
        for other_schema in analysis.schemas.values() {
            if let crate::analysis::SchemaType::DiscriminatedUnion {
                variants,
                discriminator_field: _,
            } = &other_schema.schema_type
            {
                for variant in variants {
                    if variant.type_name == schema.name {
                        // This discriminated union is nested inside another discriminated union

                        // Check if the current schema's variants have the discriminator field in their properties
                        // If they do, we need to keep this union tagged to preserve the discriminator
                        if let crate::analysis::SchemaType::DiscriminatedUnion {
                            discriminator_field: current_discriminator,
                            variants: current_variants,
                            ..
                        } = &schema.schema_type
                        {
                            // Check if any variant schemas have the discriminator field as a property
                            for current_variant in current_variants {
                                if let Some(variant_schema) =
                                    analysis.schemas.get(&current_variant.type_name)
                                {
                                    if let crate::analysis::SchemaType::Object {
                                        properties, ..
                                    } = &variant_schema.schema_type
                                    {
                                        if properties.contains_key(current_discriminator) {
                                            // This variant has the discriminator field as a property,
                                            // so we need to keep the union tagged to preserve it
                                            return false;
                                        }
                                    }
                                }
                            }
                        }

                        // No variants have the discriminator as a property, safe to make untagged
                        return true;
                    }
                }
            }
        }
        false
    }

    fn generate_union_enum(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        variants: &[crate::analysis::SchemaRef],
    ) -> Result<TokenStream> {
        let enum_name = format_ident!("{}", self.to_rust_type_name(&schema.name));

        // Generate meaningful variant names based on type names
        let mut used_variant_names = std::collections::HashSet::new();
        let enum_variants = variants.iter().enumerate().map(|(i, variant)| {
            // Generate a meaningful variant name from the type name
            let base_variant_name = self.type_name_to_variant_name(&variant.target);
            let variant_name = self.ensure_unique_variant_name_generator(
                base_variant_name,
                &mut used_variant_names,
                i,
            );
            let variant_name_ident = format_ident!("{}", variant_name);

            // For primitive types and Vec types, use them directly without conversion
            let variant_type_tokens = if matches!(
                variant.target.as_str(),
                "bool"
                    | "i8"
                    | "i16"
                    | "i32"
                    | "i64"
                    | "i128"
                    | "u8"
                    | "u16"
                    | "u32"
                    | "u64"
                    | "u128"
                    | "f32"
                    | "f64"
                    | "String"
            ) {
                let type_ident = format_ident!("{}", variant.target);
                quote! { #type_ident }
            } else if variant.target == "serde_json::Value" {
                // The target is a fully-qualified path; emit it as a path so
                // it doesn't get mangled into a phantom `SerdeJsonValue` ident.
                quote! { serde_json::Value }
            } else if variant.target.starts_with("Vec<") && variant.target.ends_with(">") {
                // Handle Vec types by parsing the inner type
                let inner = &variant.target[4..variant.target.len() - 1];

                // Handle nested Vec types (e.g., Vec<Vec<i64>>)
                if inner.starts_with("Vec<") && inner.ends_with(">") {
                    let inner_inner = &inner[4..inner.len() - 1];
                    if inner_inner == "serde_json::Value" {
                        quote! { Vec<Vec<serde_json::Value>> }
                    } else {
                        let inner_inner_type = if matches!(
                            inner_inner,
                            "bool"
                                | "i8"
                                | "i16"
                                | "i32"
                                | "i64"
                                | "i128"
                                | "u8"
                                | "u16"
                                | "u32"
                                | "u64"
                                | "u128"
                                | "f32"
                                | "f64"
                                | "String"
                        ) {
                            format_ident!("{}", inner_inner)
                        } else {
                            format_ident!("{}", self.to_rust_type_name(inner_inner))
                        };
                        quote! { Vec<Vec<#inner_inner_type>> }
                    }
                } else if inner == "serde_json::Value" {
                    quote! { Vec<serde_json::Value> }
                } else {
                    let inner_type = if matches!(
                        inner,
                        "bool"
                            | "i8"
                            | "i16"
                            | "i32"
                            | "i64"
                            | "i128"
                            | "u8"
                            | "u16"
                            | "u32"
                            | "u64"
                            | "u128"
                            | "f32"
                            | "f64"
                            | "String"
                    ) {
                        format_ident!("{}", inner)
                    } else {
                        format_ident!("{}", self.to_rust_type_name(inner))
                    };
                    quote! { Vec<#inner_type> }
                }
            } else {
                let type_ident = format_ident!("{}", self.to_rust_type_name(&variant.target));
                quote! { #type_ident }
            };

            quote! {
                #variant_name_ident(#variant_type_tokens),
            }
        });

        let doc_comment = if let Some(desc) = &schema.description {
            quote! { #[doc = #desc] }
        } else {
            TokenStream::new()
        };

        // Generate derives with optional Specta support
        let derives = if self.config.enable_specta {
            quote! {
                #[derive(Debug, Clone, Deserialize, Serialize)]
                #[cfg_attr(feature = "specta", derive(specta::Type))]
                #[serde(untagged)]
            }
        } else {
            quote! {
                #[derive(Debug, Clone, Deserialize, Serialize)]
                #[serde(untagged)]
            }
        };

        Ok(quote! {
            #doc_comment
            #derives
            pub enum #enum_name {
                #(#enum_variants)*
            }
        })
    }

    fn generate_field_type(
        &self,
        schema_name: &str,
        field_name: &str,
        prop: &crate::analysis::PropertyInfo,
        is_required: bool,
        analysis: &crate::analysis::SchemaAnalysis,
    ) -> TokenStream {
        use crate::analysis::SchemaType;

        let base_type = match &prop.schema_type {
            SchemaType::Primitive { rust_type } => {
                // Handle complex types like serde_json::Value
                if rust_type.contains("::") {
                    let parts: Vec<&str> = rust_type.split("::").collect();
                    if parts.len() == 2 {
                        let module = format_ident!("{}", parts[0]);
                        let type_name = format_ident!("{}", parts[1]);
                        quote! { #module::#type_name }
                    } else {
                        // More than 2 parts, construct path
                        let path_parts: Vec<_> =
                            parts.iter().map(|p| format_ident!("{}", p)).collect();
                        quote! { #(#path_parts)::* }
                    }
                } else {
                    let type_ident = format_ident!("{}", rust_type);
                    quote! { #type_ident }
                }
            }
            SchemaType::Reference { target } => {
                let target_type = format_ident!("{}", self.to_rust_type_name(target));
                // Wrap recursive references in Box<T> for heap allocation
                if analysis.dependencies.recursive_schemas.contains(target) {
                    quote! { Box<#target_type> }
                } else {
                    quote! { #target_type }
                }
            }
            SchemaType::Array { item_type } => {
                let inner_type = self.generate_array_item_type(item_type, analysis);
                quote! { Vec<#inner_type> }
            }
            _ => {
                // Fallback for complex types
                quote! { serde_json::Value }
            }
        };

        // Check if this field has a nullable override
        let override_key = format!("{schema_name}.{field_name}");
        let is_nullable_override = self
            .config
            .nullable_field_overrides
            .get(&override_key)
            .copied()
            .unwrap_or(false);

        if is_required && !prop.nullable && !is_nullable_override {
            // If the field has a default value but its type doesn't implement Default,
            // wrap in Option<T> so serde can default to None instead of requiring Default.
            if prop.default.is_some() && self.type_lacks_default(&prop.schema_type, analysis) {
                quote! { Option<#base_type> }
            } else {
                base_type
            }
        } else {
            quote! { Option<#base_type> }
        }
    }

    fn generate_serde_field_attrs(
        &self,
        field_name: &str,
        prop: &crate::analysis::PropertyInfo,
        is_required: bool,
        analysis: &crate::analysis::SchemaAnalysis,
    ) -> TokenStream {
        let mut attrs = Vec::new();

        // Generate rename attribute if field name differs from Rust identifier
        // Strip r# prefix for comparison since serde handles raw idents transparently
        let rust_field_name = self.to_rust_field_name(field_name);
        let comparison_name = rust_field_name
            .strip_prefix("r#")
            .unwrap_or(&rust_field_name);
        if comparison_name != field_name {
            attrs.push(quote! { rename = #field_name });
        }

        // Add skip_serializing_if for optional fields to avoid sending null values
        if !is_required || prop.nullable {
            attrs.push(quote! { skip_serializing_if = "Option::is_none" });
        }

        // Only add default attribute for required fields that have default values.
        // Skip #[serde(default)] for types that don't implement Default (discriminated
        // unions, union enums) — those fields should be Option<T> instead.
        if prop.default.is_some()
            && (is_required && !prop.nullable)
            && !self.type_lacks_default(&prop.schema_type, analysis)
        {
            attrs.push(quote! { default });
        }

        if attrs.is_empty() {
            TokenStream::new()
        } else {
            quote! { #[serde(#(#attrs),*)] }
        }
    }

    /// Check if a schema type resolves to a type that doesn't implement `Default`.
    /// Discriminated unions and union enums don't derive Default, so fields with
    /// these types can't use `#[serde(default)]`.
    fn type_lacks_default(
        &self,
        schema_type: &crate::analysis::SchemaType,
        analysis: &crate::analysis::SchemaAnalysis,
    ) -> bool {
        use crate::analysis::SchemaType;
        match schema_type {
            SchemaType::DiscriminatedUnion { .. } | SchemaType::Union { .. } => true,
            SchemaType::Reference { target } => {
                if let Some(schema) = analysis.schemas.get(target) {
                    self.type_lacks_default(&schema.schema_type, analysis)
                } else {
                    false
                }
            }
            _ => false,
        }
    }

    fn generate_specta_field_attrs(&self, field_name: &str) -> TokenStream {
        if !self.config.enable_specta {
            return TokenStream::new();
        }

        // Convert field name to camelCase for TypeScript
        let camel_case_name = self.to_camel_case(field_name);

        // Only add specta rename if it differs from the original field name
        if camel_case_name != field_name {
            quote! { #[cfg_attr(feature = "specta", specta(rename = #camel_case_name))] }
        } else {
            TokenStream::new()
        }
    }

    fn to_rust_enum_variant(&self, s: &str) -> String {
        // Convert string to valid Rust enum variant (PascalCase)
        let mut result = String::new();
        let mut next_upper = true;
        let mut prev_was_upper = false;

        for (i, c) in s.chars().enumerate() {
            match c {
                'a'..='z' => {
                    if next_upper {
                        result.push(c.to_ascii_uppercase());
                        next_upper = false;
                    } else {
                        result.push(c);
                    }
                    prev_was_upper = false;
                }
                'A'..='Z' => {
                    if next_upper || (!prev_was_upper && i > 0) {
                        // Start of word or transition from lowercase
                        result.push(c);
                        next_upper = false;
                    } else {
                        // Continue uppercase sequence, convert to lowercase
                        result.push(c.to_ascii_lowercase());
                    }
                    prev_was_upper = true;
                }
                '0'..='9' => {
                    result.push(c);
                    next_upper = false;
                    prev_was_upper = false;
                }
                '.' | '-' | '_' | ' ' | '@' | '#' | '$' | '/' | '\\' => {
                    // Word boundaries - next char should be uppercase
                    next_upper = true;
                    prev_was_upper = false;
                }
                _ => {
                    // Other special characters - treat as word boundary
                    next_upper = true;
                    prev_was_upper = false;
                }
            }
        }

        // Handle empty result
        if result.is_empty() {
            result = "Value".to_string();
        }

        // Ensure variant starts with a letter (not a number)
        if result.chars().next().is_some_and(|c| c.is_ascii_digit()) {
            result = format!("Variant{result}");
        }

        // Handle special cases for enum variants
        match result.as_str() {
            "Null" => "NullValue".to_string(),
            "True" => "TrueValue".to_string(),
            "False" => "FalseValue".to_string(),
            "Type" => "Type_".to_string(),
            "Match" => "Match_".to_string(),
            "Fn" => "Fn_".to_string(),
            "Impl" => "Impl_".to_string(),
            "Trait" => "Trait_".to_string(),
            "Struct" => "Struct_".to_string(),
            "Enum" => "Enum_".to_string(),
            "Mod" => "Mod_".to_string(),
            "Use" => "Use_".to_string(),
            "Pub" => "Pub_".to_string(),
            "Const" => "Const_".to_string(),
            "Static" => "Static_".to_string(),
            "Let" => "Let_".to_string(),
            "Mut" => "Mut_".to_string(),
            "Ref" => "Ref_".to_string(),
            "Move" => "Move_".to_string(),
            "Return" => "Return_".to_string(),
            "If" => "If_".to_string(),
            "Else" => "Else_".to_string(),
            "While" => "While_".to_string(),
            "For" => "For_".to_string(),
            "Loop" => "Loop_".to_string(),
            "Break" => "Break_".to_string(),
            "Continue" => "Continue_".to_string(),
            "Self" => "Self_".to_string(),
            "Super" => "Super_".to_string(),
            "Crate" => "Crate_".to_string(),
            "Async" => "Async_".to_string(),
            "Await" => "Await_".to_string(),
            _ => result,
        }
    }

    #[allow(dead_code)]
    fn to_rust_identifier(&self, s: &str) -> String {
        // Convert string to valid Rust identifier
        let mut result = s
            .chars()
            .map(|c| match c {
                'a'..='z' | 'A'..='Z' | '0'..='9' => c,
                '.' | '-' | '_' | ' ' | '@' | '#' | '$' | '/' | '\\' => '_',
                _ => '_',
            })
            .collect::<String>();

        // Remove leading/trailing underscores
        result = result.trim_matches('_').to_string();

        // Handle empty result
        if result.is_empty() {
            result = "value".to_string();
        }

        // Ensure identifier starts with a letter (not a number)
        if result.chars().next().is_some_and(|c| c.is_ascii_digit()) {
            result = format!("variant_{result}");
        }

        // Handle special cases for enum values
        match result.as_str() {
            "null" => "null_value".to_string(),
            "true" => "true_value".to_string(),
            "false" => "false_value".to_string(),
            "type" => "type_".to_string(),
            "match" => "match_".to_string(),
            "fn" => "fn_".to_string(),
            "impl" => "impl_".to_string(),
            "trait" => "trait_".to_string(),
            "struct" => "struct_".to_string(),
            "enum" => "enum_".to_string(),
            "mod" => "mod_".to_string(),
            "use" => "use_".to_string(),
            "pub" => "pub_".to_string(),
            "const" => "const_".to_string(),
            "static" => "static_".to_string(),
            "let" => "let_".to_string(),
            "mut" => "mut_".to_string(),
            "ref" => "ref_".to_string(),
            "move" => "move_".to_string(),
            "return" => "return_".to_string(),
            "if" => "if_".to_string(),
            "else" => "else_".to_string(),
            "while" => "while_".to_string(),
            "for" => "for_".to_string(),
            "loop" => "loop_".to_string(),
            "break" => "break_".to_string(),
            "continue" => "continue_".to_string(),
            "self" => "self_".to_string(),
            "super" => "super_".to_string(),
            "crate" => "crate_".to_string(),
            "async" => "async_".to_string(),
            "await" => "await_".to_string(),
            // Reserved keywords for edition 2018+
            "override" => "override_".to_string(),
            "box" => "box_".to_string(),
            "dyn" => "dyn_".to_string(),
            "where" => "where_".to_string(),
            "in" => "in_".to_string(),
            // Reserved for future use
            "abstract" => "abstract_".to_string(),
            "become" => "become_".to_string(),
            "do" => "do_".to_string(),
            "final" => "final_".to_string(),
            "macro" => "macro_".to_string(),
            "priv" => "priv_".to_string(),
            "try" => "try_".to_string(),
            "typeof" => "typeof_".to_string(),
            "unsized" => "unsized_".to_string(),
            "virtual" => "virtual_".to_string(),
            "yield" => "yield_".to_string(),
            _ => result,
        }
    }

    fn sanitize_doc_comment(&self, desc: &str) -> String {
        // Sanitize description to prevent doctest failures
        let mut result = desc.to_string();

        // Look for potential code examples that might be interpreted as doctests
        // Common patterns that cause issues:
        // - Lines that look like standalone expressions
        // - JSON-like content
        // - Template strings with {}

        // If the description contains what looks like code, wrap it in a text block
        if result.contains('\n')
            && (result.contains('{')
                || result.contains("```")
                || result.contains("Human:")
                || result.contains("Assistant:")
                || result
                    .lines()
                    .any(|line| line.trim().starts_with('"') && line.trim().ends_with('"')))
        {
            // If it already has code blocks, add ignore annotation
            if result.contains("```") {
                result = result.replace("```", "```ignore");
            } else {
                // Wrap the entire description in an ignored code block if it looks like code
                if result.lines().any(|line| {
                    let trimmed = line.trim();
                    trimmed.starts_with('"') && trimmed.ends_with('"') && trimmed.len() > 2
                }) {
                    result = format!("```ignore\n{result}\n```");
                }
            }
        }

        result
    }

    pub(crate) fn to_rust_type_name(&self, s: &str) -> String {
        // Convert string to valid Rust type name (PascalCase)
        let mut result = String::new();
        let mut next_upper = true;
        let mut prev_was_lower = false;

        for c in s.chars() {
            match c {
                'a'..='z' => {
                    if next_upper {
                        result.push(c.to_ascii_uppercase());
                        next_upper = false;
                    } else {
                        result.push(c);
                    }
                    prev_was_lower = true;
                }
                'A'..='Z' => {
                    result.push(c);
                    next_upper = false;
                    prev_was_lower = false;
                }
                '0'..='9' => {
                    // If previous was lowercase letter and this is start of a number sequence,
                    // make it uppercase to improve readability (e.g., Tool20241022 instead of Tool20241022)
                    if prev_was_lower && !result.chars().last().unwrap_or(' ').is_ascii_digit() {
                        // This is fine as-is, the number follows naturally
                    }
                    result.push(c);
                    next_upper = false;
                    prev_was_lower = false;
                }
                '_' | '-' | '.' | ' ' => {
                    // Skip underscore/separator and make next char uppercase
                    next_upper = true;
                    prev_was_lower = false;
                }
                _ => {
                    // Other special characters - treat as word boundary
                    next_upper = true;
                    prev_was_lower = false;
                }
            }
        }

        // Handle empty result
        if result.is_empty() {
            result = "Type".to_string();
        }

        // Ensure type name starts with a letter (not a number)
        if result.chars().next().is_some_and(|c| c.is_ascii_digit()) {
            result = format!("Type{result}");
        }

        result
    }

    fn to_rust_field_name(&self, s: &str) -> String {
        // Convert field name to snake_case properly
        let mut result = String::new();
        let mut prev_was_upper = false;
        let mut prev_was_underscore = false;

        for (i, c) in s.chars().enumerate() {
            match c {
                'A'..='Z' => {
                    // Add underscore before uppercase if previous was lowercase
                    if i > 0 && !prev_was_upper && !prev_was_underscore {
                        result.push('_');
                    }
                    result.push(c.to_ascii_lowercase());
                    prev_was_upper = true;
                    prev_was_underscore = false;
                }
                'a'..='z' | '0'..='9' => {
                    result.push(c);
                    prev_was_upper = false;
                    prev_was_underscore = false;
                }
                '-' | '.' | '_' | '@' | '#' | '$' | ' ' => {
                    if !prev_was_underscore && !result.is_empty() {
                        result.push('_');
                        prev_was_underscore = true;
                    }
                    prev_was_upper = false;
                }
                _ => {
                    // For other special characters, convert to underscore
                    if !prev_was_underscore && !result.is_empty() {
                        result.push('_');
                    }
                    prev_was_upper = false;
                    prev_was_underscore = true;
                }
            }
        }

        // Clean up result
        let mut result = result.trim_matches('_').to_string();
        if result.is_empty() {
            return "field".to_string();
        }

        // Ensure field name starts with a letter or underscore (not a number)
        if result.chars().next().is_some_and(|c| c.is_ascii_digit()) {
            result = format!("field_{result}");
        }

        // Handle reserved keywords using raw identifiers (r#keyword)
        if Self::is_rust_keyword(&result) {
            format!("r#{result}")
        } else {
            result
        }
    }

    /// Check if a string is a Rust keyword that needs raw identifier treatment
    pub fn is_rust_keyword(s: &str) -> bool {
        matches!(
            s,
            "type"
                | "match"
                | "fn"
                | "struct"
                | "enum"
                | "impl"
                | "trait"
                | "mod"
                | "use"
                | "pub"
                | "const"
                | "static"
                | "let"
                | "mut"
                | "ref"
                | "move"
                | "return"
                | "if"
                | "else"
                | "while"
                | "for"
                | "loop"
                | "break"
                | "continue"
                | "self"
                | "super"
                | "crate"
                | "async"
                | "await"
                | "override"
                | "box"
                | "dyn"
                | "where"
                | "in"
                | "abstract"
                | "become"
                | "do"
                | "final"
                | "macro"
                | "priv"
                | "try"
                | "typeof"
                | "unsized"
                | "virtual"
                | "yield"
        )
    }

    /// Create a proc_macro2::Ident from a field name, handling r# raw identifiers
    pub fn to_field_ident(name: &str) -> proc_macro2::Ident {
        if let Some(raw) = name.strip_prefix("r#") {
            proc_macro2::Ident::new_raw(raw, proc_macro2::Span::call_site())
        } else {
            proc_macro2::Ident::new(name, proc_macro2::Span::call_site())
        }
    }

    fn to_camel_case(&self, s: &str) -> String {
        // Convert snake_case or other formats to camelCase
        let mut result = String::new();
        let mut capitalize_next = false;

        for (i, c) in s.chars().enumerate() {
            match c {
                '_' | '-' | '.' | ' ' => {
                    // Word boundary - capitalize next letter
                    capitalize_next = true;
                }
                'A'..='Z' => {
                    if i == 0 {
                        // First character should be lowercase in camelCase
                        result.push(c.to_ascii_lowercase());
                    } else if capitalize_next {
                        result.push(c);
                        capitalize_next = false;
                    } else {
                        result.push(c.to_ascii_lowercase());
                    }
                }
                'a'..='z' | '0'..='9' => {
                    if capitalize_next {
                        result.push(c.to_ascii_uppercase());
                        capitalize_next = false;
                    } else {
                        result.push(c);
                    }
                }
                _ => {
                    // Other characters - treat as word boundary
                    capitalize_next = true;
                }
            }
        }

        if result.is_empty() {
            return "field".to_string();
        }

        result
    }

    fn generate_composition_struct(
        &self,
        schema: &crate::analysis::AnalyzedSchema,
        schemas: &[crate::analysis::SchemaRef],
    ) -> Result<TokenStream> {
        let struct_name = format_ident!("{}", self.to_rust_type_name(&schema.name));

        // For composition, we can either:
        // 1. Flatten all referenced schemas into one struct (if they're all objects)
        // 2. Use serde(flatten) to compose them at runtime
        // For now, let's use approach 2 with serde(flatten)

        let fields = schemas.iter().enumerate().map(|(i, schema_ref)| {
            let field_name = format_ident!("part_{}", i);
            let field_type = format_ident!("{}", self.to_rust_type_name(&schema_ref.target));

            quote! {
                #[serde(flatten)]
                pub #field_name: #field_type,
            }
        });

        let doc_comment = if let Some(desc) = &schema.description {
            quote! { #[doc = #desc] }
        } else {
            TokenStream::new()
        };

        // Generate derives with optional Specta support
        let derives = if self.config.enable_specta {
            quote! {
                #[derive(Debug, Clone, Deserialize, Serialize)]
                #[cfg_attr(feature = "specta", derive(specta::Type))]
            }
        } else {
            quote! {
                #[derive(Debug, Clone, Deserialize, Serialize)]
            }
        };

        Ok(quote! {
            #doc_comment
            #derives
            pub struct #struct_name {
                #(#fields)*
            }
        })
    }

    #[allow(dead_code)]
    fn find_missing_types(&self, analysis: &SchemaAnalysis) -> std::collections::HashSet<String> {
        let mut missing = std::collections::HashSet::new();
        let defined_types: std::collections::HashSet<String> =
            analysis.schemas.keys().cloned().collect();

        // Check all references in union variants
        for schema in analysis.schemas.values() {
            match &schema.schema_type {
                crate::analysis::SchemaType::Union { variants } => {
                    for variant in variants {
                        if !defined_types.contains(&variant.target) {
                            missing.insert(variant.target.clone());
                        }
                    }
                }
                crate::analysis::SchemaType::DiscriminatedUnion { variants, .. } => {
                    for variant in variants {
                        if !defined_types.contains(&variant.type_name) {
                            missing.insert(variant.type_name.clone());
                        }
                    }
                }
                crate::analysis::SchemaType::Object { properties, .. } => {
                    // Sort properties for deterministic iteration
                    let mut sorted_props: Vec<_> = properties.iter().collect();
                    sorted_props.sort_by_key(|(name, _)| name.as_str());
                    for (_, prop) in sorted_props {
                        if let crate::analysis::SchemaType::Reference { target } = &prop.schema_type
                        {
                            if !defined_types.contains(target) {
                                missing.insert(target.clone());
                            }
                        }
                    }
                }
                crate::analysis::SchemaType::Reference { target }
                    if !defined_types.contains(target) =>
                {
                    missing.insert(target.clone());
                }
                _ => {}
            }
        }

        missing
    }

    #[allow(clippy::only_used_in_recursion)]
    fn generate_array_item_type(
        &self,
        item_type: &crate::analysis::SchemaType,
        analysis: &crate::analysis::SchemaAnalysis,
    ) -> TokenStream {
        use crate::analysis::SchemaType;

        match item_type {
            SchemaType::Primitive { rust_type } => {
                // Handle complex types like serde_json::Value
                if rust_type.contains("::") {
                    let parts: Vec<&str> = rust_type.split("::").collect();
                    if parts.len() == 2 {
                        let module = format_ident!("{}", parts[0]);
                        let type_name = format_ident!("{}", parts[1]);
                        quote! { #module::#type_name }
                    } else {
                        // More than 2 parts, construct path
                        let path_parts: Vec<_> =
                            parts.iter().map(|p| format_ident!("{}", p)).collect();
                        quote! { #(#path_parts)::* }
                    }
                } else {
                    let type_ident = format_ident!("{}", rust_type);
                    quote! { #type_ident }
                }
            }
            SchemaType::Reference { target } => {
                let target_type = format_ident!("{}", self.to_rust_type_name(target));
                // Wrap recursive references in Box<T> for heap allocation in arrays
                if analysis.dependencies.recursive_schemas.contains(target) {
                    quote! { Box<#target_type> }
                } else {
                    quote! { #target_type }
                }
            }
            SchemaType::Array { item_type } => {
                // Nested arrays
                let inner_type = self.generate_array_item_type(item_type, analysis);
                quote! { Vec<#inner_type> }
            }
            _ => {
                // Fallback for complex types
                quote! { serde_json::Value }
            }
        }
    }

    /// Convert a type name to a variant name (e.g., OutputMessage -> OutputMessage, FileSearchToolCall -> FileSearchToolCall)
    fn type_name_to_variant_name(&self, type_name: &str) -> String {
        // Handle primitive types specially
        match type_name {
            "bool" => return "Boolean".to_string(),
            "i8" | "i16" | "i32" | "i64" | "i128" => return "Integer".to_string(),
            "u8" | "u16" | "u32" | "u64" | "u128" => return "UnsignedInteger".to_string(),
            "f32" | "f64" => return "Number".to_string(),
            "String" => return "String".to_string(),
            "serde_json::Value" => return "Value".to_string(),
            _ => {}
        }

        // Handle Vec types
        if type_name.starts_with("Vec<") && type_name.ends_with(">") {
            let inner = &type_name[4..type_name.len() - 1];
            // Handle nested Vec types specially
            if inner.starts_with("Vec<") && inner.ends_with(">") {
                let inner_inner = &inner[4..inner.len() - 1];
                return format!("{}ArrayArray", self.type_name_to_variant_name(inner_inner));
            }
            return format!("{}Array", self.type_name_to_variant_name(inner));
        }

        // For untagged unions, we want to use the type name itself as the variant name
        // since it's already meaningful. This gives us OutputMessage instead of Variant0,
        // FileSearchToolCall instead of Variant1, etc.

        // Remove common suffixes that might make variant names redundant
        let clean_name = type_name
            .trim_end_matches("Type")
            .trim_end_matches("Schema")
            .trim_end_matches("Item");

        // Always convert to proper PascalCase to ensure no underscores in enum variants
        self.to_rust_type_name(clean_name)
    }

    /// Ensure unique variant name for generator (similar to analyzer but for generator context)
    fn ensure_unique_variant_name_generator(
        &self,
        base_name: String,
        used_names: &mut std::collections::HashSet<String>,
        fallback_index: usize,
    ) -> String {
        if used_names.insert(base_name.clone()) {
            return base_name;
        }

        // Try with numbers
        for i in 2..100 {
            let numbered_name = format!("{base_name}{i}");
            if used_names.insert(numbered_name.clone()) {
                return numbered_name;
            }
        }

        // Fallback to Variant{index} if all else fails
        let fallback = format!("Variant{fallback_index}");
        used_names.insert(fallback.clone());
        fallback
    }

    /// Find the request type for a given operation ID using the analyzed operation info
    fn find_request_type_for_operation(
        &self,
        operation_id: &str,
        analysis: &SchemaAnalysis,
    ) -> Option<String> {
        // Use the operation analysis to get the actual request body schema
        analysis.operations.get(operation_id).and_then(|op| {
            op.request_body
                .as_ref()
                .and_then(|rb| rb.schema_name().map(|s| s.to_string()))
        })
    }

    /// Resolve the correct streaming event type based on EventFlow pattern
    fn resolve_streaming_event_type(
        &self,
        endpoint: &crate::streaming::StreamingEndpoint,
        analysis: &SchemaAnalysis,
    ) -> Result<String> {
        match &endpoint.event_flow {
            crate::streaming::EventFlow::Simple => {
                // For simple streaming, use the response type directly
                // Validate that the specified type exists in the schema
                if analysis.schemas.contains_key(&endpoint.event_union_type) {
                    Ok(endpoint.event_union_type.to_string())
                } else {
                    Err(crate::error::GeneratorError::ValidationError(format!(
                        "Streaming response type '{}' not found in schema for simple streaming endpoint '{}'",
                        endpoint.event_union_type, endpoint.operation_id
                    )))
                }
            }
            crate::streaming::EventFlow::StartDeltaStop { .. } => {
                // For complex event-based streaming, ensure we have a proper union type
                // For now, use the specified event_union_type but add validation
                if analysis.schemas.contains_key(&endpoint.event_union_type) {
                    Ok(endpoint.event_union_type.to_string())
                } else {
                    Err(crate::error::GeneratorError::ValidationError(format!(
                        "Event union type '{}' not found in schema for complex streaming endpoint '{}'",
                        endpoint.event_union_type, endpoint.operation_id
                    )))
                }
            }
        }
    }

    /// Generate streaming error types
    fn generate_streaming_error_types(&self) -> Result<TokenStream> {
        Ok(quote! {
            /// Error type for streaming operations
            #[derive(Debug, thiserror::Error)]
            pub enum StreamingError {
                #[error("Connection error: {0}")]
                Connection(String),
                #[error("HTTP error: {status}")]
                Http { status: u16 },
                #[error("SSE parsing error: {0}")]
                Parsing(String),
                #[error("Authentication error: {0}")]
                Authentication(String),
                #[error("Rate limit error: {0}")]
                RateLimit(String),
                #[error("API error: {0}")]
                Api(String),
                #[error("Timeout error: {0}")]
                Timeout(String),
                #[error("JSON serialization/deserialization error: {0}")]
                Json(#[from] serde_json::Error),
                #[error("Request error: {0}")]
                Request(reqwest::Error),
            }

            impl From<reqwest::header::InvalidHeaderValue> for StreamingError {
                fn from(err: reqwest::header::InvalidHeaderValue) -> Self {
                    StreamingError::Api(format!("Invalid header value: {}", err))
                }
            }

            impl From<reqwest::Error> for StreamingError {
                fn from(err: reqwest::Error) -> Self {
                    if err.is_timeout() {
                        StreamingError::Timeout(err.to_string())
                    } else if err.is_status() {
                        if let Some(status) = err.status() {
                            StreamingError::Http { status: status.as_u16() }
                        } else {
                            StreamingError::Connection(err.to_string())
                        }
                    } else {
                        StreamingError::Request(err)
                    }
                }
            }
        })
    }

    /// Generate trait for a streaming endpoint
    fn generate_endpoint_trait(
        &self,
        endpoint: &crate::streaming::StreamingEndpoint,
        analysis: &SchemaAnalysis,
    ) -> Result<TokenStream> {
        use crate::streaming::HttpMethod;

        let trait_name = format_ident!(
            "{}StreamingClient",
            self.to_rust_type_name(&endpoint.operation_id)
        );
        let method_name =
            format_ident!("stream_{}", self.to_rust_field_name(&endpoint.operation_id));
        let event_type =
            format_ident!("{}", self.resolve_streaming_event_type(endpoint, analysis)?);

        // Generate method signature based on HTTP method
        let method_signature = match endpoint.http_method {
            HttpMethod::Get => {
                // Generate parameters from query_parameters
                let mut param_defs = Vec::new();
                for qp in &endpoint.query_parameters {
                    let param_name = format_ident!("{}", self.to_rust_field_name(&qp.name));
                    if qp.required {
                        param_defs.push(quote! { #param_name: &str });
                    } else {
                        param_defs.push(quote! { #param_name: Option<&str> });
                    }
                }
                quote! {
                    async fn #method_name(
                        &self,
                        #(#param_defs),*
                    ) -> Result<Pin<Box<dyn Stream<Item = Result<#event_type, Self::Error>> + Send>>, Self::Error>;
                }
            }
            HttpMethod::Post => {
                // Find the request type for this operation
                let request_type = self
                    .find_request_type_for_operation(&endpoint.operation_id, analysis)
                    .unwrap_or_else(|| "serde_json::Value".to_string());
                let request_type_ident = if request_type.contains("::") {
                    let parts: Vec<&str> = request_type.split("::").collect();
                    let path_parts: Vec<_> = parts.iter().map(|p| format_ident!("{}", p)).collect();
                    quote! { #(#path_parts)::* }
                } else {
                    let ident = format_ident!("{}", request_type);
                    quote! { #ident }
                };
                quote! {
                    async fn #method_name(
                        &self,
                        request: #request_type_ident,
                    ) -> Result<Pin<Box<dyn Stream<Item = Result<#event_type, Self::Error>> + Send>>, Self::Error>;
                }
            }
        };

        Ok(quote! {
            /// Streaming client trait for this endpoint
            #[async_trait]
            pub trait #trait_name {
                type Error: std::error::Error + Send + Sync + 'static;

                /// Stream events from the API
                #method_signature
            }
        })
    }

    /// Generate streaming client implementation
    fn generate_streaming_client_impl(
        &self,
        streaming_config: &crate::streaming::StreamingConfig,
        analysis: &SchemaAnalysis,
    ) -> Result<TokenStream> {
        let client_name = format_ident!(
            "{}Client",
            self.to_rust_type_name(&streaming_config.client_module_name)
        );

        // Generate struct fields
        // Always include custom_headers for flexibility (like HttpClient does)
        let mut struct_fields = vec![
            quote! { base_url: String },
            quote! { api_key: Option<String> },
            quote! { http_client: reqwest::Client },
            quote! { custom_headers: std::collections::BTreeMap<String, String> },
        ];

        let has_optional_headers = !streaming_config
            .endpoints
            .iter()
            .all(|e| e.optional_headers.is_empty());

        if has_optional_headers {
            struct_fields
                .push(quote! { optional_headers: std::collections::BTreeMap<String, String> });
        }

        // Generate constructor
        // Use configured base URL as default, or fallback to generic example
        let default_base_url = if let Some(ref streaming_config) = self.config.streaming_config {
            streaming_config
                .endpoints
                .first()
                .and_then(|e| e.base_url.as_deref())
                .unwrap_or("https://api.example.com")
        } else {
            "https://api.example.com"
        };

        // Build constructor fields based on what the struct has
        let constructor_fields = if has_optional_headers {
            quote! {
                base_url: #default_base_url.to_string(),
                api_key: None,
                http_client: reqwest::Client::new(),
                custom_headers: std::collections::BTreeMap::new(),
                optional_headers: std::collections::BTreeMap::new(),
            }
        } else {
            quote! {
                base_url: #default_base_url.to_string(),
                api_key: None,
                http_client: reqwest::Client::new(),
                custom_headers: std::collections::BTreeMap::new(),
            }
        };

        // Optional headers method only if the struct has the field
        let optional_headers_method = if has_optional_headers {
            quote! {
                /// Set optional headers for all requests
                pub fn set_optional_headers(&mut self, headers: std::collections::BTreeMap<String, String>) {
                    self.optional_headers = headers;
                }
            }
        } else {
            TokenStream::new()
        };

        let constructor = quote! {
            impl #client_name {
                /// Create a new streaming client
                pub fn new() -> Self {
                    Self {
                        #constructor_fields
                    }
                }

                /// Set the base URL for API requests
                pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
                    self.base_url = base_url.into();
                    self
                }

                /// Set the API key for authentication
                pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
                    self.api_key = Some(api_key.into());
                    self
                }

                /// Add a custom header to all requests
                pub fn with_header(
                    mut self,
                    name: impl Into<String>,
                    value: impl Into<String>,
                ) -> Self {
                    self.custom_headers.insert(name.into(), value.into());
                    self
                }

                /// Set the HTTP client
                pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
                    self.http_client = client;
                    self
                }

                #optional_headers_method
            }
        };

        // Generate trait implementations for each endpoint
        let mut trait_impls = Vec::new();
        for endpoint in &streaming_config.endpoints {
            let trait_impl = self.generate_endpoint_trait_impl(endpoint, &client_name, analysis)?;
            trait_impls.push(trait_impl);
        }

        // Add Default implementation
        let default_impl = quote! {
            impl Default for #client_name {
                fn default() -> Self {
                    Self::new()
                }
            }
        };

        Ok(quote! {
            /// Streaming client implementation
            #[derive(Debug, Clone)]
            pub struct #client_name {
                #(#struct_fields,)*
            }

            #constructor

            #default_impl

            #(#trait_impls)*
        })
    }

    /// Generate trait implementation for a specific endpoint
    fn generate_endpoint_trait_impl(
        &self,
        endpoint: &crate::streaming::StreamingEndpoint,
        client_name: &proc_macro2::Ident,
        analysis: &SchemaAnalysis,
    ) -> Result<TokenStream> {
        use crate::streaming::HttpMethod;

        let trait_name = format_ident!(
            "{}StreamingClient",
            self.to_rust_type_name(&endpoint.operation_id)
        );
        let method_name =
            format_ident!("stream_{}", self.to_rust_field_name(&endpoint.operation_id));
        let event_type =
            format_ident!("{}", self.resolve_streaming_event_type(endpoint, analysis)?);

        // Generate required headers
        let mut header_setup = Vec::new();
        for (name, value) in &endpoint.required_headers {
            header_setup.push(quote! {
                headers.insert(#name, HeaderValue::from_static(#value));
            });
        }

        // Add authentication header
        // If auth_header is configured, use that; otherwise default to Bearer auth on Authorization header
        if let Some(auth_header) = &endpoint.auth_header {
            match auth_header {
                crate::streaming::AuthHeader::Bearer(header_name) => {
                    header_setup.push(quote! {
                        if let Some(ref api_key) = self.api_key {
                            headers.insert(#header_name, HeaderValue::from_str(&format!("Bearer {}", api_key))?);
                        }
                    });
                }
                crate::streaming::AuthHeader::ApiKey(header_name) => {
                    header_setup.push(quote! {
                        if let Some(ref api_key) = self.api_key {
                            headers.insert(#header_name, HeaderValue::from_str(api_key)?);
                        }
                    });
                }
            }
        } else {
            // Default: use api_key as Bearer token on Authorization header
            header_setup.push(quote! {
                if let Some(ref api_key) = self.api_key {
                    headers.insert("Authorization", HeaderValue::from_str(&format!("Bearer {}", api_key))?);
                }
            });
        }

        // Always add custom_headers (like HttpClient does)
        header_setup.push(quote! {
            for (name, value) in &self.custom_headers {
                if let (Ok(header_name), Ok(header_value)) = (reqwest::header::HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) {
                    headers.insert(header_name, header_value);
                }
            }
        });

        // Add optional headers (for endpoint-specific optional headers)
        if !endpoint.optional_headers.is_empty() {
            header_setup.push(quote! {
                for (key, value) in &self.optional_headers {
                    if let (Ok(header_name), Ok(header_value)) = (reqwest::header::HeaderName::from_bytes(key.as_bytes()), HeaderValue::from_str(value)) {
                        headers.insert(header_name, header_value);
                    }
                }
            });
        }

        // Generate different code for GET vs POST
        match endpoint.http_method {
            HttpMethod::Get => self.generate_get_streaming_impl(
                endpoint,
                client_name,
                &trait_name,
                &method_name,
                &event_type,
                &header_setup,
            ),
            HttpMethod::Post => self.generate_post_streaming_impl(
                endpoint,
                client_name,
                &trait_name,
                &method_name,
                &event_type,
                &header_setup,
                analysis,
            ),
        }
    }

    /// Generate streaming implementation for GET endpoints
    fn generate_get_streaming_impl(
        &self,
        endpoint: &crate::streaming::StreamingEndpoint,
        client_name: &proc_macro2::Ident,
        trait_name: &proc_macro2::Ident,
        method_name: &proc_macro2::Ident,
        event_type: &proc_macro2::Ident,
        header_setup: &[TokenStream],
    ) -> Result<TokenStream> {
        let path = &endpoint.path;

        // Generate method parameters from query_parameters
        let mut param_defs = Vec::new();
        let mut query_params = Vec::new();

        for qp in &endpoint.query_parameters {
            let param_name = format_ident!("{}", self.to_rust_field_name(&qp.name));
            let param_name_str = &qp.name;

            if qp.required {
                param_defs.push(quote! { #param_name: &str });
                query_params.push(quote! {
                    url.query_pairs_mut().append_pair(#param_name_str, #param_name);
                });
            } else {
                param_defs.push(quote! { #param_name: Option<&str> });
                query_params.push(quote! {
                    if let Some(v) = #param_name {
                        url.query_pairs_mut().append_pair(#param_name_str, v);
                    }
                });
            }
        }

        // Generate URL construction for GET
        let url_construction = quote! {
            let base_url = url::Url::parse(&self.base_url)
                .map_err(|e| StreamingError::Connection(format!("Invalid base URL: {}", e)))?;
            let path_to_join = #path.trim_start_matches('/');
            let mut url = base_url.join(path_to_join)
                .map_err(|e| StreamingError::Connection(format!("URL join error: {}", e)))?;
            #(#query_params)*
        };

        let instrument_skip = quote! { #[instrument(skip(self), name = "streaming_get_request")] };

        Ok(quote! {
            #[async_trait]
            impl #trait_name for #client_name {
                type Error = StreamingError;

                #instrument_skip
                async fn #method_name(
                    &self,
                    #(#param_defs),*
                ) -> Result<Pin<Box<dyn Stream<Item = Result<#event_type, Self::Error>> + Send>>, Self::Error> {
                    debug!("Starting streaming GET request");

                    let mut headers = HeaderMap::new();
                    #(#header_setup)*

                    #url_construction
                    let url_str = url.to_string();
                    debug!("Making streaming GET request to: {}", url_str);

                    let request_builder = self.http_client
                        .get(url_str)
                        .headers(headers);

                    debug!("Creating SSE stream from request");
                    let stream = parse_sse_stream::<#event_type>(request_builder).await?;
                    info!("SSE stream created successfully");
                    Ok(Box::pin(stream))
                }
            }
        })
    }

    /// Generate streaming implementation for POST endpoints
    #[allow(clippy::too_many_arguments)]
    fn generate_post_streaming_impl(
        &self,
        endpoint: &crate::streaming::StreamingEndpoint,
        client_name: &proc_macro2::Ident,
        trait_name: &proc_macro2::Ident,
        method_name: &proc_macro2::Ident,
        event_type: &proc_macro2::Ident,
        header_setup: &[TokenStream],
        analysis: &SchemaAnalysis,
    ) -> Result<TokenStream> {
        let path = &endpoint.path;

        // Find the request type for this operation
        let request_type = self
            .find_request_type_for_operation(&endpoint.operation_id, analysis)
            .unwrap_or_else(|| "serde_json::Value".to_string());
        let request_type_ident = if request_type.contains("::") {
            let parts: Vec<&str> = request_type.split("::").collect();
            let path_parts: Vec<_> = parts.iter().map(|p| format_ident!("{}", p)).collect();
            quote! { #(#path_parts)::* }
        } else {
            let ident = format_ident!("{}", request_type);
            quote! { #ident }
        };

        // Generate URL construction for POST
        let url_construction = quote! {
            let base_url = url::Url::parse(&self.base_url)
                .map_err(|e| StreamingError::Connection(format!("Invalid base URL: {}", e)))?;
            let path_to_join = #path.trim_start_matches('/');
            let url = base_url.join(path_to_join)
                .map_err(|e| StreamingError::Connection(format!("URL join error: {}", e)))?
                .to_string();
        };

        // Generate stream parameter setup (only for POST with stream_parameter)
        let stream_param = &endpoint.stream_parameter;
        let stream_setup = if stream_param.is_empty() {
            quote! {
                let streaming_request = request;
            }
        } else {
            quote! {
                // Ensure streaming is enabled
                let mut streaming_request = request;
                if let Ok(mut request_value) = serde_json::to_value(&streaming_request) {
                    if let Some(obj) = request_value.as_object_mut() {
                        obj.insert(#stream_param.to_string(), serde_json::Value::Bool(true));
                    }
                    streaming_request = serde_json::from_value(request_value)?;
                }
            }
        };

        Ok(quote! {
            #[async_trait]
            impl #trait_name for #client_name {
                type Error = StreamingError;

                #[instrument(skip(self, request), name = "streaming_post_request")]
                async fn #method_name(
                    &self,
                    request: #request_type_ident,
                ) -> Result<Pin<Box<dyn Stream<Item = Result<#event_type, Self::Error>> + Send>>, Self::Error> {
                    debug!("Starting streaming POST request");

                    #stream_setup

                    let mut headers = HeaderMap::new();
                    #(#header_setup)*

                    #url_construction
                    debug!("Making streaming POST request to: {}", url);

                    let request_builder = self.http_client
                        .post(&url)
                        .headers(headers)
                        .json(&streaming_request);

                    debug!("Creating SSE stream from request");
                    let stream = parse_sse_stream::<#event_type>(request_builder).await?;
                    info!("SSE stream created successfully");
                    Ok(Box::pin(stream))
                }
            }
        })
    }

    /// Generate SSE parsing utilities using reqwest-eventsource
    fn generate_sse_parser_utilities(
        &self,
        _streaming_config: &crate::streaming::StreamingConfig,
    ) -> Result<TokenStream> {
        Ok(quote! {
            /// Parse SSE stream from HTTP request using reqwest-eventsource
            pub async fn parse_sse_stream<T>(
                request_builder: reqwest::RequestBuilder
            ) -> Result<impl Stream<Item = Result<T, StreamingError>>, StreamingError>
            where
                T: serde::de::DeserializeOwned + Send + 'static,
            {
                let mut event_source = reqwest_eventsource::EventSource::new(request_builder).map_err(|e| {
                    StreamingError::Connection(format!("Failed to create event source: {}", e))
                })?;

                let stream = event_source.filter_map(|event_result| async move {
                    match event_result {
                        Ok(reqwest_eventsource::Event::Open) => {
                            debug!("SSE connection opened");
                            None
                        }
                        Ok(reqwest_eventsource::Event::Message(message)) => {
                            // Check if this is a ping event by SSE event type
                            if message.event == "ping" {
                                debug!("Received SSE ping event, skipping");
                                return None;
                            }

                            // Special handling for empty data
                            if message.data.trim().is_empty() {
                                debug!("Empty SSE data, skipping");
                                return None;
                            }

                            // Check if this is a ping event in the JSON data
                            if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&message.data) {
                                if let Some(event_type) = json_value.get("event").and_then(|v| v.as_str()) {
                                    if event_type == "ping" {
                                        debug!("Received ping event in JSON data, skipping");
                                        return None;
                                    }
                                }

                                // Try to parse the full event normally
                                match serde_json::from_value::<T>(json_value) {
                                    Ok(parsed_event) => {
                                        Some(Ok(parsed_event))
                                    }
                                    Err(e) => {
                                        if message.data.contains("ping") || message.event.contains("ping") {
                                            debug!("Ignoring ping-related event: {}", message.data);
                                            None
                                        } else {
                                            Some(Err(StreamingError::Parsing(
                                                format!("Failed to parse SSE event: {} (raw: {})", e, message.data)
                                            )))
                                        }
                                    }
                                }
                            } else {
                                // Not valid JSON at all
                                Some(Err(StreamingError::Parsing(
                                    format!("SSE event is not valid JSON: {}", message.data)
                                )))
                            }
                        }
                        Err(e) => {
                            // Check if this is a normal stream end vs actual error
                            match e {
                                reqwest_eventsource::Error::StreamEnded => {
                                    debug!("SSE stream completed normally");
                                    None // Normal stream end, not an error
                                }
                                reqwest_eventsource::Error::InvalidStatusCode(status, response) => {
                                    // We have access to the response body for error details
                                    let status_code = status.as_u16();

                                    // Read the response body to get error details
                                    let error_body = match response.text().await {
                                        Ok(body) => body,
                                        Err(_) => "Failed to read error response body".to_string()
                                    };

                                    error!("SSE connection error - HTTP {}: {}", status_code, error_body);

                                    let detailed_error = format!(
                                        "HTTP {} error: {}",
                                        status_code,
                                        error_body
                                    );

                                    Some(Err(StreamingError::Connection(detailed_error)))
                                }
                                _ => {
                                    let error_str = e.to_string();
                                    if error_str.contains("stream closed") {
                                        debug!("SSE stream closed");
                                        None
                                    } else {
                                        error!("SSE connection error: {}", e);
                                        Some(Err(StreamingError::Connection(error_str)))
                                    }
                                }
                            }
                        }
                    }
                });

                Ok(stream)
            }
        })
    }

    /// Generate reconnection utilities
    fn generate_reconnection_utilities(
        &self,
        reconnect_config: &crate::streaming::ReconnectionConfig,
    ) -> Result<TokenStream> {
        let max_retries = reconnect_config.max_retries;
        let initial_delay = reconnect_config.initial_delay_ms;
        let max_delay = reconnect_config.max_delay_ms;
        let backoff_multiplier = reconnect_config.backoff_multiplier;

        Ok(quote! {
            /// Reconnection configuration and utilities
            #[derive(Debug, Clone)]
            pub struct ReconnectionManager {
                max_retries: u32,
                initial_delay_ms: u64,
                max_delay_ms: u64,
                backoff_multiplier: f64,
                current_attempt: u32,
            }

            impl ReconnectionManager {
                /// Create a new reconnection manager
                pub fn new() -> Self {
                    Self {
                        max_retries: #max_retries,
                        initial_delay_ms: #initial_delay,
                        max_delay_ms: #max_delay,
                        backoff_multiplier: #backoff_multiplier,
                        current_attempt: 0,
                    }
                }

                /// Check if we should retry the connection
                pub fn should_retry(&self) -> bool {
                    self.current_attempt < self.max_retries
                }

                /// Get the delay for the next retry attempt
                pub fn next_retry_delay(&mut self) -> Duration {
                    if !self.should_retry() {
                        return Duration::from_secs(0);
                    }

                    let delay_ms = (self.initial_delay_ms as f64
                        * self.backoff_multiplier.powi(self.current_attempt as i32)) as u64;
                    let delay_ms = delay_ms.min(self.max_delay_ms);

                    self.current_attempt += 1;
                    Duration::from_millis(delay_ms)
                }

                /// Reset the retry counter after a successful connection
                pub fn reset(&mut self) {
                    self.current_attempt = 0;
                }

                /// Get the current attempt number
                pub fn current_attempt(&self) -> u32 {
                    self.current_attempt
                }
            }

            impl Default for ReconnectionManager {
                fn default() -> Self {
                    Self::new()
                }
            }
        })
    }
}