server-less-macros 0.6.0

Proc macros for server-less
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
//! HTTP handler generation macro.
//!
//! Generates axum HTTP handlers from impl blocks using convention-based routing.
//!
//! # Method Naming Conventions
//!
//! HTTP methods are inferred from function name prefixes:
//! - `get_*`, `fetch_*`, `read_*`, `list_*`, `find_*`, `search_*` → GET
//! - `create_*`, `add_*`, `new_*` → POST
//! - `update_*`, `set_*` → PUT
//! - `patch_*`, `modify_*` → PATCH
//! - `delete_*`, `remove_*` → DELETE
//!
//! # Path Generation
//!
//! Paths are derived from method names:
//! - `create_user` → `POST /users`
//! - `get_user` → `GET /users/{id}` (requires id parameter)
//! - `list_users` → `GET /users`
//! - `update_user` → `PUT /users/{id}`
//!
//! # Parameter Binding
//!
//! Parameters are automatically bound based on HTTP method:
//! - GET: Path parameters (`:id`) and query parameters (`?name=value`)
//! - POST/PUT/PATCH: JSON request body
//!
//! # Context Injection
//!
//! Methods can receive a `Context` parameter to access request metadata:
//!
//! ```ignore
//! use server_less::{http, Context};
//!
//! #[http]
//! impl UserService {
//!     async fn create_user(&self, ctx: Context, name: String) -> Result<User> {
//!         // Access request metadata
//!         let user_id = ctx.user_id()?;           // Authenticated user
//!         let request_id = ctx.request_id()?;     // Request trace ID
//!         let auth_header = ctx.authorization();   // Authorization header
//!
//!         // Create user...
//!     }
//! }
//! ```
//!
//! **Context is automatically injected and populated from HTTP headers:**
//! - All headers are available via `ctx.header("name")`
//! - `x-request-id` header → `ctx.request_id()`
//! - Custom headers can be accessed via `ctx.get("key")`
//!
//! **Context does NOT appear in the OpenAPI spec** - it's injected by the framework,
//! not provided by API consumers.
//!
//! ## Name Collision Handling
//!
//! If you have your own `Context` type, use one of these strategies:
//!
//! **Strategy 1: Qualify the server-less Context (recommended)**
//! ```ignore
//! struct Context { /* your type */ }
//!
//! #[http]
//! impl MyService {
//!     // Uses server-less Context (injected)
//!     fn api_endpoint(&self, ctx: server_less::Context) { }
//!
//!     // Uses your Context (not injected, treated as body param)
//!     fn internal(&self, ctx: Context) { }
//! }
//! ```
//!
//! **Strategy 2: Rename your Context type**
//! ```ignore
//! struct AppContext { /* your type */ }
//!
//! #[http]
//! impl MyService {
//!     fn handler(&self, ctx: Context) { }  // ✅ server-less Context injected
//! }
//! ```
//!
//! **Detection Logic:**
//! - If ANY method uses `server_less::Context`, bare `Context` is assumed to be YOUR type
//! - If NO method uses qualified form, bare `Context` is assumed to be server-less
//!
//! This gives you explicit control without needing configuration flags.
//!
//! # Streaming Support (SSE)
//!
//! Return `impl Stream<Item = T>` to enable Server-Sent Events:
//!
//! ```ignore
//! use futures::stream::Stream;
//!
//! #[http]
//! impl Service {
//!     // SSE streaming endpoint
//!     // IMPORTANT: Rust 2024 requires `+ use<>` syntax
//!     fn stream_data(&self, count: u32) -> impl Stream<Item = Event> + use<> {
//!         // Returns SSE stream
//!     }
//! }
//! ```
//!
//! **Rust 2024 Edition Note:** When using `impl Trait` in return position with
//! streams, you must add `+ use<>` to capture all generic parameters. This is
//! required by Rust 2024's stricter capture rules for opaque types.
//!
//! # Generated Methods
//!
//! - `http_router() -> axum::Router` - Complete router with all endpoints
//! - `http_openapi_paths() -> Vec<OpenApiPath>` - OpenAPI path fragments for composition
//! - `http_openapi_spec() -> serde_json::Value` - Full OpenAPI 3.0 spec (unless `openapi = false`)
//!
//! # Example
//!
//! ```ignore
//! use server_less::http;
//!
//! #[derive(Clone)]
//! struct UserService;
//!
//! #[http]
//! impl UserService {
//!     /// Create a new user
//!     async fn create_user(&self, name: String, email: String) -> User {
//!         // POST /users with JSON body
//!     }
//!
//!     /// Get user by ID
//!     async fn get_user(&self, id: String) -> Option<User> {
//!         // GET /users/{id}
//!     }
//!
//!     /// List all users
//!     async fn list_users(&self) -> Vec<User> {
//!         // GET /users
//!     }
//! }
//!
//! // Use it:
//! let service = UserService;
//! let app = service.http_router();
//! ```

use heck::ToSnakeCase;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use server_less_parse::{MethodInfo, extract_methods, get_impl_name, partition_methods};
use syn::{GenericArgument, ItemImpl, PathArguments, Token, Type, parse::Parse};

use crate::app::extract_app_meta;
use crate::server_attrs::{has_server_hidden, has_server_skip, validate_server_attrs};

// Import Context helpers
use crate::context::{generate_http_context_extraction, partition_context_params};

use server_less_parse::HttpMethod;

use crate::openapi_gen::{ResponseOverride, RouteOverride, infer_http_method, infer_path};

/// Extract the inner type T from Option<T>
fn extract_option_inner(ty: &Type) -> Option<Type> {
    if let Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && segment.ident == "Option"
        && let PathArguments::AngleBracketed(args) = &segment.arguments
        && let Some(GenericArgument::Type(inner)) = args.args.first()
    {
        return Some(inner.clone());
    }
    None
}

/// Arguments for the #[http] attribute
#[derive(Default)]
pub(crate) struct HttpArgs {
    pub prefix: Option<String>,
    /// Whether to generate OpenAPI spec (default: true)
    pub openapi: Option<bool>,
    /// Application name (used as OpenAPI info.title, overrides struct name)
    pub name: Option<String>,
    /// Human-readable description (used as OpenAPI info.description)
    pub description: Option<String>,
    /// Application version (used as OpenAPI info.version, defaults to CARGO_PKG_VERSION)
    pub version: Option<String>,
    /// Homepage URL (used as OpenAPI info.contact.url)
    pub homepage: Option<String>,
    /// Whether to emit debug logging in generated handlers (default: false).
    /// When true, each handler emits `eprintln!` lines before and after the
    /// method call. Set on the impl block to enable for all methods, or on a
    /// specific method via `#[http(debug = true)]`.
    pub debug: bool,
    /// Whether to emit per-parameter trace logging in generated handlers (default: false).
    /// When true, each handler emits an `eprintln!` line after each parameter is extracted,
    /// showing the parameter name and its `{:?}` value. Set on the impl block to enable for
    /// all methods, or on a specific method via `#[http(trace = true)]`.
    pub trace: bool,
}

