openapi-to-rust 0.5.3

Generate strongly-typed Rust structs, HTTP clients, and SSE streaming clients from OpenAPI 3.1 specifications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
//! HTTP client generation for OpenAPI specifications.
//!
//! This module is part of the code generator that creates production-ready HTTP clients
//! from OpenAPI specifications. It generates clients with middleware support including
//! retry logic and request tracing.
//!
//! # Overview
//!
//! The client generator creates:
//! - `HttpClient` struct with middleware stack (reqwest-middleware)
//! - Retry logic with exponential backoff (reqwest-retry)
//! - Request/response tracing (reqwest-tracing)
//! - Direct methods for all API operations (GET, POST, PUT, DELETE, PATCH)
//! - Comprehensive error handling with [`HttpError`](crate::http_error::HttpError)
//! - Builder pattern for configuration
//!
//! # Generated Code Structure
//!
//! For each OpenAPI specification, the generator creates:
//!
//! ```rust,ignore
//! // Generated client.rs file
//!
//! use crate::types::*;
//! use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
//! use std::collections::BTreeMap;
//!
//! pub struct HttpClient {
//!     base_url: String,
//!     api_key: Option<String>,
//!     http_client: ClientWithMiddleware,
//!     custom_headers: BTreeMap<String, String>,
//! }
//!
//! impl HttpClient {
//!     pub fn new() -> Self { /* ... */ }
//!     pub fn with_config(retry_config: Option<RetryConfig>, enable_tracing: bool) -> Self { /* ... */ }
//!     pub fn with_base_url(self, base_url: String) -> Self { /* ... */ }
//!     pub fn with_api_key(self, api_key: String) -> Self { /* ... */ }
//!     pub fn with_header(self, key: String, value: String) -> Self { /* ... */ }
//!
//!     // Generated operation methods
//!     pub async fn list_items(&self) -> Result<ItemList, HttpError> { /* ... */ }
//!     pub async fn create_item(&self, request: CreateItemRequest) -> Result<Item, HttpError> { /* ... */ }
//!     pub async fn get_item(&self, id: impl AsRef<str>) -> Result<Item, HttpError> { /* ... */ }
//! }
//! ```
//!
//! # Middleware Stack
//!
//! The generated client uses `reqwest-middleware` to build a composable middleware stack:
//!
//! 1. **Tracing Middleware** (optional, enabled by default)
//!    - Logs HTTP requests/responses
//!    - Creates spans for distributed tracing
//!    - Integrates with `tracing` ecosystem
//!
//! 2. **Retry Middleware** (optional, configured via TOML)
//!    - Exponential backoff retry policy
//!    - Automatically retries transient errors (429, 500, 502, 503, 504)
//!    - Configurable max retries and delay bounds
//!
//! # Configuration
//!
//! ## Via TOML
//!
//! ```toml
//! [http_client]
//! base_url = "https://api.example.com"
//! timeout_seconds = 30
//!
//! [http_client.retry]
//! max_retries = 3
//! initial_delay_ms = 500
//! max_delay_ms = 16000
//!
//! [http_client.tracing]
//! enabled = true
//! ```
//!
//! ## Via Rust API
//!
//! ```no_run
//! use openapi_to_rust::{GeneratorConfig, http_config::*};
//! use std::path::PathBuf;
//!
//! let config = GeneratorConfig {
//!     spec_path: PathBuf::from("openapi.json"),
//!     enable_async_client: true,
//!     retry_config: Some(RetryConfig {
//!         max_retries: 3,
//!         initial_delay_ms: 500,
//!         max_delay_ms: 16000,
//!     }),
//!     tracing_enabled: true,
//!     // ... other fields
//!     ..Default::default()
//! };
//! ```
//!
//! # Generated Client Usage
//!
//! ```rust,ignore
//! use crate::generated::client::HttpClient;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Create client with retry and tracing
//!     let client = HttpClient::new()
//!         .with_base_url("https://api.example.com".to_string())
//!         .with_api_key("your-api-key".to_string())
//!         .with_header("X-Custom-Header".to_string(), "value".to_string());
//!
//!     // Make API calls - retries happen automatically
//!     let items = client.list_items().await?;
//!     println!("Found {} items", items.items.len());
//!
//!     Ok(())
//! }
//! ```
//!
//! # HTTP Method Support
//!
//! The generator supports all standard HTTP methods:
//! - `GET` - List and retrieve operations
//! - `POST` - Create operations
//! - `PUT` - Full update operations
//! - `PATCH` - Partial update operations
//! - `DELETE` - Delete operations
//!
//! # Error Handling
//!
//! All generated methods return `Result<T, HttpError>` where `HttpError` provides:
//! - Detailed error information
//! - Retry detection via `is_retryable()`
//! - Error categorization (client errors, server errors)
//!
//! See [`http_error`](crate::http_error) module for details.
//!
//! # Implementation Details
//!
//! The generator uses the following approach:
//! 1. Analyzes OpenAPI operations to extract HTTP methods, paths, parameters
//! 2. Generates typed request/response handling
//! 3. Creates method signatures with proper parameter types
//! 4. Generates path parameter substitution
//! 5. Handles query parameters and request bodies
//! 6. Configures middleware stack based on generator config

use crate::analysis::{OperationInfo, ParameterInfo, SchemaAnalysis};
use crate::generator::CodeGenerator;
use heck::ToSnakeCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::BTreeMap;

