wadl 0.5.7

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

use crate::ast::*;
use std::collections::HashMap;
use url::Url;

/// MIME type for XHTML
pub const XHTML_MIME_TYPE: &str = "application/xhtml+xml";

#[allow(missing_docs)]
pub enum ParamContainer<'a> {
    Request(&'a Method, &'a Request),
    Response(&'a Method, &'a Response),
    Representation(&'a RepresentationDef),
}

/// Convert wadl names (with dashes) to camel-case Rust names
pub fn camel_case_name(name: &str) -> String {
    let mut it = name.chars().peekable();
    let mut result = String::new();
    // Uppercase the first letter
    if let Some(c) = it.next() {
        result.push_str(&c.to_uppercase().collect::<String>());
    }
    while it.peek().is_some() {
        let c = it.next().unwrap();
        if c == '_' || c == '-' {
            if let Some(next) = it.next() {
                result.push_str(&next.to_uppercase().collect::<String>());
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Convert wadl names (with dashes) to snake-case Rust names
pub fn snake_case_name(name: &str) -> String {
    let mut name = name.to_string();
    name = name.replace('-', "_");
    let mut result = String::new();
    let mut prev_upper = false;

    for c in name.chars() {
        if c.is_uppercase() {
            if !result.is_empty() && !prev_upper && !result.ends_with('_') {
                result.push('_');
            }
            result.push_str(&c.to_lowercase().to_string());
            prev_upper = true;
        } else {
            result.push(c);
            prev_upper = false;
        }
    }
    result
}

fn strip_code_examples(input: String) -> String {
    let mut in_example = false;
    input
        .lines()
        .filter(|line| {
            if !in_example && (line.starts_with("```python") || *line == "```") {
                in_example = true;
                false
            } else if line.starts_with("```") {
                in_example = false;
                false
            } else {
                !in_example
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Format the given `Doc` object into a string.
///
/// # Arguments
/// * `input` - The `Doc` object to format.
/// * `config` - The configuration to use.
///
/// # Returns
/// The formatted string.
fn format_doc(input: &Doc, config: &Config) -> String {
    match input.xmlns.as_ref().map(|x| x.as_str()) {
        Some("http://www.w3.org/1999/xhtml") => {
            let mut text = html2md::parse_html(&input.content);
            if config.strip_code_examples {
                text = strip_code_examples(text);
            }
            text.lines().collect::<Vec<_>>().join("\n")
        }
        Some(xmlns) => {
            log::warn!("Unknown xmlns: {}", xmlns);
            input.content.lines().collect::<Vec<_>>().join("\n")
        }
        None => input.content.lines().collect::<Vec<_>>().join("\n"),
    }
}

/// Generate a docstring from the given `Doc` object.
///
/// # Arguments
/// * `input` - The `Doc` object to generate the docstring from.
/// * `indent` - The indentation level to use.
/// * `config` - The configuration to use.
///
/// # Returns
/// A vector of strings, each representing a line of the docstring.
pub fn generate_doc(input: &Doc, indent: usize, config: &Config) -> Vec<String> {
    let mut lines: Vec<String> = vec![];

    if let Some(title) = input.title.as_ref() {
        lines.extend(vec![format!("/// # {}\n", title), "///\n".to_string()]);
    }

    let mut text = format_doc(input, config);

    if let Some(reformat_docstring) = config.reformat_docstring.as_ref() {
        text = reformat_docstring(&text);
    }

    lines.extend(
        text.lines()
            .map(|line| format!("///{}{}\n", if line.is_empty() { "" } else { " " }, line)),
    );
    lines
        .into_iter()
        .map(|line| format!("{:indent$}{}", "", line, indent = indent * 4))
        .collect()
}

fn generate_resource_type_ref_accessors(
    field_name: &str,
    input: &ResourceTypeRef,
    param: &Param,
    config: &Config,
) -> Vec<String> {
    let mut lines = vec![];
    if let Some(id) = input.id() {
        let deprecated = config
            .deprecated_param
            .as_ref()
            .map(|x| x(param))
            .unwrap_or(false);
        if let Some(doc) = param.doc.as_ref() {
            lines.extend(generate_doc(doc, 1, config));
        } else {
            // Generate default getter documentation
            lines.push(format!("    /// Get the {} value.\n", param.name));
        }
        let field_type = camel_case_name(id);
        let mut ret_type = field_type.to_string();
        let map_fn = if let Some((map_type, map_fn)) = config
            .map_type_for_accessor
            .as_ref()
            .and_then(|x| x(field_type.as_str()))
        {
            ret_type = map_type;
            Some(map_fn)
        } else {
            None
        };
        if config.nillable(param) {
            ret_type = format!("Option<{}>", ret_type);
        }
        let accessor_name = if let Some(rename_fn) = config.param_accessor_rename.as_ref() {
            rename_fn(param.name.as_str(), ret_type.as_str())
        } else {
            None
        }
        .unwrap_or_else(|| field_name.to_string());

        let visibility = config
            .accessor_visibility
            .as_ref()
            .and_then(|x| x(accessor_name.as_str(), field_type.as_str()))
            .unwrap_or_else(|| "pub".to_string());
        if deprecated {
            lines.push("    #[deprecated]".to_string());
        }
        lines.push(format!(
            "    {}fn {}(&self) -> {} {{\n",
            if visibility.is_empty() {
                "".to_string()
            } else {
                format!("{} ", visibility)
            },
            accessor_name,
            ret_type
        ));
        if !config.nillable(param) {
            if let Some(map_fn) = map_fn {
                lines.push(format!(
                    "        {}({}(self.{}.clone())\n",
                    map_fn, field_type, field_name
                ));
            } else {
                lines.push(format!(
                    "        {}(self.{}.clone())\n",
                    field_type, field_name
                ));
            }
        } else {
            lines.push(format!(
                "        self.{}.as_ref().map(|x| {}(x.clone())){}\n",
                field_name,
                field_type,
                if let Some(map_fn) = map_fn {
                    format!(".map({})", map_fn)
                } else {
                    "".to_string()
                }
            ));
        }
        lines.push("    }\n".to_string());
        lines.push("\n".to_string());

        if deprecated {
            lines.push("    #[deprecated]".to_string());
        }

        // Add setter documentation
        lines.push(format!("    /// Set the {} value.\n", param.name));

        lines.push(format!(
            "    {}fn set_{}(&mut self, value: {}) {{\n",
            if visibility.is_empty() {
                "".to_string()
            } else {
                format!("{} ", visibility)
            },
            accessor_name,
            ret_type
        ));

        if !config.nillable(param) {
            lines.push(format!(
                "        self.{} = value.url().clone();\n",
                field_name
            ));
        } else {
            lines.push(format!(
                "        self.{} = value.map(|x| x.url().clone());\n",
                field_name
            ));
        }
        lines.push("    }\n".to_string());

        if let Some(extend_accessor) = config.extend_accessor.as_ref() {
            lines.extend(extend_accessor(
                param,
                accessor_name.as_str(),
                ret_type.as_str(),
                config,
            ));
        }
    }
    lines
}

fn generate_representation(
    input: &RepresentationDef,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> Vec<String> {
    let mut lines = vec![];
    if input.media_type == Some(mime::APPLICATION_JSON) {
        lines.extend(generate_representation_struct_json(
            input,
            config,
            options_names,
        ));
    } else {
        panic!("Unknown media type: {:?}", input.media_type);
    }

    let name = input.id.as_ref().unwrap().as_str();
    let name = camel_case_name(name);

    lines.push(format!("impl {} {{\n", name));

    for param in &input.params {
        // Check if this param was filtered out
        if let Some(filter) = config.filter_param.as_ref() {
            if !filter(param) {
                continue;
            }
        }

        let field_name = snake_case_name(param.name.as_str());
        // We expect to support multiple types here in the future
        for link in &param.links {
            if let Some(r) = link.resource_type.as_ref() {
                lines.extend(generate_resource_type_ref_accessors(
                    &field_name,
                    r,
                    param,
                    config,
                ));
            }
        }
    }

    lines.push("}\n".to_string());
    lines.push("\n".to_string());

    if let Some(generate) = config.generate_representation_traits.as_ref() {
        lines.extend(generate(input, name.as_str(), input, config).unwrap_or(vec![]));
    }

    lines
}

/// Generate the Rust type for a representation
fn resource_type_rust_type(r: &ResourceTypeRef) -> String {
    if let Some(id) = r.id() {
        camel_case_name(id)
    } else {
        "url::Url".to_string()
    }
}

fn simple_type_rust_type(
    container: &ParamContainer,
    type_name: &str,
    param: &Param,
    config: &Config,
) -> (String, Vec<String>) {
    let tn = if let Some(override_name) = config.override_type_name.as_ref() {
        override_name(container, type_name, param.name.as_str(), config)
    } else {
        None
    };

    if let Some(tn) = tn {
        return (tn, vec![]);
    }

    match type_name.split_once(':').map_or(type_name, |(_, n)| n) {
        "date" => ("chrono::NaiveDate".to_string(), vec![]),
        "dateTime" => ("chrono::DateTime<chrono::Utc>".to_string(), vec![]),
        "time" => ("(chrono::Time".to_string(), vec![]),
        "int" => ("i32".to_string(), vec![]),
        "string" => ("String".to_string(), vec![]),
        "binary" => ("Vec<u8>".to_string(), vec![]),
        "boolean" => ("bool".to_string(), vec![]),
        u => panic!("Unknown type: {}", u),
    }
}

fn param_rust_type(
    container: &ParamContainer,
    param: &Param,
    config: &Config,
    resource_type_rust_type: impl Fn(&ResourceTypeRef) -> String,
    options_names: &HashMap<Options, String>,
) -> (String, Vec<String>) {
    let (mut param_type, annotations) = if !param.links.is_empty() {
        if let Some(rt) = param.links[0].resource_type.as_ref() {
            let name = resource_type_rust_type(rt);

            if let Some(override_type_name) = config
                .override_type_name
                .as_ref()
                .and_then(|x| x(container, name.as_str(), param.name.as_str(), config))
            {
                (override_type_name, vec![])
            } else {
                (name, vec![])
            }
        } else {
            ("url::Url".to_string(), vec![])
        }
    } else if let Some(os) = param.options.as_ref() {
        let options_name = options_names.get(os).unwrap_or_else(|| {
            panic!("Unknown options {:?} for {}", os, param.name);
        });
        (options_name.clone(), vec![])
    } else {
        simple_type_rust_type(container, param.r#type.as_str(), param, config)
    };

    if param.repeating {
        param_type = format!("Vec<{}>", param_type);
    }

    if config.nillable(param) {
        param_type = format!("Option<{}>", param_type);
    }

    (param_type, annotations)
}

fn readonly_rust_type(name: &str) -> String {
    if name.starts_with("Option<") && name.ends_with('>') {
        return format!(
            "Option<{}>",
            readonly_rust_type(name[7..name.len() - 1].trim())
        );
    }
    match name {
        "String" => "&str".to_string(),
        x if x.starts_with("Vec<") && x.ends_with('>') => {
            format!("&[{}]", x[4..x.len() - 1].trim())
        }
        x if x.starts_with('*') => x[1..].to_string(),
        x => format!("&{}", x),
    }
}

fn representation_rust_type(r: &RepresentationRef) -> String {
    if let Some(id) = r.id() {
        camel_case_name(id)
    } else {
        "serde_json::Value".to_string()
    }
}

fn escape_rust_reserved(name: &str) -> &str {
    match name {
        "type" => "r#type",
        "match" => "r#match",
        "move" => "r#move",
        "use" => "r#use",
        "loop" => "r#loop",
        "continue" => "r#continue",
        "break" => "r#break",
        "fn" => "r#fn",
        "struct" => "r#struct",
        "enum" => "r#enum",
        "trait" => "r#trait",
        "impl" => "r#impl",
        "pub" => "r#pub",
        "as" => "r#as",
        "const" => "r#const",
        "let" => "r#let",
        name => name,
    }
}

fn generate_representation_struct_json(
    input: &RepresentationDef,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> Vec<String> {
    let mut lines: Vec<String> = vec![];
    let name = input.id.as_ref().unwrap().as_str();
    let name = camel_case_name(name);

    let container = ParamContainer::Representation(input);

    for doc in &input.docs {
        lines.extend(generate_doc(doc, 0, config));
    }

    if input.docs.is_empty() {
        lines.push(format!(
            "/// Representation of the `{}` resource\n",
            input.id.as_ref().unwrap()
        ));
    }

    let derive_default = input.params.iter().all(|x| config.nillable(x));

    lines.push(
        "#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]\n".to_string(),
    );

    let visibility = config
        .representation_visibility
        .as_ref()
        .and_then(|x| x(name.as_str()))
        .unwrap_or_else(|| "pub".to_string());

    lines.push(format!(
        "{}struct {} {{\n",
        if visibility.is_empty() {
            "".to_string()
        } else {
            format!("{} ", visibility)
        },
        name
    ));

    for param in &input.params {
        // Check if we should filter this param
        if let Some(filter) = config.filter_param.as_ref() {
            if !filter(param) {
                continue;
            }
        }

        let param_name = snake_case_name(param.name.as_str());

        let param_name = escape_rust_reserved(param_name.as_str());

        let (param_type, annotations) = param_rust_type(
            &container,
            param,
            config,
            |_x| "url::Url".to_string(),
            options_names,
        );

        // We provide accessors for resource types
        let is_pub = true;

        lines.push(format!("    // was: {}\n", param.r#type));
        if let Some(doc) = param.doc.as_ref() {
            lines.extend(generate_doc(doc, 1, config));
        }

        for ann in annotations {
            lines.push(format!("    {}\n", ann));
        }
        lines.push(format!(
            "    {}{}: {},\n",
            if is_pub { "pub " } else { "" },
            param_name,
            param_type
        ));
        lines.push("\n".to_string());
    }

    lines.push("}\n".to_string());

    if derive_default {
        lines.push(format!("impl Default for {} {{\n", name));
        lines.push("    fn default() -> Self {\n".to_string());
        lines.push("        Self {\n".to_string());
        for param in &input.params {
            // Check if this param was filtered out
            if let Some(filter) = config.filter_param.as_ref() {
                if !filter(param) {
                    continue;
                }
            }

            let param_name = snake_case_name(param.name.as_str());
            let param_name = escape_rust_reserved(param_name.as_str());

            lines.push(format!("            {}: Default::default(),\n", param_name));
        }

        lines.push("        }\n".to_string());
        lines.push("    }\n".to_string());
        lines.push("}\n".to_string());
        lines.push("\n".to_string());
    }

    lines.push("\n".to_string());

    lines
}

fn supported_representation_def(d: &RepresentationDef) -> bool {
    // Support text/plain responses with plain-style params
    if let Some(media_type) = &d.media_type {
        if media_type.essence_str() == "text/plain" {
            // Check if it has plain-style params (typical for text/plain responses)
            return d.params.iter().any(|p| p.style == ParamStyle::Plain);
        }
    }
    false
}

/// Generate the Rust type for a representation
///
/// # Arguments
/// * `input` - The representation to generate the Rust type for
/// * `name` - The name of the representation
///
/// # Returns
///
/// The Rust type for the representation
fn rust_type_for_response(
    method: &Method,
    input: &Response,
    name: &str,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> String {
    let container = ParamContainer::Response(method, input);
    let representations = input
        .representations
        .iter()
        .filter(|r| match r {
            Representation::Definition(ref d) => supported_representation_def(d),
            _ => true,
        })
        .collect::<Vec<_>>();
    if representations.len() == 1 {
        // Allow header params for supported representation definitions (like text/plain)
        if let Representation::Definition(d) = representations[0] {
            if !supported_representation_def(d) {
                // Non-supported representations shouldn't have header params
                assert!(input.params.is_empty());
            }
        } else {
            assert!(input.params.is_empty());
        }
        match representations[0] {
            Representation::Reference(ref r) => {
                let id = r.id().unwrap().to_string();
                camel_case_name(id.as_str())
            }
            Representation::Definition(ref d) => {
                // Handle supported representation definitions (like text/plain)
                if supported_representation_def(d) {
                    // Check if there are also header-based return values
                    let mut ret = Vec::new();
                    for param in &input.params {
                        let (param_type, _annotations) = param_rust_type(
                            &container,
                            param,
                            config,
                            resource_type_rust_type,
                            options_names,
                        );
                        ret.push(param_type);
                    }

                    // Add the String body as the first element (for text/plain, etc.)
                    ret.insert(0, "String".to_string());

                    if ret.len() == 1 {
                        ret.into_iter().next().unwrap()
                    } else {
                        format!("({})", ret.join(", "))
                    }
                } else {
                    assert!(d.params.iter().all(|p| p.style == ParamStyle::Header));

                    let mut ret = Vec::new();
                    for param in &input.params {
                        let (param_type, _annotations) = param_rust_type(
                            &container,
                            param,
                            config,
                            resource_type_rust_type,
                            options_names,
                        );
                        ret.push(param_type);
                    }
                    if ret.len() == 1 {
                        ret.into_iter().next().unwrap()
                    } else {
                        format!("({})", ret.join(", "))
                    }
                }
            }
        }
    } else if representations.is_empty() {
        let mut ret = Vec::new();
        for param in &input.params {
            let (param_type, _annotations) = param_rust_type(
                &container,
                param,
                config,
                resource_type_rust_type,
                options_names,
            );
            ret.push(param_type);
        }
        if ret.len() == 1 {
            ret.into_iter().next().unwrap()
        } else {
            format!("({})", ret.join(", "))
        }
    } else {
        todo!(
            "multiple representations for response: {}: {:?}",
            name,
            representations
        );
    }
}

fn format_arg_doc(name: &str, doc: Option<&crate::ast::Doc>, config: &Config) -> Vec<String> {
    let mut lines = Vec::new();
    if let Some(doc) = doc.as_ref() {
        let doc = format_doc(doc, config);
        let mut doc_lines = doc
            .trim_start_matches('\n')
            .split('\n')
            .collect::<Vec<_>>()
            .into_iter();
        lines.push(format!(
            "    /// * `{}`: {}\n",
            name,
            doc_lines.next().unwrap().trim_end_matches(' ')
        ));
        for doc_line in doc_lines {
            if doc_line.is_empty() {
                lines.push("    ///\n".to_string());
            } else {
                lines.push(format!("    ///     {}\n", doc_line.trim_end_matches(' ')));
            }
        }
    } else {
        lines.push(format!("    /// * `{}`\n", name));
    }

    lines
}

fn apply_map_fn(map_fn: Option<&str>, ret: &str, nillable: bool) -> String {
    if let Some(map_fn) = map_fn {
        if !nillable {
            if map_fn.starts_with('|') {
                format!("({})({})", map_fn, ret)
            } else {
                format!("{}({})", map_fn, ret)
            }
        } else {
            format!("{}.map({})", ret, map_fn)
        }
    } else {
        ret.to_string()
    }
}

fn serialize_representation_def(
    def: &RepresentationDef,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> Vec<String> {
    let mut lines = vec![];
    fn process_param(
        param: &Param,
        container: &ParamContainer,
        config: &Config,
        cb: impl Fn(&str, &str, &str) -> String,
        options_names: &HashMap<Options, String>,
    ) -> Vec<String> {
        let param_name = escape_rust_reserved(param.name.as_str());

        let (param_type, _annotations) = param_rust_type(
            container,
            param,
            config,
            resource_type_rust_type,
            options_names,
        );
        let param_type = readonly_rust_type(&param_type);
        let mut indent = 4;
        let mut lines = vec![];

        let needs_iter = param_type.starts_with("Vec<") || param_type.starts_with("Option<Vec<");
        let is_optional = param_type.starts_with("Option<");

        if is_optional && param.fixed.is_none() {
            lines.push(format!(
                "{:indent$}if let Some({}) = {} {{\n",
                "",
                param_name,
                param_name,
                indent = indent
            ));
            indent += 4;
        }
        if needs_iter && param.fixed.is_none() {
            lines.push(format!(
                "{:indent$}for {} in {} {{\n",
                "", param_name, param_name
            ));
            indent += 4;
        }

        let value = if let Some(fixed) = param.fixed.as_ref() {
            format!("\"{}\"", fixed)
        } else if param.links.is_empty() {
            format!("&{}.to_string()", param_name)
        } else {
            format!("&{}.url().to_string()", param_name)
        };

        lines.push(format!(
            "{:indent$}{}\n",
            "",
            cb(param_type.as_str(), param.name.as_str(), value.as_str()),
            indent = indent
        ));

        if needs_iter && param.fixed.is_none() {
            indent -= 4;
            lines.push(format!("{:indent$}}}\n", "", indent = indent));
        }

        if is_optional && param.fixed.is_none() {
            indent -= 4;
            lines.push(format!("{:indent$}}}\n", "", indent = indent));
        }

        lines
    }

    let container = ParamContainer::Representation(def);

    match def.media_type.as_ref().map(|s| s.to_string()).as_deref() {
        Some("multipart/form-data") => {
            let mp_mod = if !config.r#async {
                "reqwest::blocking"
            } else {
                "reqwest"
            };
            lines.push(format!(
                "let mut form = {}::multipart::Form::new();\n",
                mp_mod
            ));
            for param in def.params.iter() {
                lines.extend(process_param(
                    param,
                    &container,
                    config,
                    |param_type, name, value| {
                        format!(
                            "form = form.part(\"{}\", {});",
                            name,
                            if let Some(convert_to_multipart) = config
                                .convert_to_multipart
                                .as_ref()
                                .and_then(|x| x(param_type, value))
                            {
                                convert_to_multipart
                            } else {
                                format!(
                                    "{}::multipart::Part::text({})",
                                    mp_mod,
                                    value.strip_prefix('&').unwrap_or(value)
                                )
                            }
                        )
                    },
                    options_names,
                ));
            }
            lines.push("req = req.multipart(form);\n".to_string());
        }
        Some("application/x-www-form-urlencoded") => {
            lines.push(
                "let mut serializer = form_urlencoded::Serializer::new(String::new());\n"
                    .to_string(),
            );
            for param in def.params.iter() {
                lines.extend(process_param(param, &container, config, |r#type, name, value| {
                    if r#type.contains("[") {
                        format!("for value in {} {{ serializer.append_pair(\"{}\", &value.to_string()); }}", value.strip_prefix("&").unwrap().strip_suffix(".to_string()").unwrap(), name)
                    } else {
                        format!("serializer.append_pair(\"{}\", {});", name, value)
                    }
                }, options_names));
            }
            lines.push("req = req.header(reqwest::header::CONTENT_TYPE, \"application/x-www-form-urlencoded\");\n".to_string());
            lines.push("req = req.body(serializer.finish());\n".to_string());
        }
        Some("application/json") => {
            lines.push("let mut o = serde_json::Value::Object::new();".to_string());

            for param in def.params.iter() {
                lines.extend(process_param(
                    param,
                    &container,
                    config,
                    |_type, name, value| format!("o.insert(\"{}\", {});", name, value),
                    options_names,
                ));
            }

            lines.push("req = req.json(&o);\n".to_string());
        }
        o => {
            panic!("unsupported media type {:?}", o);
        }
    }
    lines
}

/// Generate code for a WADL method (HTTP GET, POST, PUT, DELETE, etc.).
///
/// This function generates Rust methods that correspond to HTTP operations defined
/// in the WADL specification. It creates both representation-based methods and
/// WADL-specific methods when applicable.
///
/// # Arguments
/// * `input` - The WADL method definition containing HTTP method details
/// * `parent_id` - The ID of the parent resource type
/// * `config` - Configuration options for code generation
/// * `options_names` - Mapping of option sets to their generated enum names
///
/// # Returns
/// A vector of strings containing the generated Rust code lines
fn generate_method(
    input: &Method,
    parent_id: &str,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> Vec<String> {
    let mut lines = generate_method_representation(input, parent_id, config, options_names);

    for response in input.responses.iter() {
        if response.representations.iter().any(|r| {
            r.media_type().as_ref().map(|s| s.to_string()).as_deref() == Some(crate::WADL_MIME_TYPE)
        }) {
            lines.extend(generate_method_wadl(input, parent_id, config))
        }
    }

    lines
}

/// Generate Rust code for a WADL method that retrieves WADL descriptions.
///
/// This function creates methods that fetch WADL representations from endpoints.
/// These methods are generated when a resource supports returning its own WADL
/// description (typically for dynamic API discovery). The generated method will:
/// - Build a request with appropriate WADL accept headers
/// - Parse the returned WADL XML into AST structures
/// - Return the corresponding resource definition
///
/// # Arguments
/// * `input` - The WADL method definition
/// * `parent_id` - The ID of the parent resource type (used for method naming)
/// * `config` - Configuration for code generation (async/sync mode)
///
/// # Returns
/// A vector of strings containing the generated Rust method for WADL retrieval
fn generate_method_wadl(input: &Method, parent_id: &str, config: &Config) -> Vec<String> {
    let mut lines = vec![];

    let name = input.id.as_str();
    let name = name
        .strip_prefix(format!("{}-", parent_id).as_str())
        .unwrap_or(name);
    let name = snake_case_name(name);

    let async_prefix = if config.r#async { "async " } else { "" };

    // Add documentation for WADL method
    lines.push("    /// Retrieve the WADL description for this resource.\n".to_string());
    lines.push("    ///\n".to_string());
    lines.push("    /// This method fetches the WADL (Web Application Description Language) specification\n".to_string());
    lines.push(
        "    /// for the current resource, allowing for runtime API discovery.\n".to_string(),
    );
    lines.push("    ///\n".to_string());
    lines.push("    /// # Returns\n".to_string());
    lines.push("    /// Returns the `wadl::ast::Resource` definition on success, or an error if the request fails.\n".to_string());

    lines.push(format!("    pub {}fn {}_wadl<'a>(&self, client: &'a dyn {}) -> std::result::Result<wadl::ast::Resource, wadl::Error> {{\n", async_prefix, name, config.client_trait_name()));

    lines.push("        let mut url_ = self.url().clone();\n".to_string());
    for param in input
        .request
        .params
        .iter()
        .filter(|p| p.style == ParamStyle::Query)
    {
        if let Some(fixed) = param.fixed.as_ref() {
            assert!(!param.repeating);
            lines.push(format!(
                "        url_.query_pairs_mut().append_pair(\"{}\", \"{}\");\n",
                param.name, fixed
            ));
        }
    }

    lines.push("\n".to_string());

    let method = input.name.as_str();
    if config.r#async {
        lines.push(format!(
            "        let mut req = client.request(reqwest::Method::{}, url_).await;\n",
            method
        ));
    } else {
        lines.push(format!(
            "        let mut req = client.request(reqwest::Method::{}, url_);\n",
            method
        ));
    }

    lines.push(format!(
        "        req = req.header(reqwest::header::ACCEPT, \"{}\");\n",
        crate::WADL_MIME_TYPE
    ));

    lines.push("\n".to_string());

    if config.r#async {
        lines.push("        let wadl: wadl::ast::Application = req.send().await?.error_for_status()?.text().await?.parse()?;\n".to_string());
    } else {
        lines.push("        let wadl: wadl::ast::Application = req.send()?.error_for_status()?.text()?.parse()?;\n".to_string());
    }
    lines.push(
        "        let resource = wadl.get_resource_by_href(self.url()).unwrap();\n".to_string(),
    );

    lines.push("        Ok(resource.clone())\n".to_string());

    lines.push("    }\n".to_string());

    lines.push("\n".to_string());

    lines
}

static DEFAULT_RESPONSE: Response = Response {
    docs: vec![],
    params: vec![],
    status: Some(200),
    representations: vec![],
};

/// Generate Rust code for a WADL method that handles representations.
///
/// This function creates the actual implementation of HTTP methods (GET, POST, PUT, DELETE, etc.)
/// that handle request/response representations. It generates type-safe Rust methods that:
/// - Accept appropriate parameters based on the WADL definition
/// - Build HTTP requests with proper headers and query parameters
/// - Serialize request bodies according to the representation type
/// - Deserialize responses into strongly-typed Rust structures
///
/// # Arguments
/// * `input` - The WADL method definition containing request/response specifications
/// * `parent_id` - The ID of the parent resource type (used for method naming)
/// * `config` - Configuration for code generation (async/sync, visibility, etc.)
/// * `options_names` - Mapping of option sets to their generated enum names
///
/// # Returns
/// A vector of strings containing the generated Rust method implementation
fn generate_method_representation(
    input: &Method,
    parent_id: &str,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> Vec<String> {
    let mut lines = vec![];

    let name = input.id.as_str();
    let name = name
        .strip_prefix(format!("{}-", parent_id).as_str())
        .unwrap_or(name);
    let name = snake_case_name(name);

    let (ret_type, map_fn) = if input.responses.is_empty() {
        ("()".to_string(), None)
    } else {
        // Find the success response(s) - those with status 2xx or no status specified
        let mut success_responses: Vec<&Response> = input
            .responses
            .iter()
            .filter(|r| r.status.is_none() || (200..300).contains(&r.status.unwrap()))
            .collect();

        if success_responses.is_empty() {
            success_responses.push(&DEFAULT_RESPONSE);
        }

        assert_eq!(
            1,
            success_responses.len(),
            "expected 1 success response for {}, found {}",
            name,
            success_responses.len()
        );

        let mut return_type = rust_type_for_response(
            input,
            success_responses[0],
            input.id.as_str(),
            config,
            options_names,
        );
        let map_fn = if let Some((map_type, map_fn)) = config
            .map_type_for_response
            .as_ref()
            .and_then(|r| r(&name, &return_type, config))
        {
            return_type = map_type;
            Some(map_fn)
        } else {
            None
        };
        (return_type, map_fn)
    };

    let visibility = config
        .method_visibility
        .as_ref()
        .and_then(|x| x(&name, &ret_type))
        .unwrap_or("pub".to_string());

    let mut line = format!(
        "    {}{}fn {}<'a>(&self, client: &'a dyn {}",
        if visibility.is_empty() {
            "".to_string()
        } else {
            format!("{} ", visibility)
        },
        if config.r#async { "async " } else { "" },
        name,
        config.client_trait_name()
    );

    let mut params = input.request.params.iter().collect::<Vec<_>>();

    params.extend(
        input
            .request
            .representations
            .iter()
            .filter_map(|r| match r {
                Representation::Definition(d) => Some(&d.params),
                Representation::Reference(_) => None,
            })
            .flatten(),
    );

    // Generate documentation for the method
    if input.docs.is_empty() {
        // Generate a default docstring based on the HTTP method and resource
        let method_verb = match input.name.as_str() {
            "GET" => "Retrieve",
            "POST" => "Create",
            "PUT" => "Update",
            "DELETE" => "Delete",
            "PATCH" => "Partially update",
            "HEAD" => "Get headers for",
            _ => "Perform operation on",
        };
        lines.push(format!("    /// {} the resource.\n", method_verb));
        lines.push("    ///\n".to_string());
    } else {
        for doc in &input.docs {
            lines.extend(generate_doc(doc, 1, config));
        }
    }

    if !params.is_empty() {
        lines.push("    /// # Arguments\n".to_string());
    }

    for representation in &input.request.representations {
        match representation {
            Representation::Definition(_) => {}
            Representation::Reference(r) => {
                let id = camel_case_name(r.id().unwrap());
                line.push_str(format!(", representation: &{}", id).as_str());
            }
        }
    }

    let container = ParamContainer::Request(input, &input.request);
    for param in &params {
        if param.fixed.is_some() {
            continue;
        }
        let (param_type, _annotations) = param_rust_type(
            &container,
            param,
            config,
            resource_type_rust_type,
            options_names,
        );
        let param_type = readonly_rust_type(param_type.as_str());
        let param_name = param.name.clone();
        let param_name = escape_rust_reserved(param_name.as_str());

        line.push_str(format!(", {}: {}", param_name, param_type).as_str());

        lines.extend(format_arg_doc(param_name, param.doc.as_ref(), config));
    }

    // Add returns documentation
    if ret_type != "()" {
        lines.push("    ///\n".to_string());
        lines.push("    /// # Returns\n".to_string());
        lines.push(format!(
            "    /// Returns `{}` on success, or an error if the request fails.\n",
            ret_type
        ));
    }

    line.push_str(") -> std::result::Result<");
    line.push_str(ret_type.as_str());

    line.push_str(", wadl::Error> {\n");
    lines.push(line);

    assert!(input
        .request
        .params
        .iter()
        .all(|p| [ParamStyle::Header, ParamStyle::Query].contains(&p.style)));

    lines.push("        let mut url_ = self.url().clone();\n".to_string());
    for param in input
        .request
        .params
        .iter()
        .filter(|p| p.style == ParamStyle::Query)
    {
        if let Some(fixed) = param.fixed.as_ref() {
            assert!(!param.repeating);
            lines.push(format!(
                "        url_.query_pairs_mut().append_pair(\"{}\", \"{}\");\n",
                param.name, fixed
            ));
        } else {
            let param_name = param.name.as_str();
            let param_name = snake_case_name(param_name);
            let param_name = escape_rust_reserved(param_name.as_str());
            let (param_type, _annotations) = param_rust_type(
                &container,
                param,
                config,
                resource_type_rust_type,
                options_names,
            );
            let value = if !param.links.is_empty() {
                format!("&{}.url().to_string()", param_name)
            } else {
                format!("&{}.to_string()", param_name)
            };

            let mut indent = 0;

            let needs_iter = param.repeating
                || param_type.starts_with("Vec<")
                || param_type.starts_with("Option<Vec<");

            if param_type.starts_with("Option<") {
                lines.push(format!(
                    "        if let Some({}) = {} {{\n",
                    param_name, param_name
                ));
                indent += 4;
            }
            if needs_iter {
                lines.push(format!(
                    "{:indent$}        for {} in {} {{\n",
                    "", param_name, param_name
                ));
                indent += 4;
            }
            lines.push(format!(
                "{:indent$}        url_.query_pairs_mut().append_pair(\"{}\", {});\n",
                "",
                param.name,
                value,
                indent = indent
            ));
            while indent > 0 {
                lines.push(format!("{:indent$}    }}\n", "", indent = indent));
                indent -= 4;
            }
        }
    }

    lines.push("\n".to_string());

    let method = input.name.as_str();
    if config.r#async {
        lines.push(format!(
            "        let mut req = client.request(reqwest::Method::{}, url_).await;\n",
            method
        ));
    } else {
        lines.push(format!(
            "        let mut req = client.request(reqwest::Method::{}, url_);\n",
            method
        ));
    }

    for representation in &input.request.representations {
        match representation {
            Representation::Definition(ref d) => {
                lines.extend(indent(
                    2,
                    serialize_representation_def(d, config, options_names).into_iter(),
                ));
            }
            Representation::Reference(_r) => {
                // TODO(jelmer): Support non-JSON representations
                lines.push("        req = req.json(&representation);\n".to_string());
            }
        };
    }

    let response_mime_types = input
        .responses
        .iter()
        .flat_map(|x| {
            x.representations.iter().filter_map(|x| match x {
                Representation::Definition(ref d) if supported_representation_def(d) => {
                    d.media_type.clone()
                }
                Representation::Reference(_) => {
                    // TODO: Look up media type of reference
                    Some(mime::APPLICATION_JSON)
                }
                _ => None,
            })
        })
        .collect::<Vec<_>>();

    if !response_mime_types.is_empty() {
        lines.push(format!(
            "        req = req.header(reqwest::header::ACCEPT, \"{}\");\n",
            response_mime_types
                .into_iter()
                .map(|x| x.to_string())
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }

    for param in params.iter().filter(|p| p.style == ParamStyle::Header) {
        let value = if let Some(fixed) = param.fixed.as_ref() {
            format!("\"{}\"", fixed)
        } else {
            let param_name = param.name.as_str();
            let param_name = snake_case_name(param_name);
            let param_name = escape_rust_reserved(param_name.as_str());

            format!("&{}.to_string()", param_name)
        };

        lines.push(format!(
            "        req = req.header(\"{}\", {});\n",
            param.name, value
        ));
    }

    lines.push("\n".to_string());
    if config.r#async {
        lines.push("        let resp = req.send().await?;\n".to_string());
    } else {
        lines.push("        let resp = req.send()?;\n".to_string());
    }

    lines.push("        match resp.status() {\n".to_string());

    let serialize_return_types = |return_types: Vec<(String, bool)>| {
        if return_types.is_empty() {
            "Ok(())".to_string()
        } else if return_types.len() == 1 {
            format!(
                "Ok({})",
                apply_map_fn(map_fn.as_deref(), &return_types[0].0, !return_types[0].1)
            )
        } else {
            let v = format!(
                "({})",
                return_types
                    .iter()
                    .map(|x| x.0.clone())
                    .collect::<Vec<_>>()
                    .join(", ")
            );
            format!("Ok({})", apply_map_fn(map_fn.as_deref(), &v, false))
        }
    };

    for response in input.responses.iter() {
        let mut return_types = vec![];

        for param in response.params.iter() {
            match &param.style {
                ParamStyle::Header => {
                    if !param.links.is_empty() {
                        let r = &param.links[0].resource_type.as_ref().unwrap();
                        if !config.nillable(param) {
                            return_types.push((
                                format!(
                                    "{}(resp.headers().get(\"{}\")?.to_str()?.parse().unwrap())",
                                    resource_type_rust_type(r),
                                    param.name
                                ),
                                true,
                            ));
                        } else {
                            return_types.push((format!(
                                "resp.headers().get(\"{}\").map(|x| {}(x.to_str().unwrap().parse().unwrap()))",
                                param.name,
                                resource_type_rust_type(r),
                            ), false));
                        }
                    } else {
                        todo!(
                            "header param type {:?} for {} in {:?}",
                            param.r#type,
                            param.name,
                            input.id
                        );
                    }
                }
                t => todo!("param style {:?}", t),
            }
        }

        // TODO(jelmer): match on media type
        if let Some(status) = response.status {
            lines.push(format!(
                "            s if s.as_u16() == reqwest::StatusCode::{} => {{\n",
                status
            ));
        } else {
            lines.push("            s if s.is_success() => {\n".to_string());
        }

        if !response.representations.is_empty() {
            lines.push("                let content_type: Option<mime::Mime> = resp.headers().get(reqwest::header::CONTENT_TYPE).map(|x| x.to_str().unwrap()).map(|x| x.parse().unwrap());\n".to_string());
            lines.push(
                "                match content_type.as_ref().map(|x| x.essence_str()) {\n"
                    .to_string(),
            );
            for representation in response.representations.iter() {
                let media_type = representation
                    .media_type()
                    .unwrap_or(&mime::APPLICATION_JSON);
                lines.push(format!(
                    "                    Some(\"{}\") => {{\n",
                    media_type
                ));
                let t = match representation {
                    Representation::Definition(d) => {
                        // Handle text/plain responses
                        if let Some(media_type) = &d.media_type {
                            if media_type.essence_str() == "text/plain"
                                && d.params.iter().any(|p| p.style == ParamStyle::Plain)
                            {
                                Some((
                                    format!(
                                        "resp.text(){}?",
                                        if config.r#async { ".await" } else { "" }
                                    ),
                                    true,
                                ))
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    }
                    Representation::Reference(r) => {
                        let rt = representation_rust_type(r);

                        Some((
                            format!(
                                "resp.json::<{}>(){}?",
                                rt,
                                if config.r#async { ".await" } else { "" }
                            ),
                            true,
                        ))
                    }
                };
                if let Some(t) = t {
                    let mut return_types = return_types.clone();
                    return_types.insert(0, t);
                    lines.push(format!(
                        "                             {}\n",
                        serialize_return_types(return_types)
                    ));
                } else {
                    lines.push("                        unimplemented!();\n".to_string());
                }
                lines.push("                        }\n".to_string());
            }
            lines.push(
                "                    _ => { Err(wadl::Error::UnhandledContentType(content_type)) }\n"
                    .to_string(),
            );
            lines.push("                }\n".to_string());
        } else {
            lines.push(format!(
                "                {}\n",
                serialize_return_types(return_types)
            ));
        }

        lines.push("            }\n".to_string());
    }
    if input.responses.is_empty() {
        lines.push("            s if s.is_success() => Ok(()),\n".to_string());
    }
    lines.push("            s => Err(wadl::Error::UnhandledStatus(s))\n".to_string());
    lines.push("        }\n".to_string());
    lines.push("    }\n".to_string());
    lines.push("\n".to_string());

    if let Some(extend_method) = config.extend_method.as_ref() {
        lines.extend(extend_method(parent_id, &name, &ret_type, config));
    }

    lines
}

fn generate_resource_type(
    input: &ResourceType,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> Vec<String> {
    let mut lines = vec![];

    for doc in &input.docs {
        lines.extend(generate_doc(doc, 0, config));
    }

    let name = input.id.as_str();
    let name = camel_case_name(name);

    let visibility = config
        .resource_type_visibility
        .as_ref()
        .and_then(|x| x(name.as_str()))
        .unwrap_or("pub".to_string());

    lines.push(format!(
        "{}struct {} (reqwest::Url);\n",
        if visibility.is_empty() {
            "".to_string()
        } else {
            format!("{} ", visibility)
        },
        name
    ));

    lines.push("\n".to_string());

    lines.push(format!("impl {} {{\n", name));

    for method in &input.methods {
        // Check if we should filter this method
        if let Some(filter) = config.filter_method.as_ref() {
            if !filter(method) {
                continue;
            }
        }

        lines.extend(generate_method(
            method,
            input.id.as_str(),
            config,
            options_names,
        ));
    }

    lines.push("}\n".to_string());
    lines.push("\n".to_string());
    lines.push(format!("impl wadl::Resource for {} {{\n", name));
    lines.push("    fn url(&self) -> &reqwest::Url {\n".to_string());
    lines.push("        &self.0\n".to_string());
    lines.push("    }\n".to_string());
    lines.push("}\n".to_string());
    lines.push("\n".to_string());
    lines
}

fn generate_resource(
    input: &Resource,
    base_url: Option<&Url>,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> Vec<String> {
    let mut lines = vec![];

    // Derive a name from the resource's id or path
    let name = if let Some(id) = &input.id {
        camel_case_name(id.as_str())
    } else if let Some(path) = &input.path {
        // Convert path to a valid Rust identifier
        let path = path.trim_start_matches('/');
        let path = path.trim_end_matches('/');
        let name = camel_case_name(path);
        if name.is_empty() {
            return lines; // Skip resources with empty path (just type references)
        }
        name
    } else {
        return lines; // Skip resources without id or path
    };

    for doc in &input.docs {
        lines.extend(generate_doc(doc, 0, config));
    }

    let visibility = config
        .resource_type_visibility
        .as_ref()
        .and_then(|x| x(name.as_str()))
        .unwrap_or("pub".to_string());

    lines.push(format!(
        "{}struct {} (reqwest::Url);\n",
        if visibility.is_empty() {
            "".to_string()
        } else {
            format!("{} ", visibility)
        },
        name
    ));

    lines.push("\n".to_string());

    lines.push(format!("impl {} {{\n", name));

    // Generate constructor
    if let Some(resource_url) = input.url(base_url) {
        lines.push(format!(
            "    pub fn new() -> Self {{\n        Self(reqwest::Url::parse(\"{}\").unwrap())\n    }}\n",
            resource_url
        ));
        lines.push("\n".to_string());

        for method in &input.methods {
            // Check if we should filter this method
            if let Some(filter) = config.filter_method.as_ref() {
                if !filter(method) {
                    continue;
                }
            }

            let parent_id = input.id.as_deref().unwrap_or(&name);
            lines.extend(generate_method(method, parent_id, config, options_names));
        }

        lines.push("}\n".to_string());
        lines.push("\n".to_string());
        lines.push(format!("impl wadl::Resource for {} {{\n", name));
        lines.push("    fn url(&self) -> &reqwest::Url {\n".to_string());
        lines.push("        &self.0\n".to_string());
        lines.push("    }\n".to_string());
        lines.push("}\n".to_string());
        lines.push("\n".to_string());

        // Generate code for subresources recursively
        for subresource in &input.subresources {
            lines.extend(generate_resource(
                subresource,
                Some(&resource_url),
                config,
                options_names,
            ));
        }
    }

    lines
}

fn generate_resources(
    resources: &Resources,
    config: &Config,
    options_names: &HashMap<Options, String>,
) -> Vec<String> {
    let mut lines = vec![];

    for resource in &resources.resources {
        lines.extend(generate_resource(
            resource,
            resources.base.as_ref(),
            config,
            options_names,
        ));
    }

    lines
}

#[derive(Default)]
#[allow(clippy::type_complexity)]
/// Configuration for code generation
pub struct Config {
    /// Whether to generate async code
    pub r#async: bool,

    /// Based on the listed type and name of a parameter, determine the rust type
    pub override_type_name:
        Option<Box<dyn Fn(&ParamContainer, &str, &str, &Config) -> Option<String>>>,

    /// Support renaming param accessor functions
    pub param_accessor_rename: Option<Box<dyn Fn(&str, &str) -> Option<String>>>,

    /// Whether to strip code examples from the docstrings
    ///
    /// This is useful if the code examples are not valid rust code.
    pub strip_code_examples: bool,

    /// Generate custom trait implementations for representations
    pub generate_representation_traits: Option<
        Box<dyn Fn(&RepresentationDef, &str, &RepresentationDef, &Config) -> Option<Vec<String>>>,
    >,

    /// Return the visibility of a representation
    pub representation_visibility: Option<Box<dyn Fn(&str) -> Option<String>>>,

    /// Return the visibility of a representation accessor
    pub accessor_visibility: Option<Box<dyn Fn(&str, &str) -> Option<String>>>,

    /// Return the visibility of a resource type
    pub resource_type_visibility: Option<Box<dyn Fn(&str) -> Option<String>>>,

    /// Map a method response type to a different type and a function to map the response
    pub map_type_for_response: Option<Box<dyn Fn(&str, &str, &Config) -> Option<(String, String)>>>,

    /// Map an accessor function name to a different type
    pub map_type_for_accessor: Option<Box<dyn Fn(&str) -> Option<(String, String)>>>,

    /// Extend the generated accessor
    pub extend_accessor: Option<Box<dyn Fn(&Param, &'_ str, &'_ str, &Config) -> Vec<String>>>,

    /// Extend the generated method
    pub extend_method: Option<Box<dyn Fn(&str, &str, &str, &Config) -> Vec<String>>>,

    /// Retrieve visibility for a method
    pub method_visibility: Option<Box<dyn Fn(&str, &str) -> Option<String>>>,

    /// Return whether a param is deprecated
    pub deprecated_param: Option<Box<dyn Fn(&Param) -> bool>>,

    /// Return the name for an enum representation a set of options
    ///
    /// The callback can be used to determine if the name is already taken.
    pub options_enum_name: Option<Box<dyn Fn(&Param, Box<dyn Fn(&str) -> bool>) -> String>>,

    /// Reformat a docstring; should already be in markdown
    pub reformat_docstring: Option<Box<dyn Fn(&str) -> String>>,

    /// Convert a string to a multipart Part, given a type name and value
    pub convert_to_multipart: Option<Box<dyn Fn(&str, &str) -> Option<String>>>,

    /// Check whether a parameter can be nil
    pub nillable_param: Option<Box<dyn Fn(&Param) -> bool>>,

    /// Filter resource types and representations by ID
    /// Return true to include the resource type/representation
    pub filter_by_id: Option<Box<dyn Fn(&str) -> bool>>,

    /// Filter representation params/fields
    /// Return true to include the field/accessor
    /// This is used to filter out fields that reference filtered-out types
    pub filter_param: Option<Box<dyn Fn(&Param) -> bool>>,

    /// Filter methods
    /// Return true to include the method
    /// This is used to filter out methods that reference filtered-out types in parameters
    pub filter_method: Option<Box<dyn Fn(&Method) -> bool>>,
}

impl Config {
    /// Return identifier of the wadl client
    pub fn client_trait_name(&self) -> &'static str {
        if self.r#async {
            "wadl::r#async::Client"
        } else {
            "wadl::blocking::Client"
        }
    }

    /// Check whether the parameter is can be nil
    pub fn nillable(&self, param: &Param) -> bool {
        if let Some(nillable_param) = self.nillable_param.as_ref() {
            nillable_param(param)
        } else {
            !param.required
        }
    }
}

fn enum_rust_value(option: &str) -> String {
    let name = camel_case_name(option.replace(' ', "-").as_str());

    // Now, strip all characters not allowed in rust identifiers
    let name = name
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '_')
        .collect::<String>();

    // If the identifier starts with a digit, prefix it with '_' to make it a valid identifier
    if name.chars().next().unwrap().is_numeric() {
        format!("_{}", name)
    } else {
        name
    }
}

fn generate_options(name: &str, options: &crate::ast::Options) -> Vec<String> {
    let mut lines = vec![];

    lines.push("#[derive(Debug, Clone, Copy, PartialEq, Eq, std::hash::Hash, serde::Serialize, serde::Deserialize)]\n".to_string());
    lines.push(format!("pub enum {} {{\n", name));

    let mut option_map = HashMap::new();

    for option in options.keys() {
        let rust_name = enum_rust_value(option);
        lines.push(format!("    #[serde(rename = \"{}\")]\n", option));
        lines.push(format!("    {},\n", rust_name));
        option_map.insert(option, rust_name);
    }
    lines.push("}\n".to_string());
    lines.push("\n".to_string());

    lines.push(format!("impl std::fmt::Display for {} {{\n", name));
    lines.push(
        "    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n".to_string(),
    );
    lines.push("        match self {\n".to_string());
    for (option, rust_name) in option_map {
        lines.push(format!(
            "            {}::{} => write!(f, \"{}\"),\n",
            name, rust_name, option
        ));
    }
    lines.push("        }\n".to_string());
    lines.push("    }\n".to_string());
    lines.push("}\n".to_string());
    lines
}

fn options_rust_enum_name(param: &Param, options: &HashMap<Options, String>) -> String {
    let mut name = camel_case_name(param.name.as_str());
    while options.values().any(|v| v == &name) {
        name = format!("{}_", name);
    }
    name
}

/// Generate code from a WADL application definition.
///
/// This function generates Rust code from a WADL application definition.
/// The generated code includes Rust types for the representations and
/// resource types defined in the WADL application, as well as methods
/// for interacting with the resources.
///
/// # Arguments
/// * `app` - The WADL application definition.
/// * `config` - Configuration for the code generation.
pub fn generate(app: &Application, config: &Config) -> String {
    let mut lines = vec![];

    let mut options = HashMap::new();

    for param in app.iter_all_params() {
        if let Some(os) = &param.options {
            if options.contains_key(os) {
                continue;
            }
            let name = if let Some(enum_name_fn) = config.options_enum_name.as_ref() {
                let cb_options = options.clone();
                let name = enum_name_fn(
                    param,
                    Box::new(move |name: &str| -> bool { cb_options.values().any(|v| v == name) }),
                );
                let taken = options
                    .iter()
                    .filter_map(|(k, v)| if v == &name { Some(k) } else { None })
                    .collect::<Vec<_>>();
                if !taken.is_empty() {
                    panic!(
                        "Enum name {} is already taken by {:?} ({:?})",
                        name, taken, options
                    );
                }
                name
            } else {
                options_rust_enum_name(param, &options)
            };
            let enum_lines = generate_options(name.as_str(), os);
            options.insert(os.clone(), name);
            lines.extend(enum_lines);
        }
    }

    for doc in &app.docs {
        lines.extend(generate_doc(doc, 0, config));
    }

    for representation in &app.representations {
        if let Some(filter) = config.filter_by_id.as_ref() {
            if let Some(id) = representation.id.as_ref() {
                if !filter(id) {
                    continue;
                }
            }
        }
        lines.extend(generate_representation(representation, config, &options));
    }

    for resource_type in &app.resource_types {
        if let Some(filter) = config.filter_by_id.as_ref() {
            if !filter(&resource_type.id) {
                continue;
            }
        }
        lines.extend(generate_resource_type(resource_type, config, &options));
    }

    for resources in &app.resources {
        lines.extend(generate_resources(resources, config, &options));
    }

    lines.concat()
}

fn indent(indent: usize, lines: impl Iterator<Item = String>) -> impl Iterator<Item = String> {
    lines.map(move |line| format!("{}{}", " ".repeat(indent * 4), line))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_camel_case_name() {
        assert_eq!(camel_case_name("foo-bar"), "FooBar");
        assert_eq!(camel_case_name("foo-bar-baz"), "FooBarBaz");
        assert_eq!(camel_case_name("foo-bar-baz-quux"), "FooBarBazQuux");
        assert_eq!(camel_case_name("_foo-bar"), "_fooBar");
        assert_eq!(camel_case_name("service-root-json"), "ServiceRootJson");
        assert_eq!(camel_case_name("get-some-URL"), "GetSomeURL");
    }

    #[test]
    fn test_generate_empty() {
        let input = crate::ast::Application {
            docs: vec![],
            representations: vec![],
            resource_types: vec![],
            resources: vec![],
            grammars: vec![],
        };
        let config = Config::default();
        let lines = generate(&input, &config);
        assert_eq!(lines, "".to_string());
    }

    #[test]
    fn test_enum_rust_value() {
        assert_eq!(enum_rust_value("foo"), "Foo");
        assert_eq!(enum_rust_value("foo bar"), "FooBar");
        assert_eq!(enum_rust_value("foo bar blah"), "FooBarBlah");
        assert_eq!(enum_rust_value("foo-bar"), "FooBar");
    }

    #[test]
    fn test_snake_case_name() {
        assert_eq!(snake_case_name("F"), "f");
        assert_eq!(snake_case_name("FooBar"), "foo_bar");
        assert_eq!(snake_case_name("FooBarBaz"), "foo_bar_baz");
        assert_eq!(snake_case_name("FooBarBazQuux"), "foo_bar_baz_quux");
        assert_eq!(snake_case_name("_FooBar"), "_foo_bar");
        assert_eq!(snake_case_name("ServiceRootJson"), "service_root_json");
        assert_eq!(snake_case_name("GetSomeURL"), "get_some_url");
    }

    #[test]
    fn test_strip_code_examples() {
        let input = r#"This is a test
```python
def foo():
    pass
```

This is another test
```python
def bar():
    pass
```
"#;
        let expected = r#"This is a test

This is another test"#;
        assert_eq!(strip_code_examples(input.to_string()), expected);
    }

    #[test]
    fn test_format_doc_plain() {
        let doc = Doc {
            title: None,
            lang: None,
            content: "This is a test".to_string(),
            xmlns: None,
        };

        assert_eq!(
            format_doc(&doc, &Config::default()),
            "This is a test".to_string()
        );
    }

    #[test]
    fn test_format_doc_html() {
        let doc = Doc {
            title: None,
            lang: None,
            content: "<p>This is a test</p>".to_string(),
            xmlns: Some("http://www.w3.org/1999/xhtml".parse().unwrap()),
        };

        assert_eq!(
            format_doc(&doc, &Config::default()),
            "This is a test".to_string()
        );
    }

    #[test]
    fn test_format_doc_html_link() {
        let doc = Doc {
            title: None,
            lang: None,
            content: "<p>This is a <a href=\"https://example.com\">test</a></p>".to_string(),
            xmlns: Some("http://www.w3.org/1999/xhtml".parse().unwrap()),
        };

        assert_eq!(
            format_doc(&doc, &Config::default()),
            "This is a [test](https://example.com)".to_string()
        );
    }

    #[test]
    fn test_generate_doc_plain() {
        let doc = Doc {
            title: Some("Foo".to_string()),
            lang: None,
            content: "This is a test".to_string(),
            xmlns: None,
        };

        assert_eq!(
            generate_doc(&doc, 0, &Config::default()),
            vec![
                "/// # Foo\n".to_string(),
                "///\n".to_string(),
                "/// This is a test\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_generate_doc_html() {
        let doc = Doc {
            title: Some("Foo".to_string()),
            lang: None,
            content: "<p>This is a test</p>".to_string(),
            xmlns: Some("http://www.w3.org/1999/xhtml".parse().unwrap()),
        };

        assert_eq!(
            generate_doc(&doc, 0, &Config::default()),
            vec![
                "/// # Foo\n".to_string(),
                "///\n".to_string(),
                "/// This is a test\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_generate_doc_multiple_lines() {
        let doc = Doc {
            title: Some("Foo".to_string()),
            lang: None,
            content: "This is a test\n\nThis is another test".to_string(),
            xmlns: None,
        };

        assert_eq!(
            generate_doc(&doc, 0, &Config::default()),
            vec![
                "/// # Foo\n".to_string(),
                "///\n".to_string(),
                "/// This is a test\n".to_string(),
                "///\n".to_string(),
                "/// This is another test\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_resource_type_rust_type() {
        use std::str::FromStr;
        let rt = ResourceTypeRef::from_str("https://api.launchpad.net/1.0/#person").unwrap();
        assert_eq!(resource_type_rust_type(&rt), "Person");
    }

    #[test]
    fn test_param_rust_type() {
        use std::str::FromStr;
        let rt = ResourceTypeRef::from_str("https://api.launchpad.net/1.0/#person").unwrap();
        let mut param = Param {
            name: "person".to_string(),
            r#type: "string".to_string(),
            required: true,
            repeating: false,
            fixed: None,
            doc: None,
            options: None,
            id: None,
            style: ParamStyle::Plain,
            path: None,
            links: vec![crate::ast::Link {
                resource_type: Some(rt),
                relation: None,
                reverse_relation: None,
                doc: None,
            }],
        };

        let method = Method {
            docs: vec![],
            id: "getPerson".to_string(),
            name: "getPerson".to_string(),
            request: Request {
                docs: vec![],
                params: vec![param.clone()],
                representations: vec![],
            },
            responses: vec![Response {
                status: None,
                docs: vec![],
                params: vec![param.clone()],
                representations: vec![],
            }],
        };

        let container = ParamContainer::Request(&method, &method.request);

        let (param_type, _) = param_rust_type(
            &container,
            &param,
            &Config::default(),
            resource_type_rust_type,
            &HashMap::new(),
        );
        assert_eq!(param_type, "Person");

        param.required = false;
        let (param_type, _) = param_rust_type(
            &container,
            &param,
            &Config::default(),
            resource_type_rust_type,
            &HashMap::new(),
        );
        assert_eq!(param_type, "Option<Person>");

        param.repeating = true;
        param.required = true;
        let (param_type, _) = param_rust_type(
            &container,
            &param,
            &Config::default(),
            resource_type_rust_type,
            &HashMap::new(),
        );
        assert_eq!(param_type, "Vec<Person>");

        param.repeating = false;
        param.r#type = "string".to_string();
        param.links = vec![];
        let (param_type, _) = param_rust_type(
            &container,
            &param,
            &Config::default(),
            resource_type_rust_type,
            &HashMap::new(),
        );
        assert_eq!(param_type, "String");

        param.r#type = "binary".to_string();
        let (param_type, _) = param_rust_type(
            &container,
            &param,
            &Config::default(),
            resource_type_rust_type,
            &HashMap::new(),
        );
        assert_eq!(param_type, "Vec<u8>");

        param.r#type = "xsd:date".to_string();
        let (param_type, _) = param_rust_type(
            &container,
            &param,
            &Config::default(),
            resource_type_rust_type,
            &HashMap::new(),
        );
        assert_eq!(param_type, "chrono::NaiveDate");

        param.r#type = "string".to_string();
        param.options = Some(Options::from(vec!["one".to_string(), "two".to_string()]));
        let (param_type, _) = param_rust_type(
            &container,
            &param,
            &Config::default(),
            resource_type_rust_type,
            &maplit::hashmap! {
                Options::from(vec!["one".to_string(), "two".to_string()]) => "MyOptions".to_string(),
            },
        );
        assert_eq!(param_type, "MyOptions");
    }

    #[test]
    fn test_readonly_rust_type() {
        assert_eq!(readonly_rust_type("String"), "&str");
        assert_eq!(readonly_rust_type("Vec<String>"), "&[String]");
        assert_eq!(
            readonly_rust_type("Option<Vec<String>>"),
            "Option<&[String]>"
        );
        assert_eq!(readonly_rust_type("Option<String>"), "Option<&str>");
        assert_eq!(readonly_rust_type("usize"), "&usize");
    }

    #[test]
    fn test_escape_rust_reserved() {
        assert_eq!(escape_rust_reserved("type"), "r#type");
        assert_eq!(escape_rust_reserved("match"), "r#match");
        assert_eq!(escape_rust_reserved("move"), "r#move");
        assert_eq!(escape_rust_reserved("use"), "r#use");
        assert_eq!(escape_rust_reserved("loop"), "r#loop");
        assert_eq!(escape_rust_reserved("continue"), "r#continue");
        assert_eq!(escape_rust_reserved("break"), "r#break");
        assert_eq!(escape_rust_reserved("fn"), "r#fn");
        assert_eq!(escape_rust_reserved("struct"), "r#struct");
        assert_eq!(escape_rust_reserved("enum"), "r#enum");
        assert_eq!(escape_rust_reserved("trait"), "r#trait");
        assert_eq!(escape_rust_reserved("impl"), "r#impl");
        assert_eq!(escape_rust_reserved("pub"), "r#pub");
        assert_eq!(escape_rust_reserved("as"), "r#as");
        assert_eq!(escape_rust_reserved("const"), "r#const");
        assert_eq!(escape_rust_reserved("let"), "r#let");
        assert_eq!(escape_rust_reserved("foo"), "foo");
    }

    #[test]
    fn test_representation_rust_type() {
        let rt = RepresentationRef::Id("person".to_string());
        assert_eq!(representation_rust_type(&rt), "Person");
    }

    #[test]
    fn test_generate_representation() {
        let input = RepresentationDef {
            media_type: Some("application/json".parse().unwrap()),
            element: None,
            profile: None,
            docs: vec![],
            id: Some("person".to_string()),
            params: vec![
                Param {
                    name: "name".to_string(),
                    r#type: "string".to_string(),
                    style: ParamStyle::Plain,
                    required: true,
                    doc: Some(Doc::new("The name of the person".to_string())),
                    path: None,
                    id: None,
                    repeating: false,
                    fixed: None,
                    links: vec![],
                    options: None,
                },
                Param {
                    name: "age".to_string(),
                    r#type: "xs:int".to_string(),
                    required: true,
                    doc: Some(Doc::new("The age of the person".to_string())),
                    style: ParamStyle::Query,
                    path: None,
                    id: None,
                    repeating: false,
                    fixed: None,
                    links: vec![],
                    options: None,
                },
            ],
        };

        let config = Config::default();

        let lines = generate_representation_struct_json(&input, &config, &HashMap::new());

        assert_eq!(
            lines,
            vec![
                "/// Representation of the `person` resource\n".to_string(),
                "#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]\n"
                    .to_string(),
                "pub struct Person {\n".to_string(),
                "    // was: string\n".to_string(),
                "    /// The name of the person\n".to_string(),
                "    pub name: String,\n".to_string(),
                "\n".to_string(),
                "    // was: xs:int\n".to_string(),
                "    /// The age of the person\n".to_string(),
                "    pub age: i32,\n".to_string(),
                "\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_supported_representation_def() {
        let mut d = RepresentationDef {
            media_type: Some(crate::WADL_MIME_TYPE.parse().unwrap()),
            ..Default::default()
        };
        assert!(!supported_representation_def(&d));

        d.media_type = Some(XHTML_MIME_TYPE.parse().unwrap());
        assert!(!supported_representation_def(&d));

        d.media_type = Some("application/json".parse().unwrap());
        assert!(!supported_representation_def(&d));

        // text/plain without plain params should not be supported
        d.media_type = Some("text/plain".parse().unwrap());
        d.params = vec![];
        assert!(!supported_representation_def(&d));

        // text/plain with plain params should be supported
        d.params = vec![Param {
            name: "return".to_string(),
            r#type: "string".to_string(),
            style: ParamStyle::Plain,
            required: false,
            repeating: false,
            fixed: None,
            doc: None,
            path: None,
            id: None,
            links: vec![],
            options: None,
        }];
        assert!(supported_representation_def(&d));
    }

    #[test]
    fn test_rust_type_for_response() {
        let mut input = Response {
            params: vec![Param {
                id: Some("foo".to_string()),
                name: "foo".to_string(),
                r#type: "string".to_string(),
                style: ParamStyle::Header,
                doc: None,
                required: true,
                repeating: false,
                fixed: None,
                path: None,
                links: Vec::new(),
                options: None,
            }],
            ..Default::default()
        };

        let method = Method {
            name: "GET".to_string(),
            id: "get".to_string(),
            docs: Vec::new(),
            request: Request::default(),
            responses: vec![input.clone()],
        };

        assert_eq!(
            rust_type_for_response(&method, &input, "foo", &Config::default(), &HashMap::new()),
            "String".to_string()
        );

        input.params = vec![
            Param {
                id: Some("foo".to_string()),
                name: "foo".to_string(),
                r#type: "string".to_string(),
                style: ParamStyle::Header,
                doc: None,
                required: true,
                repeating: false,
                fixed: None,
                path: None,
                links: Vec::new(),
                options: None,
            },
            Param {
                id: Some("bar".to_string()),
                name: "bar".to_string(),
                r#type: "string".to_string(),
                style: ParamStyle::Header,
                doc: None,
                required: true,
                repeating: false,
                fixed: None,
                path: None,
                links: Vec::new(),
                options: None,
            },
        ];
        assert_eq!(
            rust_type_for_response(&method, &input, "foo", &Config::default(), &HashMap::new()),
            "(String, String)".to_string()
        );

        input.params = vec![Param {
            id: Some("foo".to_string()),
            name: "foo".to_string(),
            r#type: "string".to_string(),
            style: ParamStyle::Header,
            doc: None,
            required: true,
            repeating: false,
            fixed: None,
            path: None,
            links: vec![Link {
                relation: None,
                reverse_relation: None,
                resource_type: Some("http://example.com/#foo".parse().unwrap()),
                doc: None,
            }],
            options: None,
        }];
        assert_eq!(
            rust_type_for_response(&method, &input, "foo", &Config::default(), &HashMap::new()),
            "Foo".to_string()
        );

        input.params = vec![Param {
            id: Some("foo".to_string()),
            name: "foo".to_string(),
            r#type: "string".to_string(),
            style: ParamStyle::Header,
            doc: None,
            required: true,
            repeating: false,
            fixed: None,
            path: None,
            links: vec![Link {
                relation: None,
                reverse_relation: None,
                resource_type: Some("http://example.com/#foo".parse().unwrap()),
                doc: None,
            }],
            options: None,
        }];
        assert_eq!(
            rust_type_for_response(&method, &input, "foo", &Config::default(), &HashMap::new()),
            "Foo".to_string()
        );

        input.params = vec![Param {
            id: None,
            name: "foo".to_string(),
            r#type: "string".to_string(),
            style: ParamStyle::Header,
            doc: None,
            required: true,
            repeating: false,
            fixed: None,
            options: None,
            path: None,
            links: vec![Link {
                relation: None,
                reverse_relation: None,
                resource_type: None,
                doc: None,
            }],
        }];
        assert_eq!(
            rust_type_for_response(&method, &input, "foo", &Config::default(), &HashMap::new()),
            "url::Url".to_string()
        );
    }

    #[test]
    fn test_format_arg_doc() {
        let config = Config::default();
        assert_eq!(
            format_arg_doc("foo", None, &config),
            vec!["    /// * `foo`\n".to_string()]
        );
        assert_eq!(
            format_arg_doc("foo", Some(&Doc::new("bar".to_string())), &config),
            vec!["    /// * `foo`: bar\n".to_string()]
        );
        assert_eq!(
            format_arg_doc("foo", Some(&Doc::new("bar\nbaz".to_string())), &config),
            vec![
                "    /// * `foo`: bar\n".to_string(),
                "    ///     baz\n".to_string()
            ]
        );
        assert_eq!(
            format_arg_doc("foo", Some(&Doc::new("bar\n\nbaz".to_string())), &config),
            vec![
                "    /// * `foo`: bar\n".to_string(),
                "    ///\n".to_string(),
                "    ///     baz\n".to_string()
            ]
        );
    }

    #[test]
    fn test_apply_map_fn() {
        assert_eq!(apply_map_fn(None, "x", false), "x".to_string());
        assert_eq!(
            apply_map_fn(Some("Some"), "x", false),
            "Some(x)".to_string()
        );
        assert_eq!(
            apply_map_fn(Some("Some"), "x", true),
            "x.map(Some)".to_string()
        );
        assert_eq!(
            apply_map_fn(Some("|y|y+1"), "x", false),
            "(|y|y+1)(x)".to_string()
        );
        assert_eq!(
            apply_map_fn(Some("|y|y+1"), "x", true),
            "x.map(|y|y+1)".to_string()
        );
    }

    #[test]
    fn test_generate_method() {
        let input = Method {
            id: "foo".to_string(),
            name: "GET".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![],
        };
        let config = Config::default();
        let lines = generate_method(&input, "bar", &config, &HashMap::new());
        assert_eq!(lines, vec![
        "    /// Retrieve the resource.\n".to_string(),
        "    ///\n".to_string(),
        "    pub fn foo<'a>(&self, client: &'a dyn wadl::blocking::Client) -> std::result::Result<(), wadl::Error> {\n".to_string(),
        "        let mut url_ = self.url().clone();\n".to_string(),
        "\n".to_string(),
        "        let mut req = client.request(reqwest::Method::GET, url_);\n".to_string(),
        "\n".to_string(),
        "        let resp = req.send()?;\n".to_string(),
        "        match resp.status() {\n".to_string(),
        "            s if s.is_success() => Ok(()),\n".to_string(),
        "            s => Err(wadl::Error::UnhandledStatus(s))\n".to_string(),
        "        }\n".to_string(),
        "    }\n".to_string(),
        "\n".to_string(),
    ]);
    }

    #[test]
    fn test_rust_type_for_response_text_plain() {
        // Test text/plain response returns String
        let response = Response {
            params: vec![],
            representations: vec![Representation::Definition(RepresentationDef {
                id: None,
                media_type: Some("text/plain".parse().unwrap()),
                element: None,
                profile: None,
                docs: vec![],
                params: vec![Param {
                    name: "return".to_string(),
                    r#type: "xsd:string".to_string(),
                    style: ParamStyle::Plain,
                    required: false,
                    repeating: false,
                    fixed: None,
                    doc: None,
                    path: None,
                    id: None,
                    links: vec![],
                    options: None,
                }],
            })],
            ..Default::default()
        };

        let method = Method {
            name: "POST".to_string(),
            id: "test".to_string(),
            docs: Vec::new(),
            request: Request::default(),
            responses: vec![response.clone()],
        };

        assert_eq!(
            rust_type_for_response(
                &method,
                &response,
                "test",
                &Config::default(),
                &HashMap::new()
            ),
            "String".to_string()
        );
    }

    #[test]
    fn test_rust_type_for_response_text_plain_with_headers() {
        // Test text/plain response with header params returns (String, ...)
        let response = Response {
            params: vec![
                Param {
                    id: Some("location".to_string()),
                    name: "Location".to_string(),
                    r#type: "string".to_string(),
                    style: ParamStyle::Header,
                    doc: None,
                    required: false,
                    repeating: false,
                    fixed: None,
                    path: None,
                    links: vec![],
                    options: None,
                },
                Param {
                    id: Some("etag".to_string()),
                    name: "ETag".to_string(),
                    r#type: "string".to_string(),
                    style: ParamStyle::Header,
                    doc: None,
                    required: false,
                    repeating: false,
                    fixed: None,
                    path: None,
                    links: vec![],
                    options: None,
                },
            ],
            representations: vec![Representation::Definition(RepresentationDef {
                id: None,
                media_type: Some("text/plain".parse().unwrap()),
                element: None,
                profile: None,
                docs: vec![],
                params: vec![Param {
                    name: "return".to_string(),
                    r#type: "xsd:string".to_string(),
                    style: ParamStyle::Plain,
                    required: false,
                    repeating: false,
                    fixed: None,
                    doc: None,
                    path: None,
                    id: None,
                    links: vec![],
                    options: None,
                }],
            })],
            ..Default::default()
        };

        let method = Method {
            name: "POST".to_string(),
            id: "test".to_string(),
            docs: Vec::new(),
            request: Request::default(),
            responses: vec![response.clone()],
        };

        // Should return tuple with String first, then header params (wrapped in Option since required=false)
        assert_eq!(
            rust_type_for_response(
                &method,
                &response,
                "test",
                &Config::default(),
                &HashMap::new()
            ),
            "(String, Option<String>, Option<String>)".to_string()
        );
    }

    #[test]
    fn test_generate_method_text_plain_response() {
        let input = Method {
            id: "getArchiveSubscriptionURL".to_string(),
            name: "POST".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![Response {
                status: None,
                docs: vec![],
                params: vec![],
                representations: vec![Representation::Definition(RepresentationDef {
                    id: None,
                    media_type: Some("text/plain".parse().unwrap()),
                    element: None,
                    profile: None,
                    docs: vec![],
                    params: vec![Param {
                        name: "return".to_string(),
                        r#type: "xsd:string".to_string(),
                        style: ParamStyle::Plain,
                        required: false,
                        repeating: false,
                        fixed: None,
                        doc: None,
                        path: None,
                        id: None,
                        links: vec![],
                        options: None,
                    }],
                })],
            }],
        };
        let config = Config::default();
        let lines = generate_method(&input, "bar", &config, &HashMap::new());

        assert_eq!(lines, vec![
            "    /// Create the resource.\n".to_string(),
            "    ///\n".to_string(),
            "    ///\n".to_string(),
            "    /// # Returns\n".to_string(),
            "    /// Returns `String` on success, or an error if the request fails.\n".to_string(),
            "    pub fn get_archive_subscription_url<'a>(&self, client: &'a dyn wadl::blocking::Client) -> std::result::Result<String, wadl::Error> {\n".to_string(),
            "        let mut url_ = self.url().clone();\n".to_string(),
            "\n".to_string(),
            "        let mut req = client.request(reqwest::Method::POST, url_);\n".to_string(),
            "        req = req.header(reqwest::header::ACCEPT, \"text/plain\");\n".to_string(),
            "\n".to_string(),
            "        let resp = req.send()?;\n".to_string(),
            "        match resp.status() {\n".to_string(),
            "            s if s.is_success() => {\n".to_string(),
            "                let content_type: Option<mime::Mime> = resp.headers().get(reqwest::header::CONTENT_TYPE).map(|x| x.to_str().unwrap()).map(|x| x.parse().unwrap());\n".to_string(),
            "                match content_type.as_ref().map(|x| x.essence_str()) {\n".to_string(),
            "                    Some(\"text/plain\") => {\n".to_string(),
            "                             Ok(resp.text()?)\n".to_string(),
            "                        }\n".to_string(),
            "                    _ => { Err(wadl::Error::UnhandledContentType(content_type)) }\n".to_string(),
            "                }\n".to_string(),
            "            }\n".to_string(),
            "            s => Err(wadl::Error::UnhandledStatus(s))\n".to_string(),
            "        }\n".to_string(),
            "    }\n".to_string(),
            "\n".to_string(),
        ]);
    }

    #[test]
    fn test_generate_method_text_plain_response_with_headers() {
        let input = Method {
            id: "getTextWithHeaders".to_string(),
            name: "GET".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![Response {
                status: None,
                docs: vec![],
                params: vec![Param {
                    id: Some("location".to_string()),
                    name: "Location".to_string(),
                    r#type: "string".to_string(),
                    style: ParamStyle::Header,
                    doc: None,
                    required: false,
                    repeating: false,
                    fixed: None,
                    path: None,
                    links: vec![Link {
                        relation: None,
                        reverse_relation: None,
                        resource_type: Some("http://example.com/#foo".parse().unwrap()),
                        doc: None,
                    }],
                    options: None,
                }],
                representations: vec![Representation::Definition(RepresentationDef {
                    id: None,
                    media_type: Some("text/plain".parse().unwrap()),
                    element: None,
                    profile: None,
                    docs: vec![],
                    params: vec![Param {
                        name: "return".to_string(),
                        r#type: "xsd:string".to_string(),
                        style: ParamStyle::Plain,
                        required: false,
                        repeating: false,
                        fixed: None,
                        doc: None,
                        path: None,
                        id: None,
                        links: vec![],
                        options: None,
                    }],
                })],
            }],
        };
        let config = Config::default();
        let lines = generate_method(&input, "bar", &config, &HashMap::new());

        // Should return a tuple: (String, Option<Foo>) where Foo is from the resource type link
        assert_eq!(lines, vec![
            "    /// Retrieve the resource.\n".to_string(),
            "    ///\n".to_string(),
            "    ///\n".to_string(),
            "    /// # Returns\n".to_string(),
            "    /// Returns `(String, Option<Foo>)` on success, or an error if the request fails.\n".to_string(),
            "    pub fn get_text_with_headers<'a>(&self, client: &'a dyn wadl::blocking::Client) -> std::result::Result<(String, Option<Foo>), wadl::Error> {\n".to_string(),
            "        let mut url_ = self.url().clone();\n".to_string(),
            "\n".to_string(),
            "        let mut req = client.request(reqwest::Method::GET, url_);\n".to_string(),
            "        req = req.header(reqwest::header::ACCEPT, \"text/plain\");\n".to_string(),
            "\n".to_string(),
            "        let resp = req.send()?;\n".to_string(),
            "        match resp.status() {\n".to_string(),
            "            s if s.is_success() => {\n".to_string(),
            "                let content_type: Option<mime::Mime> = resp.headers().get(reqwest::header::CONTENT_TYPE).map(|x| x.to_str().unwrap()).map(|x| x.parse().unwrap());\n".to_string(),
            "                match content_type.as_ref().map(|x| x.essence_str()) {\n".to_string(),
            "                    Some(\"text/plain\") => {\n".to_string(),
            "                             Ok((resp.text()?, resp.headers().get(\"Location\").map(|x| Foo(x.to_str().unwrap().parse().unwrap()))))\n".to_string(),
            "                        }\n".to_string(),
            "                    _ => { Err(wadl::Error::UnhandledContentType(content_type)) }\n".to_string(),
            "                }\n".to_string(),
            "            }\n".to_string(),
            "            s => Err(wadl::Error::UnhandledStatus(s))\n".to_string(),
            "        }\n".to_string(),
            "    }\n".to_string(),
            "\n".to_string(),
        ]);
    }

    #[test]
    fn test_generate_method_text_plain_response_async() {
        let input = Method {
            id: "getArchiveSubscriptionURL".to_string(),
            name: "POST".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![Response {
                status: None,
                docs: vec![],
                params: vec![],
                representations: vec![Representation::Definition(RepresentationDef {
                    id: None,
                    media_type: Some("text/plain".parse().unwrap()),
                    element: None,
                    profile: None,
                    docs: vec![],
                    params: vec![Param {
                        name: "return".to_string(),
                        r#type: "xsd:string".to_string(),
                        style: ParamStyle::Plain,
                        required: false,
                        repeating: false,
                        fixed: None,
                        doc: None,
                        path: None,
                        id: None,
                        links: vec![],
                        options: None,
                    }],
                })],
            }],
        };
        let config = Config {
            r#async: true,
            ..Default::default()
        };
        let lines = generate_method(&input, "bar", &config, &HashMap::new());

        // Verify it uses .await for async
        assert_eq!(lines, vec![
            "    /// Create the resource.\n".to_string(),
            "    ///\n".to_string(),
            "    ///\n".to_string(),
            "    /// # Returns\n".to_string(),
            "    /// Returns `String` on success, or an error if the request fails.\n".to_string(),
            "    pub async fn get_archive_subscription_url<'a>(&self, client: &'a dyn wadl::r#async::Client) -> std::result::Result<String, wadl::Error> {\n".to_string(),
            "        let mut url_ = self.url().clone();\n".to_string(),
            "\n".to_string(),
            "        let mut req = client.request(reqwest::Method::POST, url_).await;\n".to_string(),
            "        req = req.header(reqwest::header::ACCEPT, \"text/plain\");\n".to_string(),
            "\n".to_string(),
            "        let resp = req.send().await?;\n".to_string(),
            "        match resp.status() {\n".to_string(),
            "            s if s.is_success() => {\n".to_string(),
            "                let content_type: Option<mime::Mime> = resp.headers().get(reqwest::header::CONTENT_TYPE).map(|x| x.to_str().unwrap()).map(|x| x.parse().unwrap());\n".to_string(),
            "                match content_type.as_ref().map(|x| x.essence_str()) {\n".to_string(),
            "                    Some(\"text/plain\") => {\n".to_string(),
            "                             Ok(resp.text().await?)\n".to_string(),
            "                        }\n".to_string(),
            "                    _ => { Err(wadl::Error::UnhandledContentType(content_type)) }\n".to_string(),
            "                }\n".to_string(),
            "            }\n".to_string(),
            "            s => Err(wadl::Error::UnhandledStatus(s))\n".to_string(),
            "        }\n".to_string(),
            "    }\n".to_string(),
            "\n".to_string(),
        ]);
    }

    #[test]
    fn test_generate_resource_type() {
        let input = ResourceType {
            id: "foo".to_string(),
            docs: vec![],
            methods: vec![],
            query_type: mime::APPLICATION_JSON,
            params: vec![],
            subresources: vec![],
        };
        let config = Config::default();
        let lines = generate_resource_type(&input, &config, &HashMap::new());
        assert_eq!(
            lines,
            vec![
                "pub struct Foo (reqwest::Url);\n".to_string(),
                "\n".to_string(),
                "impl Foo {\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
                "impl wadl::Resource for Foo {\n".to_string(),
                "    fn url(&self) -> &reqwest::Url {\n".to_string(),
                "        &self.0\n".to_string(),
                "    }\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_generate_resource_with_path() {
        let input = Resource {
            id: None,
            path: Some("test-path".to_string()),
            r#type: vec![],
            docs: vec![],
            methods: vec![],
            query_type: mime::APPLICATION_JSON,
            params: vec![],
            subresources: vec![],
        };
        let base_url = Url::parse("http://example.com/api").unwrap();
        let config = Config::default();
        let lines = generate_resource(&input, Some(&base_url), &config, &HashMap::new());

        assert_eq!(
            lines,
            vec![
                "pub struct TestPath (reqwest::Url);\n".to_string(),
                "\n".to_string(),
                "impl TestPath {\n".to_string(),
                "    pub fn new() -> Self {\n        Self(reqwest::Url::parse(\"http://example.com/test-path\").unwrap())\n    }\n".to_string(),
                "\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
                "impl wadl::Resource for TestPath {\n".to_string(),
                "    fn url(&self) -> &reqwest::Url {\n".to_string(),
                "        &self.0\n".to_string(),
                "    }\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_generate_resource_with_id() {
        let input = Resource {
            id: Some("my-resource".to_string()),
            path: Some("path".to_string()),
            r#type: vec![],
            docs: vec![],
            methods: vec![],
            query_type: mime::APPLICATION_JSON,
            params: vec![],
            subresources: vec![],
        };
        let base_url = Url::parse("http://example.com").unwrap();
        let config = Config::default();
        let lines = generate_resource(&input, Some(&base_url), &config, &HashMap::new());

        assert_eq!(
            lines,
            vec![
                "pub struct MyResource (reqwest::Url);\n".to_string(),
                "\n".to_string(),
                "impl MyResource {\n".to_string(),
                "    pub fn new() -> Self {\n        Self(reqwest::Url::parse(\"http://example.com/path\").unwrap())\n    }\n".to_string(),
                "\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
                "impl wadl::Resource for MyResource {\n".to_string(),
                "    fn url(&self) -> &reqwest::Url {\n".to_string(),
                "        &self.0\n".to_string(),
                "    }\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_generate_resource_without_id_or_path() {
        let input = Resource {
            id: None,
            path: None,
            r#type: vec![],
            docs: vec![],
            methods: vec![],
            query_type: mime::APPLICATION_JSON,
            params: vec![],
            subresources: vec![],
        };
        let config = Config::default();
        let lines = generate_resource(&input, None, &config, &HashMap::new());

        // Should return empty when no id or path
        assert_eq!(lines, Vec::<String>::new());
    }

    #[test]
    fn test_generate_resource_with_empty_path() {
        let input = Resource {
            id: None,
            path: Some("/".to_string()),
            r#type: vec![],
            docs: vec![],
            methods: vec![],
            query_type: mime::APPLICATION_JSON,
            params: vec![],
            subresources: vec![],
        };
        let base_url = Url::parse("http://example.com").unwrap();
        let config = Config::default();
        let lines = generate_resource(&input, Some(&base_url), &config, &HashMap::new());

        // Should return empty when path becomes empty after trimming
        assert_eq!(lines, Vec::<String>::new());
    }

    #[test]
    fn test_generate_resources() {
        let input = Resources {
            base: Some(Url::parse("http://api.example.com").unwrap()),
            resources: vec![Resource {
                id: None,
                path: Some("users".to_string()),
                r#type: vec![],
                docs: vec![],
                methods: vec![],
                query_type: mime::APPLICATION_JSON,
                params: vec![],
                subresources: vec![],
            }],
        };
        let config = Config::default();
        let lines = generate_resources(&input, &config, &HashMap::new());

        assert_eq!(
            lines,
            vec![
                "pub struct Users (reqwest::Url);\n".to_string(),
                "\n".to_string(),
                "impl Users {\n".to_string(),
                "    pub fn new() -> Self {\n        Self(reqwest::Url::parse(\"http://api.example.com/users\").unwrap())\n    }\n".to_string(),
                "\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
                "impl wadl::Resource for Users {\n".to_string(),
                "    fn url(&self) -> &reqwest::Url {\n".to_string(),
                "        &self.0\n".to_string(),
                "    }\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_generate_resource_with_subresources() {
        let input = Resource {
            id: Some("parent".to_string()),
            path: Some("parent".to_string()),
            r#type: vec![],
            docs: vec![],
            methods: vec![],
            query_type: mime::APPLICATION_JSON,
            params: vec![],
            subresources: vec![Resource {
                id: Some("child".to_string()),
                path: Some("child".to_string()),
                r#type: vec![],
                docs: vec![],
                methods: vec![],
                query_type: mime::APPLICATION_JSON,
                params: vec![],
                subresources: vec![],
            }],
        };
        let base_url = Url::parse("http://example.com").unwrap();
        let config = Config::default();
        let lines = generate_resource(&input, Some(&base_url), &config, &HashMap::new());

        assert_eq!(
            lines,
            vec![
                "pub struct Parent (reqwest::Url);\n".to_string(),
                "\n".to_string(),
                "impl Parent {\n".to_string(),
                "    pub fn new() -> Self {\n        Self(reqwest::Url::parse(\"http://example.com/parent\").unwrap())\n    }\n".to_string(),
                "\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
                "impl wadl::Resource for Parent {\n".to_string(),
                "    fn url(&self) -> &reqwest::Url {\n".to_string(),
                "        &self.0\n".to_string(),
                "    }\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
                "pub struct Child (reqwest::Url);\n".to_string(),
                "\n".to_string(),
                "impl Child {\n".to_string(),
                "    pub fn new() -> Self {\n        Self(reqwest::Url::parse(\"http://example.com/child\").unwrap())\n    }\n".to_string(),
                "\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
                "impl wadl::Resource for Child {\n".to_string(),
                "    fn url(&self) -> &reqwest::Url {\n".to_string(),
                "        &self.0\n".to_string(),
                "    }\n".to_string(),
                "}\n".to_string(),
                "\n".to_string(),
            ]
        );
    }

    #[test]
    fn test_method_with_no_responses() {
        // Test that a method with no responses uses DEFAULT_RESPONSE and passes assertion
        let method = Method {
            id: "test-method".to_string(),
            name: "GET".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![],
        };

        let config = Config::default();
        let result = generate_method_representation(&method, "parent", &config, &HashMap::new());

        // Should succeed without panicking
        assert!(!result.is_empty());
    }

    #[test]
    fn test_method_with_one_success_response() {
        // Test that a method with one success response (200) passes assertion
        let method = Method {
            id: "test-method".to_string(),
            name: "GET".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![Response {
                docs: vec![],
                params: vec![],
                status: Some(200),
                representations: vec![],
            }],
        };

        let config = Config::default();
        let result = generate_method_representation(&method, "parent", &config, &HashMap::new());

        // Should succeed without panicking
        assert!(!result.is_empty());
    }

    #[test]
    fn test_method_with_success_response_no_status() {
        // Test that a method with one response (no status specified) passes assertion
        let method = Method {
            id: "test-method".to_string(),
            name: "GET".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![Response {
                docs: vec![],
                params: vec![],
                status: None,
                representations: vec![],
            }],
        };

        let config = Config::default();
        let result = generate_method_representation(&method, "parent", &config, &HashMap::new());

        // Should succeed without panicking
        assert!(!result.is_empty());
    }

    #[test]
    fn test_method_with_success_and_error_responses() {
        // Test that a method with one success response and one error response passes assertion
        let method = Method {
            id: "test-method".to_string(),
            name: "GET".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![
                Response {
                    docs: vec![],
                    params: vec![],
                    status: Some(200),
                    representations: vec![],
                },
                Response {
                    docs: vec![],
                    params: vec![],
                    status: Some(400),
                    representations: vec![],
                },
            ],
        };

        let config = Config::default();
        let result = generate_method_representation(&method, "parent", &config, &HashMap::new());

        // Should succeed without panicking - only success responses are counted
        assert!(!result.is_empty());
    }

    #[test]
    #[should_panic(expected = "expected 1 success response")]
    fn test_method_with_multiple_success_responses_panics() {
        // Test that a method with multiple success responses (200 and 201) triggers assertion
        let method = Method {
            id: "test-method".to_string(),
            name: "GET".to_string(),
            docs: vec![],
            request: Request {
                docs: vec![],
                params: vec![],
                representations: vec![],
            },
            responses: vec![
                Response {
                    docs: vec![],
                    params: vec![],
                    status: Some(200),
                    representations: vec![],
                },
                Response {
                    docs: vec![],
                    params: vec![],
                    status: Some(201),
                    representations: vec![],
                },
            ],
        };

        let config = Config::default();
        // This should panic with "expected 1 success response for test_method, found 2"
        generate_method_representation(&method, "parent", &config, &HashMap::new());
    }
}