impl Parse for HttpArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = HttpArgs::default();

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;

            match ident.to_string().as_str() {
                "prefix" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.prefix = Some(lit.value());
                }
                "openapi" => {
                    if input.peek(Token![=]) {
                        input.parse::<Token![=]>()?;
                        let lit: syn::LitBool = input.parse()?;
                        args.openapi = Some(lit.value());
                    } else {
                        // Bare `openapi` means enable
                        args.openapi = Some(true);
                    }
                }
                "debug" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitBool = input.parse()?;
                    args.debug = lit.value();
                }
                "trace" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitBool = input.parse()?;
                    args.trace = lit.value();
                }
                "name" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.name = Some(lit.value());
                }
                "description" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.description = Some(lit.value());
                }
                "version" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.version = Some(lit.value());
                }
                "homepage" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.homepage = Some(lit.value());
                }
                other => {
                    const VALID: &[&str] =
                        &["prefix", "openapi", "name", "description", "version", "homepage", "debug", "trace"];
                    let suggestion = crate::did_you_mean(other, VALID)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    return Err(syn::Error::new(
                        ident.span(),
                        format!(
                            "unknown argument `{other}`{suggestion}\n\
                             Valid arguments: prefix, openapi, name, description, version, homepage, debug, trace\n\
                             Examples:\n\
                             - #[http(prefix = \"/api/v1\")]\n\
                             - #[http(openapi = false)]\n\
                             - #[http(name = \"My API\", description = \"Does the thing\")]\n\
                             - #[http(debug = true)]\n\
                             \n\
                             Related: #[serve] (multi-protocol), #[openapi] (standalone API docs), #[server] (blessed preset)"
                        ),
                    ));
                }
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(args)
    }
}

/// Strip `#[param]`, `#[route]`, `#[response]`, and per-method `#[http]` attributes
/// from the impl block before re-emitting it, so rustc does not encounter unknown
/// or macro attributes on function parameters / methods in the generated output.
fn strip_http_attrs(impl_block: &ItemImpl) -> ItemImpl {
    let mut block = impl_block.clone();
    for item in &mut block.items {
        if let syn::ImplItem::Fn(method) = item {
            // Strip method-level HTTP attributes (route, response, and per-method http).
            method.attrs.retain(|attr| {
                !attr.path().is_ident("route")
                    && !attr.path().is_ident("response")
                    && !attr.path().is_ident("http")
            });
            // Strip #[param(...)] from function parameters.
            for input in &mut method.sig.inputs {
                if let syn::FnArg::Typed(pat_type) = input {
                    pat_type.attrs.retain(|attr| !attr.path().is_ident("param"));
                }
            }
        }
    }
    block
}