impl CodeGenerator {
    /// Generate the HTTP client struct with middleware support
    pub fn generate_http_client_struct(&self) -> TokenStream {
        let has_retry = self.config().retry_config.is_some();
        let has_tracing = self.config().tracing_enabled;

        // Generate RetryConfig struct if needed
        let retry_config_struct = if has_retry {
            quote! {
                /// Retry configuration for HTTP requests
                #[derive(Debug, Clone)]
                pub struct RetryConfig {
                    pub max_retries: u32,
                    pub initial_delay_ms: u64,
                    pub max_delay_ms: u64,
                }

                impl Default for RetryConfig {
                    fn default() -> Self {
                        Self {
                            max_retries: 3,
                            initial_delay_ms: 500,
                            max_delay_ms: 16000,
                        }
                    }
                }
            }
        } else {
            quote! {}
        };

        // Generate the main HttpClient struct
        let client_struct = quote! {
            use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
            use std::collections::BTreeMap;

            /// HTTP client for making API requests
            #[derive(Clone)]
            pub struct HttpClient {
                base_url: String,
                api_key: Option<String>,
                http_client: ClientWithMiddleware,
                custom_headers: BTreeMap<String, String>,
            }
        };

        // Generate constructor
        let constructor = self.generate_constructor(has_retry, has_tracing);

        // Generate builder methods
        let builder_methods = self.generate_builder_methods();

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

        // Path-segment percent encoder, used by url construction (T5).
        // Encodes per RFC3986 §3.3: only ALPHA, DIGIT, and `-._~` pass through;
        // everything else becomes `%XX`.
        let path_encoder = quote! {
            fn __pct_encode_path_segment(s: &str) -> String {
                let mut out = String::with_capacity(s.len());
                for &b in s.as_bytes() {
                    match b {
                        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                            out.push(b as char);
                        }
                        _ => {
                            out.push('%');
                            out.push_str(&format!("{:02X}", b));
                        }
                    }
                }
                out
            }
        };