pub(crate) fn expand_http(args: HttpArgs, mut impl_block: ItemImpl) -> syn::Result<TokenStream2> {
    crate::reject_generic_impl(&impl_block)?;
    let app_meta = extract_app_meta(&mut impl_block.attrs);
    let args = HttpArgs {
        name: args.name.or(app_meta.name),
        description: args.description.or(app_meta.description),
        version: args.version.or_else(|| app_meta.version.into_explicit()),
        homepage: args.homepage.or(app_meta.homepage),
        ..args
    };

    let struct_name = get_impl_name(&impl_block)?;
    let (impl_generics, _ty_generics, where_clause) = impl_block.generics.split_for_impl();
    let self_ty = &impl_block.self_ty;
    let methods = extract_methods(&impl_block)?;

    let prefix = args.prefix.unwrap_or_default();
    let generate_openapi = args.openapi.unwrap_or(true);
    let impl_debug = args.debug;
    let impl_trace = args.trace;
    let openapi_title = args.name.unwrap_or_else(|| struct_name.to_string());
    let openapi_version = match args.version {
        Some(ref v) => quote! { #v },
        None => quote! { ::std::env!("CARGO_PKG_VERSION") },
    };
    let openapi_description_entry = match args.description {
        Some(ref d) => quote! { , "description": #d },
        None => quote! {},
    };
    let openapi_contact_entry = match args.homepage {
        Some(ref hp) => quote! { , "contact": { "url": #hp } },
        None => quote! {},
    };

    for m in &methods {
        validate_server_attrs(m)?;
    }
    let partitioned = partition_methods(&methods, has_server_skip);

    // Generate mount routes (static mounts only)
    let mut mount_routes = Vec::new();
    let mut mount_openapi_calls = Vec::new();
    for mount in &partitioned.static_mounts {
        let mount_name = mount.wire_name_or(|n| n);
        let mount_path = format!("/{}", mount_name);
        let method_name = &mount.name;
        let inner_ty = mount.return_info.reference_inner.as_ref().ok_or_else(|| {
            syn::Error::new_spanned(
                &mount.method.sig,
                "BUG: mount method must have a reference return type (&T)",
            )
        })?;

        mount_routes.push(quote! {
            .nest_service(#mount_path, <#inner_ty as ::server_less::HttpMount>::http_mount_router(
                ::std::sync::Arc::new(state.#method_name().clone())
            ))
        });

        // Collect child OpenAPI paths prefixed with the mount path.
        mount_openapi_calls.push(quote! {
            for mut child_path in <#inner_ty as ::server_less::HttpMount>::http_mount_openapi_paths() {
                child_path.path = format!("{}{}", #mount_path, child_path.path);
                paths.push(child_path);
            }
        });
    }

    let mut handlers = Vec::new();
    let mut routes = Vec::new();
    let mut openapi_methods = Vec::new();
    let mut route_docs: Vec<String> = Vec::new();
    // Maps normalized route signature (e.g., "GET /users/{*}") to (method_name, original_path)
    let mut route_signatures: std::collections::HashMap<String, (String, String)> =
        std::collections::HashMap::new();

    for method in &partitioned.leaf {
        let overrides = RouteOverride::parse_from_attrs(&method.method.attrs)?;
        let response_overrides = ResponseOverride::parse_from_attrs(&method.method.attrs)?;

        if overrides.skip {
            continue;
        }

        // Check for duplicate routes
        let http_method_enum = if let Some(ref m) = overrides.method {
            match m.as_str() {
                "GET" => HttpMethod::Get,
                "POST" => HttpMethod::Post,
                "PUT" => HttpMethod::Put,
                "PATCH" => HttpMethod::Patch,
                "DELETE" => HttpMethod::Delete,
                other => {
                    let span = overrides.method_span.unwrap_or_else(|| method.name.span());
                    const SUPPORTED: &[&str] = &["GET", "POST", "PUT", "PATCH", "DELETE"];
                    let suggestion = crate::did_you_mean(other, SUPPORTED)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    return Err(syn::Error::new(
                        span,
                        format!(
                            "unknown HTTP method `{other}`{suggestion}\n\
                             \n\
                             Supported methods: GET, POST, PUT, PATCH, DELETE\n\
                             \n\
                             Hint: Use one of the supported verbs, e.g., #[route(method = \"POST\")]"
                        ),
                    ));
                }
            }
        } else {
            infer_http_method(&method.name_str())
        };

        let path = if let Some(ref p) = overrides.path {
            p.clone()
        } else {
            infer_path(&method.name_str(), &http_method_enum, &method.params)
        };
        let full_path = format!("{}{}", prefix, path);

        // Normalize path for duplicate detection (e.g., /users/{id} and /users/{user_id} are the same)
        let normalized_path = normalize_path_for_duplicate_check(&full_path);
        let route_sig = format!("{} {}", http_method_enum.as_str(), normalized_path);

        if let Some((existing_method, existing_path)) = route_signatures.get(&route_sig) {
            let hint_msg = if existing_path != &full_path {
                format!(
                    "Duplicate route: {} {} is structurally identical to {} defined by method '{}'\n\
                     \n\
                     Note: These paths have the same structure (different parameter names don't matter):\n\
                     - Method '{}': {}\n\
                     - Method '{}': {}\n\
                     \n\
                     Hint: You can either:\n\
                     1. Use #[route(skip)] to exclude one method from HTTP routing\n\
                     2. Use #[route(path = \"/custom\")] to use a completely different path\n\
                     3. Use #[route(method = \"PATCH\")] to use a different HTTP method",
                    http_method_enum.as_str(),
                    full_path,
                    existing_path,
                    existing_method,
                    existing_method,
                    existing_path,
                    method.name,
                    full_path
                )
            } else {
                format!(
                    "Duplicate route: {} {} is already defined by method '{}'\n\
                     \n\
                     Hint: You can either:\n\
                     1. Use #[route(skip)] to exclude this method from HTTP routing\n\
                     2. Use #[route(path = \"/custom\")] to use a different path\n\
                     3. Use #[route(method = \"PATCH\")] to use a different HTTP method",
                    http_method_enum.as_str(),
                    full_path,
                    existing_method
                )
            };

            return Err(syn::Error::new_spanned(&method.method.sig, hint_msg));
        }
        route_signatures.insert(
            route_sig.clone(),
            (method.name_str(), full_path.clone()),
        );
        route_docs.push(format!("- `{}`", route_sig));

        // Per-method debug flag: method-level `#[http(debug = true)]` OR impl-level flag.
        let method_debug = impl_debug || has_http_debug(method);
        // Per-method trace flag: method-level `#[http(trace = true)]` OR impl-level flag.
        let method_trace = impl_trace || has_http_trace(method);
        let cfg_attrs = &method.cfg_attrs;
        let raw_handler = generate_handler(&struct_name, self_ty, method, &response_overrides, method_debug, method_trace)?;
        handlers.push(quote! {
            #(#cfg_attrs)*
            #raw_handler
        });

        let raw_route = generate_route(&prefix, method, &overrides, &struct_name)?;
        // Emit as a rebinding statement so #[cfg] can be applied per-route.
        routes.push(quote! {
            #(#cfg_attrs)*
            let router = router #raw_route;
        });

        // Always collect for http_openapi_paths() (used by #[openapi] and #[serve])
        // Exclude from OpenAPI if hidden via #[route(hidden)] or #[server(hidden)]
        if !overrides.hidden && !has_server_hidden(method) {
            openapi_methods.push((
                (*method).clone(),
                overrides.clone(),
                response_overrides.clone(),
            ));
        }
    }

    // Build route documentation
    let router_doc = if route_docs.is_empty() {
        "Create an axum Router for this service.".to_string()
    } else {
        format!(
            "Create an axum Router for this service.\n\n# Routes\n\n{}",
            route_docs.join("\n")
        )
    };

    // Generate OpenAPI paths method (always available for composition)
    let openapi_paths_fn =
        crate::openapi_gen::generate_openapi_paths(&prefix, &openapi_methods)?;
    let openapi_paths_doc = format!(
        "Get OpenAPI paths for this service ({} route{}).",
        route_docs.len(),
        if route_docs.len() == 1 { "" } else { "s" }
    );
    let openapi_paths_method = quote! {
        #[doc = #openapi_paths_doc]
        pub fn http_openapi_paths() -> ::std::vec::Vec<::server_less::OpenApiPath> {
            let mut paths = #openapi_paths_fn;
            #(#mount_openapi_calls)*
            paths
        }
    };

    // Conditionally generate OpenAPI spec method.
    // Builds from http_openapi_paths() so mounted child paths are automatically included.
    let openapi_method = if generate_openapi {
        let openapi_doc = "Get HTTP-only OpenAPI 3.0 specification for this service.\n\n\
             Includes all paths (own + mounted children). Use `http_openapi_paths()` for composable path fragments.\n\
             For multi-protocol specs, use the `openapi_spec()` method generated by `#[serve]` or `#[openapi]`.";
        quote! {
            #[doc = #openapi_doc]
            pub fn http_openapi_spec() -> ::server_less::serde_json::Value {
                let mut paths = ::server_less::serde_json::Map::new();
                for path_info in Self::http_openapi_paths() {
                    let path_item = paths.entry(path_info.path.clone())
                        .or_insert_with(|| ::server_less::serde_json::json!({}));
                    if let Some(map) = path_item.as_object_mut() {
                        let op = ::server_less::serde_json::to_value(&path_info.operation)
                            .expect("BUG: OpenApiOperation must be serializable");
                        map.insert(path_info.method.clone(), op);
                    }
                }
                ::server_less::serde_json::json!({
                    "openapi": "3.0.0",
                    "info": {
                        "title": #openapi_title,
                        "version": #openapi_version
                        #openapi_description_entry
                        #openapi_contact_entry
                    },
                    "paths": paths
                })
            }
        }
    } else {
        quote! {}
    };

    let clean_impl = if crate::is_protocol_impl_emitter(&impl_block, "http") {
        let stripped = strip_http_attrs(&impl_block);
        quote! { #stripped }
    } else {
        quote! {}
    };

    Ok(quote! {
        #clean_impl

        impl #impl_generics ::server_less::HttpMount for #self_ty #where_clause {
            fn http_mount_router(self: ::std::sync::Arc<Self>) -> ::server_less::axum::Router {
                use ::server_less::axum::routing::{get, post, put, patch, delete};

                let state = self;
                let router = ::server_less::axum::Router::new();
                #(#routes)*
                let router = router
                    #(#mount_routes)*
                    .with_state(state);
                router
            }

            fn http_mount_openapi_paths() -> Vec<::server_less::OpenApiPath> {
                Self::http_openapi_paths()
            }
        }

        impl #impl_generics #self_ty #where_clause {
            #[doc = #router_doc]
            pub fn http_router(self) -> ::server_less::axum::Router
            where
                Self: Clone + Send + Sync + 'static,
            {
                use ::server_less::axum::routing::{get, post, put, patch, delete};

                let state = ::std::sync::Arc::new(self);
                let router = ::server_less::axum::Router::new();
                #(#routes)*
                let router = router
                    #(#mount_routes)*
                    .with_state(state);
                router
            }

            #openapi_paths_method

            #openapi_method
        }

        #(#handlers)*
    })
}

fn generate_handler(
    struct_name: &syn::Ident,
    self_ty: &syn::Type,
    method: &MethodInfo,
    response_overrides: &ResponseOverride,
    debug: bool,
    trace: bool,
) -> syn::Result<TokenStream2> {
    let method_name = &method.name;
    // NOTE: to_snake_case can produce collisions for structs that differ only in
    // separator style (e.g. `UserService` and `User_Service` both → `user_service`).
    let struct_name_snake = struct_name.to_string().to_snake_case();
    let handler_name = format_ident!("__server_less_http_{}_{}", struct_name_snake, method_name);
    let method_name_str = method_name.to_string();

    let (param_extractions, param_pre_stmts, param_calls, param_names) =
        generate_param_handling(method)?;

    // When tracing is enabled, bind each user-visible parameter to a named local variable
    // (`__sl_param_{name}`) so we can log its value immediately after extraction.
    let (call, param_trace_stmts) = if trace {
        let mut trace_stmts: Vec<proc_macro2::TokenStream> = Vec::new();
        let mut bound_calls: Vec<proc_macro2::TokenStream> = Vec::new();

        for (call_expr, maybe_name) in param_calls.iter().zip(param_names.iter()) {
            if let Some(name) = maybe_name {
                let var_ident = format_ident!("__sl_param_{}", name);
                let name_str = name.as_str();
                trace_stmts.push(quote! {
                    let #var_ident = #call_expr;
                    eprintln!("[server-less] trace: param `{}` = {:?}", #name_str, #var_ident);
                });
                bound_calls.push(quote! { #var_ident });
            } else {
                // Context or other injected params: use inline expression, no trace line.
                bound_calls.push(call_expr.clone());
            }
        }

        let method_call = if method.is_async {
            quote! { state.#method_name(#(#bound_calls),*).await }
        } else {
            quote! { state.#method_name(#(#bound_calls),*) }
        };

        (method_call, trace_stmts)
    } else {
        let method_call = if method.is_async {
            quote! { state.#method_name(#(#param_calls),*).await }
        } else {
            quote! { state.#method_name(#(#param_calls),*) }
        };
        (method_call, Vec::new())
    };

    let response = generate_response_handling(method, &call, response_overrides)?;

    // When pre_stmts exist they contain early returns of type `Response<Body>`, so the final
    // expression must also return that same concrete type — otherwise Rust's type checker rejects
    // the `impl IntoResponse` return as having two different concrete types.
    let response = if !param_pre_stmts.is_empty() {
        quote! { {
            use ::server_less::axum::response::IntoResponse as _;
            (#response).into_response()
        }}
    } else {
        response
    };

    let handler = if debug {
        quote! {
            async fn #handler_name(
                state_extractor: ::server_less::axum::extract::State<::std::sync::Arc<#self_ty>>,
                #(#param_extractions),*
            ) -> impl ::server_less::axum::response::IntoResponse {
                let state = state_extractor.0;
                eprintln!("[server-less] {} called", #method_name_str);
                #(#param_pre_stmts)*
                #(#param_trace_stmts)*
                let __sl_response = #response;
                eprintln!("[server-less] {} returned", #method_name_str);
                __sl_response
            }
        }
    } else if trace {
        quote! {
            async fn #handler_name(
                state_extractor: ::server_less::axum::extract::State<::std::sync::Arc<#self_ty>>,
                #(#param_extractions),*
            ) -> impl ::server_less::axum::response::IntoResponse {
                let state = state_extractor.0;
                #(#param_pre_stmts)*
                #(#param_trace_stmts)*
                #response
            }
        }
    } else {
        quote! {
            async fn #handler_name(
                state_extractor: ::server_less::axum::extract::State<::std::sync::Arc<#self_ty>>,
                #(#param_extractions),*
            ) -> impl ::server_less::axum::response::IntoResponse {
                let state = state_extractor.0;
                #(#param_pre_stmts)*
                #response
            }
        }
    };

    Ok(handler)
}

/// Returns `true` if the method has `#[http(debug = true)]` on it directly.
fn has_http_debug(method: &MethodInfo) -> bool {
    for attr in &method.method.attrs {
        if attr.path().is_ident("http") {
            let mut found = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("debug") {
                    if meta.input.peek(syn::Token![=]) {
                        let value: syn::LitBool = meta.value()?.parse()?;
                        if value.value() {
                            found = true;
                        }
                    } else {
                        found = true;
                    }
                } else if meta.input.peek(syn::Token![=]) {
                    // Consume other key = value pairs to avoid parse errors.
                    let _: proc_macro2::TokenStream = meta.value()?.parse()?;
                }
                Ok(())
            });
            if found {
                return true;
            }
        }
    }
    false
}

/// Returns `true` if the method has `#[http(trace = true)]` on it directly.
fn has_http_trace(method: &MethodInfo) -> bool {
    for attr in &method.method.attrs {
        if attr.path().is_ident("http") {
            let mut found = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("trace") {
                    if meta.input.peek(syn::Token![=]) {
                        let value: syn::LitBool = meta.value()?.parse()?;
                        if value.value() {
                            found = true;
                        }
                    } else {
                        found = true;
                    }
                } else if meta.input.peek(syn::Token![=]) {
                    // Consume other key = value pairs to avoid parse errors.
                    let _: proc_macro2::TokenStream = meta.value()?.parse()?;
                }
                Ok(())
            });
            if found {
                return true;
            }
        }
    }
    false
}

#[allow(clippy::type_complexity)]
fn generate_param_handling(
    method: &MethodInfo,
) -> syn::Result<(Vec<TokenStream2>, Vec<TokenStream2>, Vec<TokenStream2>, Vec<Option<String>>)> {
    use server_less_parse::ParamLocation;

    let mut extractions = Vec::new();
    let mut pre_stmts = Vec::new();
    let mut calls = Vec::new();
    // Parallel to `calls`: None for injected params (Context), Some(name) for user-visible params.
    let mut param_names: Vec<Option<String>> = Vec::new();

    let http_method = infer_http_method(&method.name_str());
    let default_has_body = matches!(
        http_method,
        HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch
    );

    // Partition Context vs regular parameters
    let (context_param, regular_params) = partition_context_params(&method.params)?;

    // Generate Context extraction (if needed)
    if context_param.is_some() {
        let (extraction, call) = generate_http_context_extraction();
        extractions.push(extraction);
        calls.push(call);
        param_names.push(None); // Context is injected; not user-visible for tracing
    }

    // Group regular parameters by their actual location (respecting overrides)
    let mut path_params = Vec::new();
    let mut query_params = Vec::new();
    let mut body_params = Vec::new();
    let mut header_params = Vec::new();

    for param in regular_params {
        match param.location.as_ref() {
            Some(ParamLocation::Path) => path_params.push(param),
            Some(ParamLocation::Query) => query_params.push(param),
            Some(ParamLocation::Body) => body_params.push(param),
            Some(ParamLocation::Header) => header_params.push(param),
            None => {
                // Infer location based on conventions
                if param.is_id {
                    path_params.push(param);
                } else if default_has_body {
                    body_params.push(param);
                } else {
                    query_params.push(param);
                }
            }
        }
    }

    // Generate path parameter extraction.
    // Axum only allows a single `Path` extractor per handler. For a single path
    // param we use `Path<T>` directly; for multiple we use a `Path<(T1, T2, ...)>`
    // tuple extractor and destructure it in the handler body.
    if path_params.len() == 1 {
        let param = &path_params[0];
        let ty = &param.ty;
        let var_ident = format_ident!("__sl_path_{}", param.name_str());
        extractions.push(quote! {
            #var_ident: ::server_less::axum::extract::Path<#ty>
        });
        calls.push(quote! { #var_ident.0 });
        param_names.push(Some(param.name_str()));
    } else if path_params.len() > 1 {
        let types: Vec<_> = path_params.iter().map(|p| &p.ty).collect();
        extractions.push(quote! {
            __sl_path_tuple: ::server_less::axum::extract::Path<(#(#types),*)>
        });
        // Destructure the tuple into individual bindings so they can be referenced
        // by name in the method call below.
        let var_idents: Vec<_> = path_params
            .iter()
            .map(|p| format_ident!("__sl_path_{}", p.name_str()))
            .collect();
        let indices: Vec<syn::Index> = (0..path_params.len()).map(syn::Index::from).collect();
        pre_stmts.push(quote! {
            #(let #var_idents = __sl_path_tuple.0.#indices;)*
        });
        for (param, var) in path_params.iter().zip(var_idents.iter()) {
            calls.push(quote! { #var });
            param_names.push(Some(param.name_str()));
        }
    }

    // Generate body parameter extraction
    if !body_params.is_empty() {
        extractions.push(quote! {
            body_extractor: ::server_less::axum::extract::Json<::server_less::serde_json::Value>
        });

        // Collect known body field names for unknown-field warnings
        let body_known_names: Vec<String> = body_params
            .iter()
            .map(|p| p.wire_name.clone().unwrap_or_else(|| p.name_str()))
            .collect();
        let body_known_strs: Vec<&str> = body_known_names.iter().map(|s| s.as_str()).collect();
        let body_expected_str = body_known_strs.join(", ");
        pre_stmts.push(quote! {
            // Warn on unknown body fields (known at compile time)
            if let ::std::option::Option::Some(obj) = body_extractor.0.as_object() {
                for key in obj.keys() {
                    if ![#(#body_known_strs),*].contains(&key.as_str()) {
                        eprintln!(
                            "[server-less] warning: unknown body field `{}` (expected: {})",
                            key, #body_expected_str
                        );
                    }
                }
            }
        });

        for param in &body_params {
            // Use wire_name if provided, otherwise use the parameter name
            let name_str = param
                .wire_name
                .clone()
                .unwrap_or_else(|| param.name_str());
            let ty = &param.ty;
            if param.is_optional {
                let inner_ty = extract_option_inner(ty).unwrap_or_else(|| ty.clone());
                let inner_ty_str = quote!(#inner_ty).to_string().replace(" ", "");
                let var_ident = format_ident!("__sl_opt_{}", param.name_str());
                pre_stmts.push(quote! {
                    let #var_ident: ::std::option::Option<#inner_ty> = match body_extractor.0.get(#name_str) {
                        ::std::option::Option::None => ::std::option::Option::None,
                        ::std::option::Option::Some(v) => match ::server_less::serde_json::from_value::<#inner_ty>(v.clone()) {
                            ::std::result::Result::Ok(val) => ::std::option::Option::Some(val),
                            ::std::result::Result::Err(_) => {
                                use ::server_less::axum::response::IntoResponse as _;
                                return (
                                    ::server_less::axum::http::StatusCode::BAD_REQUEST,
                                    format!("Optional body field '{}' has invalid value (expected {})", #name_str, #inner_ty_str),
                                ).into_response();
                            }
                        }
                    };
                });
                calls.push(quote! { #var_ident });
            } else {
                let ty_str = quote!(#ty).to_string().replace(" ", "");
                let var_ident = format_ident!("__sl_req_{}", param.name_str());
                pre_stmts.push(quote! {
                    let #var_ident: #ty = match body_extractor.0.get(#name_str)
                        .and_then(|v| ::server_less::serde_json::from_value::<#ty>(v.clone()).ok())
                    {
                        ::std::option::Option::Some(v) => v,
                        ::std::option::Option::None => {
                            use ::server_less::axum::response::IntoResponse as _;
                            return (
                                ::server_less::axum::http::StatusCode::BAD_REQUEST,
                                format!("Request body field '{}' is required (expected {})", #name_str, #ty_str),
                            ).into_response();
                        }
                    };
                });
                calls.push(quote! { #var_ident });
            }
            param_names.push(Some(param.name_str()));
        }
    }

    // Generate query parameter extraction
    if !query_params.is_empty() {
        extractions.push(quote! {
            query_extractor: ::server_less::axum::extract::Query<::std::collections::HashMap<String, String>>
        });

        // Collect known query param names for unknown-param warnings
        let query_known_names: Vec<String> = query_params
            .iter()
            .map(|p| p.wire_name.clone().unwrap_or_else(|| p.name_str()))
            .collect();
        let query_known_strs: Vec<&str> = query_known_names.iter().map(|s| s.as_str()).collect();
        let query_expected_str = query_known_strs.join(", ");
        pre_stmts.push(quote! {
            // Warn on unknown query params (known at compile time)
            for key in query_extractor.0.keys() {
                if ![#(#query_known_strs),*].contains(&key.as_str()) {
                    eprintln!(
                        "[server-less] warning: unknown query parameter `{}` (expected: {})",
                        key, #query_expected_str
                    );
                }
            }
        });

        for param in &query_params {
            // Use wire_name if provided, otherwise use the parameter name
            let name_str = param
                .wire_name
                .clone()
                .unwrap_or_else(|| param.name_str());
            let ty = &param.ty;

            // Handle default values
            if param.is_optional {
                let inner_ty = extract_option_inner(ty).unwrap_or_else(|| ty.clone());
                let inner_ty_str = quote!(#inner_ty).to_string().replace(" ", "");
                let var_ident = format_ident!("__sl_opt_{}", param.name_str());
                pre_stmts.push(quote! {
                    let #var_ident: ::std::option::Option<#inner_ty> = match query_extractor.0.get(#name_str) {
                        ::std::option::Option::None => ::std::option::Option::None,
                        ::std::option::Option::Some(v) => match v.parse::<#inner_ty>() {
                            ::std::result::Result::Ok(val) => ::std::option::Option::Some(val),
                            ::std::result::Result::Err(_) => {
                                use ::server_less::axum::response::IntoResponse as _;
                                return (
                                    ::server_less::axum::http::StatusCode::BAD_REQUEST,
                                    format!("Optional query parameter '{}' has invalid value (expected {})", #name_str, #inner_ty_str),
                                ).into_response();
                            }
                        }
                    };
                });
                calls.push(quote! { #var_ident });
            } else if let Some(ref default_val) = param.default_value {
                // Parse the default value at compile time
                let default_expr: proc_macro2::TokenStream = default_val.parse().map_err(|_| {
                    syn::Error::new(
                        method.name.span(),
                        format!(
                            "failed to parse default value `{}` as a Rust expression\n\
                                 \n\
                                 Hint: Default values must be valid Rust expressions, e.g., \
                                 #[param(default = 0)] or #[param(default = \"hello\")]",
                            default_val
                        ),
                    )
                })?;
                calls.push(quote! {
                    query_extractor.0.get(#name_str)
                        .and_then(|v| v.parse::<#ty>().ok())
                        .unwrap_or(#default_expr)
                });
            } else {
                let ty_str = quote!(#ty).to_string().replace(" ", "");
                let var_ident = format_ident!("__sl_req_{}", param.name_str());
                pre_stmts.push(quote! {
                    let #var_ident: #ty = match query_extractor.0.get(#name_str)
                        .and_then(|v| v.parse::<#ty>().ok())
                    {
                        ::std::option::Option::Some(v) => v,
                        ::std::option::Option::None => {
                            use ::server_less::axum::response::IntoResponse as _;
                            return (
                                ::server_less::axum::http::StatusCode::BAD_REQUEST,
                                format!("Query parameter '{}' is required (expected {})", #name_str, #ty_str),
                            ).into_response();
                        }
                    };
                });
                calls.push(quote! { #var_ident });
            }
            param_names.push(Some(param.name_str()));
        }
    }

    // Generate header parameter extraction
    if !header_params.is_empty() {
        // Note: we intentionally do NOT generate unknown-header warnings here.
        // HTTP requests routinely carry many standard headers (Content-Type, Authorization,
        // Accept, User-Agent, etc.) that are not method params. Warning on them would produce
        // false positives on nearly every request, making the feature useless.
        extractions.push(quote! {
            headers: ::server_less::axum::http::HeaderMap
        });

        for param in &header_params {
            // Use wire_name if provided, otherwise use the parameter name
            let name_str = param
                .wire_name
                .clone()
                .unwrap_or_else(|| param.name_str());
            let ty = &param.ty;

            if param.is_optional {
                let inner_ty = extract_option_inner(ty).unwrap_or_else(|| ty.clone());
                let inner_ty_str = quote!(#inner_ty).to_string().replace(" ", "");
                let var_ident = format_ident!("__sl_opt_{}", param.name_str());
                pre_stmts.push(quote! {
                    let #var_ident: ::std::option::Option<#inner_ty> = match headers.get(#name_str) {
                        ::std::option::Option::None => ::std::option::Option::None,
                        ::std::option::Option::Some(raw) => match raw.to_str().ok().and_then(|v| v.parse::<#inner_ty>().ok()) {
                            ::std::option::Option::Some(val) => ::std::option::Option::Some(val),
                            ::std::option::Option::None => {
                                use ::server_less::axum::response::IntoResponse as _;
                                return (
                                    ::server_less::axum::http::StatusCode::BAD_REQUEST,
                                    format!("Optional header '{}' has invalid value (expected {})", #name_str, #inner_ty_str),
                                ).into_response();
                            }
                        }
                    };
                });
                calls.push(quote! { #var_ident });
            } else {
                let ty_str = quote!(#ty).to_string().replace(" ", "");
                let var_ident = format_ident!("__sl_req_{}", param.name_str());
                pre_stmts.push(quote! {
                    let #var_ident: #ty = match headers.get(#name_str)
                        .and_then(|v| v.to_str().ok())
                        .and_then(|v| v.parse::<#ty>().ok())
                    {
                        ::std::option::Option::Some(v) => v,
                        ::std::option::Option::None => {
                            use ::server_less::axum::response::IntoResponse as _;
                            return (
                                ::server_less::axum::http::StatusCode::BAD_REQUEST,
                                format!("Header '{}' is required (expected {})", #name_str, #ty_str),
                            ).into_response();
                        }
                    };
                });
                calls.push(quote! { #var_ident });
            }
            param_names.push(Some(param.name_str()));
        }
    }

    Ok((extractions, pre_stmts, calls, param_names))
}

fn generate_response_handling(
    method: &MethodInfo,
    call: &TokenStream2,
    response_overrides: &ResponseOverride,
) -> syn::Result<TokenStream2> {
    let ret = &method.return_info;

    let base_response = if ret.is_unit {
        quote! {
            {
                #call;
                ::server_less::axum::http::StatusCode::NO_CONTENT
            }
        }
    } else if ret.is_result {
        quote! {
            {
                use ::server_less::axum::response::IntoResponse;
                use ::server_less::HttpStatusFallback as _;
                match #call {
                    Ok(value) => ::server_less::axum::Json(value).into_response(),
                    Err(err) => {
                        let status_u16 = ::server_less::HttpStatusHelper(&err).http_status_code();
                        let status = ::server_less::axum::http::StatusCode::from_u16(status_u16)
                            .unwrap_or(::server_less::axum::http::StatusCode::INTERNAL_SERVER_ERROR);
                        let body = ::server_less::serde_json::json!({
                            "error": format!("{:?}", err),
                            "message": format!("{}", err)
                        });
                        (status, ::server_less::axum::Json(body)).into_response()
                    }
                }
            }
        }
    } else if ret.is_option {
        quote! {
            {
                use ::server_less::axum::response::IntoResponse;
                match #call {
                    Some(value) => ::server_less::axum::Json(value).into_response(),
                    None => ::server_less::axum::http::StatusCode::NOT_FOUND.into_response(),
                }
            }
        }
    } else if ret.is_iterator {
        quote! {
            {
                use ::server_less::futures::StreamExt;
                let iter = #call;
                let stream = ::server_less::futures::stream::iter(iter);
                let boxed_stream = Box::pin(stream);
                ::server_less::axum::response::sse::Sse::new(
                    boxed_stream.map(|item| {
                        Ok::<_, std::convert::Infallible>(
                            ::server_less::axum::response::sse::Event::default()
                                .json_data(item)
                                .expect("BUG: failed to serialize SSE event as JSON — Iterator item type must implement serde::Serialize")
                        )
                    })
                )
            }
        }
    } else if ret.is_stream {
        quote! {
            {
                use ::server_less::futures::StreamExt;
                let stream = #call;
                let boxed_stream = Box::pin(stream);
                ::server_less::axum::response::sse::Sse::new(
                    boxed_stream.map(|item| {
                        Ok::<_, std::convert::Infallible>(
                            ::server_less::axum::response::sse::Event::default()
                                .json_data(item)
                                .expect("BUG: failed to serialize SSE event as JSON — the Stream item type must implement serde::Serialize")
                        )
                    })
                )
            }
        }
    } else {
        quote! {
            {
                let result = #call;
                ::server_less::axum::Json(result)
            }
        }
    };

    // Apply response overrides if any are specified
    if response_overrides.status.is_some()
        || response_overrides.content_type.is_some()
        || !response_overrides.headers.is_empty()
    {
        apply_response_overrides(base_response, response_overrides)
    } else {
        Ok(base_response)
    }
}

/// Apply response overrides (status, headers, content-type) to a base response
fn apply_response_overrides(
    base_response: TokenStream2,
    overrides: &ResponseOverride,
) -> syn::Result<TokenStream2> {
    let status_code = if let Some(status) = overrides.status {
        quote! {
            ::server_less::axum::http::StatusCode::from_u16(#status)
                .unwrap_or(::server_less::axum::http::StatusCode::OK)
        }
    } else {
        quote! { ::server_less::axum::http::StatusCode::OK }
    };

    let header_insertions: Vec<TokenStream2> = overrides
        .headers
        .iter()
        .map(|(name, value)| {
            quote! {
                headers.insert(
                    ::server_less::axum::http::header::HeaderName::from_static(#name),
                    ::server_less::axum::http::header::HeaderValue::from_static(#value)
                );
            }
        })
        .collect();

    let content_type_insertion = if let Some(ref ct) = overrides.content_type {
        quote! {
            headers.insert(
                ::server_less::axum::http::header::CONTENT_TYPE,
                ::server_less::axum::http::header::HeaderValue::from_static(#ct)
            );
        }
    } else {
        quote! {}
    };

    Ok(quote! {
        {
            use ::server_less::axum::response::IntoResponse;
            let base_response = #base_response;
            let mut headers = ::server_less::axum::http::HeaderMap::new();
            #(#header_insertions)*
            #content_type_insertion
            (#status_code, headers, base_response).into_response()
        }
    })
}

fn generate_route(
    prefix: &str,
    method: &MethodInfo,
    overrides: &RouteOverride,
    struct_name: &syn::Ident,
) -> syn::Result<TokenStream2> {
    let method_name = &method.name;
    // NOTE: to_snake_case can produce collisions for structs that differ only in
    // separator style (e.g. `UserService` and `User_Service` both → `user_service`).
    let struct_name_snake = struct_name.to_string().to_snake_case();
    let handler_name = format_ident!("__server_less_http_{}_{}", struct_name_snake, method_name);

    let http_method = if let Some(ref m) = overrides.method {
        match m.as_str() {
            "GET" => HttpMethod::Get,
            "POST" => HttpMethod::Post,
            "PUT" => HttpMethod::Put,
            "PATCH" => HttpMethod::Patch,
            "DELETE" => HttpMethod::Delete,
            other => {
                // Unknown verbs are caught earlier in expand_http; this branch
                // is unreachable in normal use but kept for defensive correctness.
                let span = overrides.method_span.unwrap_or_else(|| method_name.span());
                const SUPPORTED: &[&str] = &["GET", "POST", "PUT", "PATCH", "DELETE"];
                let suggestion = crate::did_you_mean(other, SUPPORTED)
                    .map(|s| format!(" — did you mean `{s}`?"))
                    .unwrap_or_default();
                return Err(syn::Error::new(
                    span,
                    format!(
                        "unknown HTTP method `{other}`{suggestion}\n\
                         \n\
                         Supported methods: GET, POST, PUT, PATCH, DELETE"
                    ),
                ));
            }
        }
    } else {
        infer_http_method(&method_name.to_string())
    };

    let path = if let Some(ref p) = overrides.path {
        let span = overrides.path_span.unwrap_or_else(|| method_name.span());
        validate_http_path(p, span)?;
        p.clone()
    } else {
        infer_path(&method_name.to_string(), &http_method, &method.params)
    };
    let full_path = format!("{}{}", prefix, path);

    let method_fn = match http_method {
        HttpMethod::Get => quote! { get },
        HttpMethod::Post => quote! { post },
        HttpMethod::Put => quote! { put },
        HttpMethod::Patch => quote! { patch },
        HttpMethod::Delete => quote! { delete },
    };

    Ok(quote! {
        .route(#full_path, #method_fn(#handler_name))
    })
}

/// Normalize a path for duplicate detection by replacing all path parameters with a placeholder
///
/// This ensures that paths like `/users/{id}` and `/users/{user_id}` are detected as duplicates,
/// since they have the same routing structure even though parameter names differ.
fn normalize_path_for_duplicate_check(path: &str) -> String {
    path.split('/')
        .map(|segment| {
            if segment.starts_with('{') && segment.ends_with('}') {
                "{*}"
            } else {
                segment
            }
        })
        .collect::<Vec<_>>()
        .join("/")
}

/// Validate HTTP path at compile time.
///
/// `path_span` should be the span of the `#[route(path = "...")]` literal so
/// that error diagnostics underline the problematic string rather than the
/// method name.
fn validate_http_path(path: &str, path_span: proc_macro2::Span) -> syn::Result<()> {
    // Check that path starts with /
    if !path.starts_with('/') {
        return Err(syn::Error::new(
            path_span,
            format!(
                "HTTP path must start with '/'. Got: '{}'\n\
                 \n\
                 Hint: Change to '/{}'",
                path, path
            ),
        ));
    }

    // Check for multiple consecutive slashes
    if path.contains("//") {
        return Err(syn::Error::new(
            path_span,
            format!(
                "HTTP path contains consecutive slashes. Path: '{}'\n\
                 \n\
                 Hint: Use single slashes to separate path segments, e.g., /users/posts",
                path
            ),
        ));
    }

    // Warn about trailing slashes (can cause routing issues)
    if path.len() > 1 && path.ends_with('/') {
        return Err(syn::Error::new(
            path_span,
            format!(
                "HTTP path has trailing slash. Path: '{}'\n\
                 \n\
                 Hint: Remove trailing slash: '{}'\n\
                 Trailing slashes can cause routing inconsistencies.",
                path,
                path.trim_end_matches('/')
            ),
        ));
    }

    // Check for invalid characters
    let invalid_chars = ['<', '>', '"', '`', ' ', '\t', '\n', '?', '#'];
    if let Some(ch) = invalid_chars.iter().find(|&&c| path.contains(c)) {
        let hint = if *ch == '<' || *ch == '>' {
            "\n\nHint: Use curly braces for path parameters, e.g., /users/{id}"
        } else if *ch == ' ' {
            "\n\nHint: Use hyphens or underscores instead of spaces, e.g., /my-resource"
        } else if *ch == '?' {
            "\n\nHint: Query parameters are added automatically from method parameters"
        } else if *ch == '#' {
            "\n\nHint: Fragment identifiers are not supported in server routes"
        } else {
            ""
        };
        return Err(syn::Error::new(
            path_span,
            format!(
                "HTTP path contains invalid character '{}'. Path: '{}'{}",
                ch, path, hint
            ),
        ));
    }

    // Check for malformed path parameters
    let open_braces = path.matches('{').count();
    let close_braces = path.matches('}').count();
    if open_braces != close_braces {
        return Err(syn::Error::new(
            path_span,
            format!(
                "HTTP path has mismatched braces. Path: '{}'\n\
                 \n\
                 Found {} opening '{{' and {} closing '}}'\n\
                 Hint: Each path parameter should be wrapped in braces, e.g., /users/{{id}}",
                path, open_braces, close_braces
            ),
        ));
    }

    // Extract and validate path parameter names
    let mut param_names = std::collections::HashSet::new();
    for (idx, part) in path.split('/').enumerate() {
        if part.starts_with('{') && part.ends_with('}') {
            let param_name = part.trim_start_matches('{').trim_end_matches('}');

            // Check for empty parameter name
            if param_name.is_empty() {
                return Err(syn::Error::new(
                    path_span,
                    format!(
                        "HTTP path has empty path parameter at segment {}. Path: '{}'\n\
                         \n\
                         Hint: Path parameters need names, e.g., /users/{{id}} or /posts/{{post_id}}",
                        idx, path
                    ),
                ));
            }

            // Check for valid parameter name (alphanumeric, underscore, hyphen)
            if !param_name
                .chars()
                .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
            {
                return Err(syn::Error::new(
                    path_span,
                    format!(
                        "HTTP path parameter '{}' contains invalid characters. Path: '{}'\n\
                         \n\
                         Hint: Parameter names should only contain alphanumeric characters, underscores, and hyphens",
                        param_name, path
                    ),
                ));
            }

            // Check for duplicate parameter names
            if !param_names.insert(param_name.to_string()) {
                return Err(syn::Error::new(
                    path_span,
                    format!(
                        "HTTP path has duplicate parameter '{{{}}}'. Path: '{}'\n\
                         \n\
                         Hint: Each path parameter must have a unique name\n\
                         Consider using names like {{user_id}} and {{post_id}} instead of multiple {{id}}",
                        param_name, path
                    ),
                ));
            }
        } else if part.contains('{') || part.contains('}') {
            // Malformed segment with partial braces
            return Err(syn::Error::new(
                path_span,
                format!(
                    "HTTP path has malformed path parameter at segment {}. Path: '{}'\n\
                     \n\
                     Hint: Path parameters must be complete segments, e.g., /users/{{id}}/posts\n\
                     Not: /users/user-{{id}}/posts",
                    idx, path
                ),
            ));
        }
    }

    Ok(())
}

/// Arguments for the #[serve] attribute
#[derive(Default)]
pub(crate) struct ServeArgs {
    /// Protocols to serve (http, ws, jsonrpc, graphql)
    pub protocols: Vec<String>,
    /// Health check path (default: /health)
    pub health_path: Option<String>,
    /// OpenAPI spec generation (default: true when protocols are present)
    /// Set to false with `openapi = false`
    pub openapi: Option<bool>,
    /// Application name (used as OpenAPI info.title, overrides struct name)
    pub name: Option<String>,
    /// Human-readable description (used as OpenAPI info.description)
    pub description: Option<String>,
    /// Application version (used as OpenAPI info.version, defaults to CARGO_PKG_VERSION)
    pub version: Option<String>,
    /// Homepage URL (used as OpenAPI info.contact.url)
    pub homepage: Option<String>,
}

impl ServeArgs {
    /// Whether OpenAPI spec should be generated.
    /// Default: true (opt-out with `openapi = false`)
    pub fn openapi_enabled(&self) -> bool {
        self.openapi.unwrap_or(true)
    }
}

impl Parse for ServeArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = ServeArgs::default();

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;
            let ident_str = ident.to_string();

            match ident_str.as_str() {
                "http" | "ws" | "jsonrpc" | "graphql" => {
                    args.protocols.push(ident_str);
                }
                "health" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.health_path = Some(lit.value());
                }
                "openapi" => {
                    if input.peek(Token![=]) {
                        input.parse::<Token![=]>()?;
                        let lit: syn::LitBool = input.parse()?;
                        args.openapi = Some(lit.value());
                    } else {
                        // Bare `openapi` means enable
                        args.openapi = Some(true);
                    }
                }
                "name" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.name = Some(lit.value());
                }
                "description" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.description = Some(lit.value());
                }
                "version" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.version = Some(lit.value());
                }
                "homepage" => {
                    input.parse::<Token![=]>()?;
                    let lit: syn::LitStr = input.parse()?;
                    args.homepage = Some(lit.value());
                }
                other => {
                    const VALID: &[&str] = &[
                        "http", "ws", "jsonrpc", "graphql", "health", "openapi",
                        "name", "description", "version", "homepage",
                    ];
                    let suggestion = crate::did_you_mean(other, VALID)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    return Err(syn::Error::new(
                        ident.span(),
                        format!(
                            "unknown argument `{other}`{suggestion}\n\
                             \n\
                             Valid protocols: http, ws, jsonrpc, graphql\n\
                             Valid options: health, openapi, name, description, version, homepage\n\
                             \n\
                             Examples:\n\
                             - #[serve(http, ws, health = \"/status\")]\n\
                             - #[serve(http, openapi = false)]\n\
                             - #[serve(http, name = \"My API\", description = \"Does the thing\")]"
                        ),
                    ));
                }
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(args)
    }
}

/// Coordinate multiple protocol handlers into a single server.
pub(crate) fn expand_serve(args: ServeArgs, impl_block: ItemImpl) -> syn::Result<TokenStream2> {
    let struct_name = get_impl_name(&impl_block)?;
    let (impl_generics, _ty_generics, where_clause) = impl_block.generics.split_for_impl();
    let self_ty = &impl_block.self_ty;

    let openapi_enabled = args.openapi_enabled();
    let health_path = args.health_path.unwrap_or_else(|| "/health".to_string());
    let serve_title = args.name.unwrap_or_else(|| struct_name.to_string());
    let serve_version = match args.version {
        Some(ref v) => quote! { #v },
        None => quote! { ::std::env!("CARGO_PKG_VERSION") },
    };

    // Build router combination based on protocols
    let router_setup = generate_router_setup(&args.protocols);

    // Generate OpenAPI spec method and route if enabled
    let (openapi_spec_method, openapi_route) = if openapi_enabled {
        let openapi_paths_merges = generate_openapi_merges(&args.protocols);

        let method = quote! {
            /// Get the combined OpenAPI spec for all configured protocols.
            ///
            /// Merges paths from HTTP, JSON-RPC, GraphQL, and/or WebSocket
            /// into a single OpenAPI 3.0 spec using OpenApiBuilder.
            ///
            /// Disable with `#[serve(http, openapi = false)]`.
            pub fn openapi_spec() -> ::server_less::serde_json::Value {
                ::server_less::OpenApiBuilder::new()
                    .title(#serve_title)
                    .version(#serve_version)
                    #openapi_paths_merges
                    .build()
            }
        };

        let route = quote! {
            let router = router.route(
                "/openapi.json",
                ::server_less::axum::routing::get(|| async {
                    ::server_less::axum::Json(#struct_name::openapi_spec())
                })
            );
        };

        (method, route)
    } else {
        (quote! {}, quote! {})
    };

    // Generate the serve method
    let serve_impl = quote! {
        impl #impl_generics #self_ty #where_clause {
            /// Start serving all configured protocols.
            pub async fn serve(self, addr: impl ::std::convert::AsRef<str>) -> ::std::io::Result<()>
            where
                Self: Clone + Send + Sync + 'static,
            {
                #router_setup

                // Add health check
                let router = router.route(
                    #health_path,
                    ::server_less::axum::routing::get(|| async { "ok" })
                );

                // Add OpenAPI spec endpoint
                #openapi_route

                let listener = ::server_less::tokio::net::TcpListener::bind(addr.as_ref()).await?;
                ::server_less::axum::serve(listener, router).await
            }

            /// Build the combined router without starting the server.
            pub fn router(self) -> ::server_less::axum::Router
            where
                Self: Clone + Send + Sync + 'static,
            {
                #router_setup

                let router = router.route(
                    #health_path,
                    ::server_less::axum::routing::get(|| async { "ok" })
                );

                // Add OpenAPI spec endpoint
                #openapi_route

                router
            }

            #openapi_spec_method
        }
    };

    Ok(quote! {
        #impl_block

        #serve_impl
    })
}

/// Generate OpenAPI merge calls for each enabled protocol.
fn generate_openapi_merges(protocols: &[String]) -> TokenStream2 {
    let has_http = protocols.contains(&"http".to_string());
    let has_ws = protocols.contains(&"ws".to_string());
    let has_jsonrpc = protocols.contains(&"jsonrpc".to_string());
    let has_graphql = protocols.contains(&"graphql".to_string());

    let mut merges = Vec::new();

    if has_http {
        merges.push(quote! {
            .merge_paths(Self::http_openapi_paths())
        });
    }
    if has_jsonrpc {
        merges.push(quote! {
            .merge_paths(Self::jsonrpc_openapi_paths())
        });
    }
    if has_graphql {
        merges.push(quote! {
            .merge_paths(Self::graphql_openapi_paths())
        });
    }
    if has_ws {
        merges.push(quote! {
            .merge_paths(Self::ws_openapi_paths())
        });
    }

    quote! { #(#merges)* }
}

/// Generate router setup code based on enabled protocols
fn generate_router_setup(protocols: &[String]) -> TokenStream2 {
    let has_http = protocols.contains(&"http".to_string());
    let has_ws = protocols.contains(&"ws".to_string());
    let has_jsonrpc = protocols.contains(&"jsonrpc".to_string());
    let has_graphql = protocols.contains(&"graphql".to_string());

    // Build list of merge operations
    let mut parts = Vec::new();

    if has_http {
        parts.push(quote! { self.clone().http_router() });
    }
    if has_ws {
        parts.push(quote! { self.clone().ws_router() });
    }
    if has_jsonrpc {
        parts.push(quote! { self.clone().jsonrpc_router() });
    }
    if has_graphql {
        parts.push(quote! { self.clone().graphql_router() });
    }

    if parts.is_empty() {
        quote! {
            let router = ::server_less::axum::Router::new();
        }
    } else if parts.len() == 1 {
        let first = &parts[0];
        quote! {
            let router = #first;
        }
    } else {
        let first = &parts[0];
        let rest = &parts[1..];
        quote! {
            let router = #first #(.merge(#rest))*;
        }
    }
}