        // Combine all parts
        quote! {
            #retry_config_struct
            #client_struct

            impl HttpClient {
                #constructor
                #builder_methods
            }

            #default_impl
            #path_encoder
        }
    }

    /// Generate the constructor method
    fn generate_constructor(&self, has_retry: bool, has_tracing: bool) -> TokenStream {
        let retry_param = if has_retry {
            quote! { retry_config: Option<RetryConfig>, }
        } else {
            quote! {}
        };

        let tracing_param = if has_tracing {
            quote! { enable_tracing: bool, }
        } else {
            quote! {}
        };

        let retry_middleware = if has_retry {
            quote! {
                if let Some(config) = retry_config {
                    use reqwest_retry::{RetryTransientMiddleware, policies::ExponentialBackoff};

                    let retry_policy = ExponentialBackoff::builder()
                        .retry_bounds(
                            std::time::Duration::from_millis(config.initial_delay_ms),
                            std::time::Duration::from_millis(config.max_delay_ms),
                        )
                        .build_with_max_retries(config.max_retries);

                    let retry_middleware = RetryTransientMiddleware::new_with_policy(retry_policy);
                    client_builder = client_builder.with(retry_middleware);
                }
            }
        } else {
            quote! {}
        };

        let tracing_middleware = if has_tracing {
            quote! {
                if enable_tracing {
                    use reqwest_tracing::TracingMiddleware;
                    client_builder = client_builder.with(TracingMiddleware::default());
                }
            }
        } else {
            quote! {}
        };

        let default_constructor = if has_retry && has_tracing {
            quote! {
                /// Create a new HTTP client with default configuration
                pub fn new() -> Self {
                    Self::with_config(None, true)
                }
            }
        } else if has_retry {
            quote! {
                /// Create a new HTTP client with default configuration
                pub fn new() -> Self {
                    Self::with_config(None)
                }
            }
        } else if has_tracing {
            quote! {
                /// Create a new HTTP client with default configuration
                pub fn new() -> Self {
                    Self::with_config(true)
                }
            }
        } else {
            quote! {
                /// Create a new HTTP client with default configuration
                pub fn new() -> Self {
                    let reqwest_client = reqwest::Client::new();
                    let client_builder = ClientBuilder::new(reqwest_client);
                    let http_client = client_builder.build();

                    Self {
                        base_url: String::new(),
                        api_key: None,
                        http_client,
                        custom_headers: BTreeMap::new(),
                    }
                }
            }
        };

        if has_retry || has_tracing {
            quote! {
                #default_constructor

                /// Create a new HTTP client with custom configuration
                pub fn with_config(#retry_param #tracing_param) -> Self {
                    let reqwest_client = reqwest::Client::new();
                    let mut client_builder = ClientBuilder::new(reqwest_client);

                    #tracing_middleware
                    #retry_middleware

                    let http_client = client_builder.build();

                    Self {
                        base_url: String::new(),
                        api_key: None,
                        http_client,
                        custom_headers: BTreeMap::new(),
                    }
                }
            }
        } else {
            default_constructor
        }
    }

    /// Generate builder methods for configuration
    fn generate_builder_methods(&self) -> TokenStream {
        quote! {
            /// Set the base URL for all requests
            pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
                self.base_url = base_url.into();
                self
            }

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

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

            /// Add multiple custom headers
            pub fn with_headers(mut self, headers: BTreeMap<String, String>) -> Self {
                self.custom_headers.extend(headers);
                self
            }
        }
    }

    /// Generate HTTP operation methods for the client.
    ///
    /// Emits per-operation typed error enums (one variant per declared non-2xx
    /// response with a body schema) BEFORE the `impl HttpClient` block so the
    /// generated method signatures can reference them.
    pub fn generate_operation_methods(&self, analysis: &SchemaAnalysis) -> TokenStream {
        let param_enums = self.generate_param_enum_types(analysis);

        let op_error_enums: Vec<TokenStream> = analysis
            .operations
            .values()
            .filter_map(|op| self.generate_op_error_enum(op))
            .collect();

        let methods: Vec<TokenStream> = analysis
            .operations
            .values()
            .map(|op| self.generate_single_operation_method(op))
            .collect();

        quote! {
            #param_enums

            #(#op_error_enums)*

            impl HttpClient {
                #(#methods)*
            }
        }
    }

    /// Emit inline enum types for parameters whose schema is `type: string`
    /// with `enum` or `const`. The generated enum implements `Display` so it
    /// drops into the existing `format!`-based path/query templating without
    /// any special-casing at the call site. See issue #10 follow-up.
    fn generate_param_enum_types(&self, analysis: &SchemaAnalysis) -> TokenStream {
        let mut by_name: BTreeMap<String, &ParameterInfo> = BTreeMap::new();
        for op in analysis.operations.values() {
            for param in &op.parameters {
                if param.enum_values.is_some() {
                    by_name.entry(param.rust_type.clone()).or_insert(param);
                }
            }
        }

        if by_name.is_empty() {
            return quote! {};
        }

        let defs: Vec<TokenStream> = by_name
            .values()
            .map(|param| self.generate_single_param_enum(param))
            .collect();

        quote! { #(#defs)* }
    }

    fn generate_single_param_enum(&self, param: &ParameterInfo) -> TokenStream {
        let Some(values) = param.enum_values.as_deref() else {
            return quote! {};
        };

        let enum_ident = format_ident!("{}", param.rust_type);

        // Dedupe variant names. Real-world specs use sort enums like
        // `["created_at", "-created_at"]` (descending prefix), and both
        // PascalCase to `CreatedAt`. Suffix collisions with `_2`/`_3`/…
        // while keeping each `serde(rename)` pointing at the original
        // wire string.
        let mut used: std::collections::HashSet<String> = std::collections::HashSet::new();
        let variant_names: Vec<String> = values
            .iter()
            .map(|value| {
                let base = self.to_rust_enum_variant(value);
                let mut chosen = base.clone();
                let mut suffix = 2;
                while !used.insert(chosen.clone()) {
                    chosen = format!("{base}_{suffix}");
                    suffix += 1;
                }
                chosen
            })
            .collect();

        let variants: Vec<TokenStream> = values
            .iter()
            .zip(&variant_names)
            .map(|(value, name)| {
                let variant_ident = format_ident!("{}", name);
                quote! {
                    #[serde(rename = #value)]
                    #variant_ident,
                }
            })
            .collect();

        let display_arms: Vec<TokenStream> = values
            .iter()
            .zip(&variant_names)
            .map(|(value, name)| {
                let variant_ident = format_ident!("{}", name);
                quote! { Self::#variant_ident => #value, }
            })
            .collect();

        let doc = format!(
            "Allowed values for the `{}` {} parameter.",
            param.name, param.location
        );

        quote! {
            #[doc = #doc]
            #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
            pub enum #enum_ident {
                #(#variants)*
            }

            impl #enum_ident {
                pub fn as_str(&self) -> &'static str {
                    match self {
                        #(#display_arms)*
                    }
                }
            }

            impl std::fmt::Display for #enum_ident {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.write_str(self.as_str())
                }
            }

            impl AsRef<str> for #enum_ident {
                fn as_ref(&self) -> &str {
                    self.as_str()
                }
            }
        }
    }

    /// Generate the per-operation typed error enum, if the op has any non-2xx
    /// responses with a body schema. Returns None when the op has no declared
    /// error bodies — those operations use `ApiOpError<serde_json::Value>` so
    /// the raw response body is still inspectable.
    fn generate_op_error_enum(&self, op: &OperationInfo) -> Option<TokenStream> {
        let variants: Vec<(String, String)> = op
            .response_schemas
            .iter()
            .filter(|(code, _)| !code.starts_with('2'))
            .map(|(code, schema)| (code.clone(), schema.clone()))
            .collect();

        if variants.is_empty() {
            return None;
        }

        let enum_ident = self.op_error_enum_ident(op);
        let variant_decls: Vec<TokenStream> = variants
            .iter()
            .map(|(code, schema)| {
                let variant_ident = Self::op_error_variant_ident(code);
                let payload_ty_name = self.to_rust_type_name(schema);
                let payload_ty = syn::Ident::new(&payload_ty_name, proc_macro2::Span::call_site());
                quote! { #variant_ident(#payload_ty) }
            })
            .collect();

        let doc = format!(
            "Typed error responses for `{}`. One variant per declared non-2xx response.",
            op.operation_id
        );

        Some(quote! {
            #[doc = #doc]
            #[derive(Debug, Clone)]
            pub enum #enum_ident {
                #(#variant_decls,)*
            }
        })
    }

    /// Type name (Ident) for the per-op error enum, e.g. `ListTodosApiError`.
    fn op_error_enum_ident(&self, op: &OperationInfo) -> syn::Ident {
        use heck::ToPascalCase;
        let name = format!(
            "{}ApiError",
            op.operation_id.replace('.', "_").to_pascal_case()
        );
        syn::Ident::new(&name, proc_macro2::Span::call_site())
    }

    /// Variant name for a status code: "400" → Status400, "default" → Default,
    /// "4XX" → Status4xx.
    fn op_error_variant_ident(status_code: &str) -> syn::Ident {
        let raw = match status_code {
            "default" | "Default" => "Default".to_string(),
            other if other.chars().all(|c| c.is_ascii_digit()) => format!("Status{other}"),
            other => format!("Status{}", other.to_ascii_lowercase()),
        };
        syn::Ident::new(&raw, proc_macro2::Span::call_site())
    }

    /// Token stream for the type plugged into `ApiOpError<T>` for an op:
    /// either the per-op enum, or `serde_json::Value` for ops with no
    /// declared error body schemas.
    fn op_error_type_token(&self, op: &OperationInfo) -> TokenStream {
        if op
            .response_schemas
            .iter()
            .any(|(code, _)| !code.starts_with('2'))
        {
            let ident = self.op_error_enum_ident(op);
            quote! { #ident }
        } else {
            quote! { serde_json::Value }
        }
    }

    /// Generate a single operation method
    fn generate_single_operation_method(&self, op: &OperationInfo) -> TokenStream {
        let method_name = self.get_method_name(op);
        let http_method_call = self.http_method_call(op);
        let path = &op.path;
        let request_param = self.generate_request_param(op);
        let request_body = self.generate_request_body(op);
        let query_params = self.generate_query_params(op);
        let header_params = self.generate_header_params(op);
        let auth_application = self.generate_auth_application();
        let response_type = self.get_response_type(op);
        let has_response_body = self.get_success_response_schema(op).is_some();
        let op_error_type = self.op_error_type_token(op);
        let error_handling = self.generate_error_handling(op, has_response_body);
        let url_construction = self.generate_url_construction(path, op);
        let doc_comment = self.generate_operation_doc_comment(op);

        quote! {
            #doc_comment
            pub async fn #method_name(
                &self,
                #request_param
            ) -> Result<#response_type, ApiOpError<#op_error_type>> {
                #url_construction

                let mut req = #http_method_call;
                #request_body

                #query_params
                #header_params

                // Apply configured authentication (T3). Was previously
                // hardcoded to bearer_auth regardless of GeneratorConfig.
                #auth_application

                // Add custom headers
                for (name, value) in &self.custom_headers {
                    req = req.header(name, value);
                }

                let response = req.send().await?;
                #error_handling
            }
        }
    }

    /// T3: emit the auth-token application based on the configured AuthConfig.
    /// Default (no config) is Bearer on Authorization. ApiKey emits a custom
    /// header. Custom honors header_value_prefix.
    fn generate_auth_application(&self) -> TokenStream {
        use crate::http_config::AuthConfig;
        match &self.config().auth_config {
            Some(AuthConfig::Bearer { header_name }) if header_name == "Authorization" => quote! {
                if let Some(api_key) = &self.api_key {
                    req = req.bearer_auth(api_key);
                }
            },
            Some(AuthConfig::Bearer { header_name }) => {
                let h = header_name.clone();
                quote! {
                    if let Some(api_key) = &self.api_key {
                        req = req.header(#h, format!("Bearer {}", api_key));
                    }
                }
            }
            Some(AuthConfig::ApiKey { header_name }) => {
                let h = header_name.clone();
                quote! {
                    if let Some(api_key) = &self.api_key {
                        req = req.header(#h, api_key.as_str());
                    }
                }
            }
            Some(AuthConfig::Custom {
                header_name,
                header_value_prefix,
            }) => {
                let h = header_name.clone();
                let prefix = header_value_prefix.clone().unwrap_or_default();
                if prefix.is_empty() {
                    quote! {
                        if let Some(api_key) = &self.api_key {
                            req = req.header(#h, api_key.as_str());
                        }
                    }
                } else {
                    let format_str = format!("{}{{}}", prefix);
                    quote! {
                        if let Some(api_key) = &self.api_key {
                            req = req.header(#h, format!(#format_str, api_key));
                        }
                    }
                }
            }
            None => quote! {
                if let Some(api_key) = &self.api_key {
                    req = req.bearer_auth(api_key);
                }
            },
        }
    }

    /// Generate header-parameter handling. Emits `req = req.header(name, ...)`
    /// for each `in: header` parameter — required headers unconditionally,
    /// optional ones gated on `Some(_)`.
    fn generate_header_params(&self, op: &OperationInfo) -> TokenStream {
        let header_params: Vec<_> = op
            .parameters
            .iter()
            .filter(|p| p.location == "header")
            .collect();
        if header_params.is_empty() {
            return quote! {};
        }
        let mut emit = Vec::new();
        for param in header_params {
            let param_name_snake = self.param_ident_str(param);
            let param_ident = Self::to_field_ident(&param_name_snake);
            let header_name = &param.name;
            if param.required {
                if Self::param_uses_as_ref_str(param) {
                    emit.push(quote! {
                        req = req.header(#header_name, #param_ident.as_ref());
                    });
                } else {
                    emit.push(quote! {
                        req = req.header(#header_name, #param_ident.to_string());
                    });
                }
            } else if Self::param_uses_as_ref_str(param) {
                emit.push(quote! {
                    if let Some(v) = #param_ident {
                        req = req.header(#header_name, v.as_ref());
                    }
                });
            } else {
                emit.push(quote! {
                    if let Some(v) = #param_ident {
                        req = req.header(#header_name, v.to_string());
                    }
                });
            }
        }
        quote! {
            #(#emit)*
        }
    }

    /// Generate query parameter handling
    fn generate_query_params(&self, op: &OperationInfo) -> TokenStream {
        let query_params: Vec<_> = op
            .parameters
            .iter()
            .filter(|p| p.location == "query")
            .collect();

        if query_params.is_empty() {
            return quote! {};
        }

        let mut param_building = Vec::new();

        for param in query_params {
            // Use snake_case for Rust variable name with keyword escaping
            let param_name_snake = self.param_ident_str(param);
            let param_name = Self::to_field_ident(&param_name_snake);

            // Use the original parameter name from OpenAPI spec as the query string key
            let param_key = &param.name;

            if param.required {
                // Required parameters: always add
                if Self::param_uses_as_ref_str(param) {
                    param_building.push(quote! {
                        query_params.push((#param_key, #param_name.as_ref().to_string()));
                    });
                } else {
                    param_building.push(quote! {
                        query_params.push((#param_key, #param_name.to_string()));
                    });
                }
            } else {
                // Optional parameters: add only if Some
                if Self::param_uses_as_ref_str(param) {
                    param_building.push(quote! {
                        if let Some(v) = #param_name {
                            query_params.push((#param_key, v.as_ref().to_string()));
                        }
                    });
                } else {
                    param_building.push(quote! {
                        if let Some(v) = #param_name {
                            query_params.push((#param_key, v.to_string()));
                        }
                    });
                }
            }
        }

        quote! {
            // Add query parameters
            {
                let mut query_params: Vec<(&str, String)> = Vec::new();
                #(#param_building)*
                if !query_params.is_empty() {
                    req = req.query(&query_params);
                }
            }
        }
    }

    /// Generate the rustdoc block for an operation, surfacing summary,
    /// description, the HTTP method+path, and any tags from the OAS spec
    /// (T13). Also marks the method `#[deprecated]` if the operation is.
    fn generate_operation_doc_comment(&self, op: &OperationInfo) -> TokenStream {
        let method = op.method.to_uppercase();
        let path = &op.path;
        let mut docs: Vec<String> = Vec::new();
        if let Some(s) = &op.summary {
            if !s.is_empty() {
                docs.push(s.clone());
                docs.push(String::new());
            }
        }
        if let Some(d) = &op.description {
            if !d.is_empty() {
                for line in d.lines() {
                    docs.push(line.to_string());
                }
                docs.push(String::new());
            }
        }
        docs.push(format!("`{} {}`", method, path));
        let doc_attrs: Vec<TokenStream> = docs
            .iter()
            .map(|line| {
                let prefixed = if line.is_empty() {
                    String::new()
                } else {
                    format!(" {line}")
                };
                quote! { #[doc = #prefixed] }
            })
            .collect();
        quote! { #(#doc_attrs)* }
    }

    /// Get the method name from the operation
    fn get_method_name(&self, op: &OperationInfo) -> syn::Ident {
        let name = if !op.operation_id.is_empty() {
            op.operation_id.to_snake_case()
        } else {
            // Fallback: generate from HTTP method and path
            format!(
                "{}_{}",
                op.method,
                op.path.replace('/', "_").replace(['{', '}'], "")
            )
            .to_snake_case()
        };

        syn::Ident::new(&name, proc_macro2::Span::call_site())
    }

    /// Build the request-builder expression for the operation's HTTP method.
    /// Named reqwest methods (`.get`/`.post`/…) are used where available;
    /// OPTIONS and TRACE go through `Client::request(Method::OPTIONS, _)` since
    /// reqwest doesn't expose those as named methods.
    fn http_method_call(&self, op: &OperationInfo) -> TokenStream {
        match op.method.to_uppercase().as_str() {
            "GET" => quote! { self.http_client.get(request_url) },
            "POST" => quote! { self.http_client.post(request_url) },
            "PUT" => quote! { self.http_client.put(request_url) },
            "DELETE" => quote! { self.http_client.delete(request_url) },
            "PATCH" => quote! { self.http_client.patch(request_url) },
            "HEAD" => quote! { self.http_client.head(request_url) },
            "OPTIONS" => quote! {
                self.http_client.request(reqwest::Method::OPTIONS, request_url)
            },
            "TRACE" => quote! {
                self.http_client.request(reqwest::Method::TRACE, request_url)
            },
            // D1: 3.2 `QUERY` verb + any custom verb from
            // PathItem.additionalOperations. reqwest's Method::from_bytes
            // accepts arbitrary uppercase tokens that match the RFC7230
            // method grammar.
            other => {
                let upper = other.to_string();
                quote! {
                    self.http_client.request(
                        reqwest::Method::from_bytes(#upper.as_bytes())
                            .expect("invalid HTTP method"),
                        request_url,
                    )
                }
            }
        }
    }

    /// Generate request parameters including path, query, header, and request body.
    fn generate_request_param(&self, op: &OperationInfo) -> TokenStream {
        let mut params = Vec::new();
        // Dedup parameter Rust idents within this method signature. Real-world
        // specs sometimes declare two parameters that sanitize to the same
        // snake_case name (modern-treasury declared `name` twice across
        // different param objects). Suffixing with `_2`, `_3`, … keeps each
        // parameter accessible while preserving the original wire-level name
        // (which is used elsewhere as the query/path/header key).
        let mut used: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut unique_param_ident = |raw: String| -> syn::Ident {
            let mut chosen = raw.clone();
            let mut suffix = 2;
            while !used.insert(chosen.clone()) {
                chosen = format!("{raw}_{suffix}");
                suffix += 1;
            }
            Self::to_field_ident(&chosen)
        };

        // Add path parameters
        for param in &op.parameters {
            if param.location == "path" {
                let param_name_snake = self.param_ident_str(param);
                let param_name = unique_param_ident(param_name_snake);
                let param_type = self.get_param_rust_type(param);
                params.push(quote! { #param_name: #param_type });
            }
        }

        // Add query parameters (all as Option<T>)
        for param in &op.parameters {
            if param.location == "query" {
                let param_name_snake = self.param_ident_str(param);
                let param_name = unique_param_ident(param_name_snake);
                let param_type = self.get_param_rust_type(param);

                // Query parameters should be Option unless explicitly required
                if param.required {
                    params.push(quote! { #param_name: #param_type });
                } else {
                    params.push(quote! { #param_name: Option<#param_type> });
                }
            }
        }

        // Add header parameters. Required headers are bare; optional ones are
        // Option<T>. Per OAS 3.x §"Parameter Object", header names matching
        // `Accept`, `Content-Type`, and `Authorization` are forbidden — those
        // are described by other mechanisms — but we leave that validation to
        // analysis.
        for param in &op.parameters {
            if param.location == "header" {
                let param_name_snake = self.param_ident_str(param);
                let param_name = unique_param_ident(param_name_snake);
                let param_type = self.get_param_rust_type(param);
                if param.required {
                    params.push(quote! { #param_name: #param_type });
                } else {
                    params.push(quote! { #param_name: Option<#param_type> });
                }
            }
        }

        // Add request body parameter based on content type. Optional bodies
        // (`requestBody.required` is false or absent) become `Option<T>` per T11.
        if let Some(ref rb) = op.request_body {
            use crate::analysis::RequestBodyContent;
            let required = op.request_body_required;
            let body_type = match rb {
                RequestBodyContent::Json { schema_name }
                | RequestBodyContent::FormUrlEncoded { schema_name } => {
                    let rust_type_name = self.to_rust_type_name(schema_name);
                    let request_ident =
                        syn::Ident::new(&rust_type_name, proc_macro2::Span::call_site());
                    quote! { #request_ident }
                }
                RequestBodyContent::Multipart => quote! { reqwest::multipart::Form },
                RequestBodyContent::OctetStream => quote! { Vec<u8> },
                RequestBodyContent::TextPlain => quote! { String },
            };
            let body_ident = match rb {
                RequestBodyContent::Multipart => quote! { form },
                RequestBodyContent::OctetStream | RequestBodyContent::TextPlain => quote! { body },
                _ => quote! { request },
            };
            if required {
                params.push(quote! { #body_ident: #body_type });
            } else {
                params.push(quote! { #body_ident: Option<#body_type> });
            }
        }

        if params.is_empty() {
            quote! {}
        } else {
            quote! { #(#params),* }
        }
    }

    /// Get the Rust type for a parameter
    fn get_param_rust_type(&self, param: &crate::analysis::ParameterInfo) -> TokenStream {
        // T10: $ref-typed parameters used to lose their type because we only
        // consulted `rust_type` (which stays "String"). Now: prefer the
        // resolved schema reference if present.
        if let Some(ref schema_name) = param.schema_ref {
            let rust_name = self.to_rust_type_name(schema_name);
            let ident = syn::Ident::new(&rust_name, proc_macro2::Span::call_site());
            return quote! { #ident };
        }
        let type_str = &param.rust_type;
        match type_str.as_str() {
            "String" => quote! { impl AsRef<str> },
            "i64" => quote! { i64 },
            "i32" => quote! { i32 },
            "f64" => quote! { f64 },
            "bool" => quote! { bool },
            _ => {
                let type_ident = syn::Ident::new(type_str, proc_macro2::Span::call_site());
                quote! { #type_ident }
            }
        }
    }

    /// True when the parameter's compile-time type is `impl AsRef<str>` and
    /// we should call `.as_ref()` on it before stringifying. False for any
    /// $ref-resolved type (T10) or non-String primitive — those just call
    /// `.to_string()`.
    fn param_uses_as_ref_str(param: &crate::analysis::ParameterInfo) -> bool {
        param.schema_ref.is_none() && param.rust_type == "String"
    }

    /// Generate request body serialization based on content type
    /// Emit statements that mutate `req` to apply the request body. Returns
    /// `quote!{}` if the operation has no body. Optional bodies (T11) gate the
    /// application on `Some(_)`; required bodies apply unconditionally.
    fn generate_request_body(&self, op: &OperationInfo) -> TokenStream {
        let Some(rb) = op.request_body.as_ref() else {
            return quote! {};
        };
        use crate::analysis::RequestBodyContent;
        let required = op.request_body_required;
        let (ident, apply): (TokenStream, TokenStream) = match rb {
            RequestBodyContent::Json { .. } => (
                quote! { request },
                quote! {
                    req = req
                        .body(serde_json::to_vec(&request).map_err(HttpError::serialization_error)?)
                        .header("content-type", "application/json");
                },
            ),
            RequestBodyContent::FormUrlEncoded { .. } => (
                quote! { request },
                quote! {
                    req = req
                        .body(serde_urlencoded::to_string(&request).map_err(HttpError::serialization_error)?)
                        .header("content-type", "application/x-www-form-urlencoded");
                },
            ),
            RequestBodyContent::Multipart => (
                quote! { form },
                quote! {
                    req = req.multipart(form);
                },
            ),
            RequestBodyContent::OctetStream => (
                quote! { body },
                quote! {
                    req = req
                        .body(body)
                        .header("content-type", "application/octet-stream");
                },
            ),
            RequestBodyContent::TextPlain => (
                quote! { body },
                quote! {
                    req = req
                        .body(body)
                        .header("content-type", "text/plain");
                },
            ),
        };
        if required {
            apply
        } else {
            quote! {
                if let Some(#ident) = #ident {
                    #apply
                }
            }
        }
    }

    /// Find the success (2xx) response schema name, if any.
    ///
    /// Only considers 2xx status codes. Error schemas (4xx, 5xx) are ignored
    /// so that endpoints like 204 No Content correctly return `()` instead of
    /// accidentally picking up the error schema (e.g. `BadRequestError`).
    fn get_success_response_schema<'a>(&self, op: &'a OperationInfo) -> Option<&'a String> {
        op.response_schemas
            .get("200")
            .or_else(|| op.response_schemas.get("201"))
            .or_else(|| {
                op.response_schemas
                    .iter()
                    .find(|(code, _)| code.starts_with('2'))
                    .map(|(_, v)| v)
            })
    }

    /// Get response type
    fn get_response_type(&self, op: &OperationInfo) -> TokenStream {
        if let Some(response_type) = self.get_success_response_schema(op) {
            // Convert schema name to Rust type name (handles underscores, etc.)
            let rust_type_name = self.to_rust_type_name(response_type);
            let response_ident = syn::Ident::new(&rust_type_name, proc_macro2::Span::call_site());
            quote! { #response_ident }
        } else {
            quote! { () }
        }
    }

    /// Generate error handling.
    ///
    /// Always reads the response body to a string before attempting any typed
    /// deserialization, so the raw body and headers are preserved on the error
    /// path even when JSON parsing fails. On 2xx the body is parsed into the
    /// success type; on non-2xx the body is parsed into the matching variant
    /// of the per-operation error enum (when one is declared) and wrapped in
    /// `ApiError<E>`.
    fn generate_error_handling(&self, op: &OperationInfo, has_response_body: bool) -> TokenStream {
        let op_error_type = self.op_error_type_token(op);

        let success_branch = if has_response_body {
            quote! {
                match serde_json::from_str(&body_text) {
                    Ok(body) => Ok(body),
                    Err(e) => Err(ApiOpError::Api(ApiError {
                        status: status_code,
                        headers: headers,
                        body: body_text,
                        typed: None,
                        parse_error: Some(format!(
                            "failed to deserialize 2xx response body: {}",
                            e
                        )),
                    })),
                }
            }
        } else {
            quote! {
                let _ = body_text;
                let _ = headers;
                Ok(())
            }
        };

        let error_match_arms = self.generate_error_match_arms(op);

        quote! {
            let status = response.status();
            let status_code = status.as_u16();
            let headers = response.headers().clone();
            let body_text = response.text().await
                .map_err(|e| ApiOpError::Transport(HttpError::Network(e)))?;

            if status.is_success() {
                #success_branch
            } else {
                let typed: Option<#op_error_type>;
                let parse_error: Option<String>;
                #error_match_arms
                Err(ApiOpError::Api(ApiError {
                    status: status_code,
                    headers,
                    body: body_text,
                    typed,
                    parse_error,
                }))
            }
        }
    }

    /// Generate the match arms that select which per-op error variant to
    /// deserialize the response body into based on the runtime status code.
    fn generate_error_match_arms(&self, op: &OperationInfo) -> TokenStream {
        let arms: Vec<TokenStream> = op
            .response_schemas
            .iter()
            .filter(|(code, _)| !code.starts_with('2'))
            .filter_map(|(code, schema)| {
                let variant_ident = Self::op_error_variant_ident(code);
                let payload_ty_name = self.to_rust_type_name(schema);
                let payload_ty = syn::Ident::new(&payload_ty_name, proc_macro2::Span::call_site());
                let enum_ident = self.op_error_enum_ident(op);

                // T8: range-keyed responses (1XX/2XX/3XX/4XX/5XX) per OAS
                // 3.x §"Responses Object". Specific codes still take priority
                // (handled by ordering — concrete codes deserialize first
                // because the generic dispatch is a generic `_ if (range)`).
                let pattern = match code.as_str() {
                    "default" | "Default" => return None, // handled in fallback
                    other if other.chars().all(|c| c.is_ascii_digit()) => {
                        let n: u16 = other.parse().ok()?;
                        quote! { #n }
                    }
                    "1XX" | "1xx" => quote! { code if (100..=199).contains(&code) },
                    "2XX" | "2xx" => quote! { code if (200..=299).contains(&code) },
                    "3XX" | "3xx" => quote! { code if (300..=399).contains(&code) },
                    "4XX" | "4xx" => quote! { code if (400..=499).contains(&code) },
                    "5XX" | "5xx" => quote! { code if (500..=599).contains(&code) },
                    _ => return None,
                };

                Some(quote! {
                    #pattern => {
                        match serde_json::from_str::<#payload_ty>(&body_text) {
                            Ok(v) => {
                                typed = Some(#enum_ident::#variant_ident(v));
                                parse_error = None;
                            }
                            Err(e) => {
                                typed = None;
                                parse_error = Some(e.to_string());
                            }
                        }
                    }
                })
            })
            .collect();

        // Fallback for "default" or undeclared status codes: try to parse
        // as `serde_json::Value` for inspectability when the op's error
        // type is generic, otherwise leave typed = None.
        // Must mirror op_error_type_token: if op_error_type is the typed
        // enum (any non-2xx response, including `default`), the fallback arm
        // can't deserialize into `serde_json::Value` because `typed` is the
        // enum. Default to `typed = None` in that case.
        let has_typed_enum = op
            .response_schemas
            .iter()
            .any(|(code, _)| !code.starts_with('2'));

        let default_arm = if has_typed_enum {
            quote! {
                _ => {
                    typed = None;
                    parse_error = None;
                }
            }
        } else {
            // No typed enum — op_error_type is serde_json::Value.
            quote! {
                _ => {
                    match serde_json::from_str::<serde_json::Value>(&body_text) {
                        Ok(v) => {
                            typed = Some(v);
                            parse_error = None;
                        }
                        Err(e) => {
                            typed = None;
                            parse_error = Some(e.to_string());
                        }
                    }
                }
            }
        };

        if arms.is_empty() {
            // No declared status arms — just the fallback.
            quote! {
                match status_code {
                    #default_arm
                }
            }
        } else {
            quote! {
                match status_code {
                    #(#arms)*
                    #default_arm
                }
            }
        }
    }

    /// Generate URL construction with path parameter substitution
    fn generate_url_construction(&self, path: &str, op: &OperationInfo) -> TokenStream {
        // Check if path has parameters (contains {...})
        if path.contains('{') {
            self.generate_url_with_params(path, op)
        } else {
            quote! {
                let request_url = format!("{}{}", self.base_url, #path);
            }
        }
    }

    /// Generate URL with path parameters
    fn generate_url_with_params(&self, path: &str, op: &OperationInfo) -> TokenStream {
        // Find all path parameters in the operation.
        let path_params: Vec<_> = op
            .parameters
            .iter()
            .filter(|p| p.location == "path")
            .collect();

        // T5: percent-encode each path-template variable per RFC3986 §3.3.
        // We build a positional-arg format string by walking the template
        // left-to-right and emitting one `{}` + one format arg per
        // placeholder occurrence. Cloudflare has paths like
        // `/accounts/{account_id}/.../accounts/{account_id}` — the same
        // variable appears twice. A naive `replace_all` produced two `{}`
        // placeholders but only one format arg (E0277). Per-occurrence
        // emission keeps them in sync.
        let mut format_string = String::with_capacity(path.len());
        let mut format_args: Vec<TokenStream> = Vec::new();
        let mut chars = path.chars().peekable();
        while let Some(c) = chars.next() {
            if c != '{' {
                format_string.push(c);
                continue;
            }
            // Read until the matching '}'.
            let mut name = String::new();
            while let Some(&n) = chars.peek() {
                chars.next();
                if n == '}' {
                    break;
                }
                name.push(n);
            }
            // Resolve to a path param. If no match, leave the placeholder
            // verbatim (real-world spec bug — this op shouldn't have made
            // it past analysis).
            let param = path_params.iter().find(|p| p.name == name);
            let Some(param) = param else {
                format_string.push('{');
                format_string.push_str(&name);
                format_string.push('}');
                continue;
            };
            format_string.push_str("{}");
            let param_name_snake = self.param_ident_str(param);
            let param_ident = Self::to_field_ident(&param_name_snake);
            if Self::param_uses_as_ref_str(param) {
                format_args.push(quote! {
                    __pct_encode_path_segment(#param_ident.as_ref())
                });
            } else {
                format_args.push(quote! {
                    __pct_encode_path_segment(&#param_ident.to_string())
                });
            }
        }

        if format_args.is_empty() {
            quote! {
                let request_url = format!("{}{}", self.base_url, #path);
            }
        } else {
            quote! {
                let request_url = format!("{}{}", self.base_url, format!(#format_string, #(#format_args),*));
            }
        }
    }

    /// Resolve the Rust ident for a parameter. Prefers the disambiguated
    /// `rust_ident` set by the analyzer (which dedupes across the whole
    /// operation), falling back to a fresh sanitize of the wire name when
    /// no analyzer-side ident is present.
    fn param_ident_str(&self, param: &crate::analysis::ParameterInfo) -> String {
        if let Some(ident) = &param.rust_ident {
            // Apply the keyword-escape and self/super/crate dance the
            // sanitize fn does. The analyzer's base ident is already the
            // snake/kebab-aware shape; we only need post-processing.
            return self.escape_keyword_ident(ident);
        }
        self.sanitize_param_name(&param.name)
    }

    fn escape_keyword_ident(&self, snake_case: &str) -> String {
        if matches!(snake_case, "self" | "super" | "crate" | "Self") {
            return format!("{snake_case}_param");
        }
        if Self::is_rust_keyword(snake_case) {
            format!("r#{snake_case}")
        } else {
            snake_case.to_string()
        }
    }

    /// Sanitize a parameter name by escaping Rust reserved keywords with raw
    /// identifiers and disambiguating Twilio-style suffix operators
    /// (`StartTime`, `StartTime<`, `StartTime>` would otherwise all snake-
    /// case to `start_time`).
    fn sanitize_param_name(&self, name: &str) -> String {
        // Disambiguate before stripping. `<`, `>`, `<=`, `>=` are common in
        // filter-style query params; map them to `_lt` / `_gt` etc. so the
        // Rust ident is unique while the wire-level param name stays the
        // original string elsewhere in the codegen.
        let suffix = if name.ends_with("<=") {
            "_lte"
        } else if name.ends_with(">=") {
            "_gte"
        } else if name.ends_with('<') {
            "_lt"
        } else if name.ends_with('>') {
            "_gt"
        } else {
            ""
        };
        let stripped = name.trim_end_matches(['<', '>', '=']);
        let mut snake_case = stripped.to_snake_case();
        snake_case.push_str(suffix);

        if matches!(snake_case.as_str(), "self" | "super" | "crate" | "Self") {
            return format!("{snake_case}_param");
        }
        if Self::is_rust_keyword(&snake_case) {
            format!("r#{snake_case}")
        } else {
            snake_case
        }
    }
}