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
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
//! Proc macros for server-less.
//!
//! This crate provides attribute macros that transform impl blocks into protocol handlers,
//! and derive macros for common patterns.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
#[cfg(feature = "graphql")]
use syn::ItemEnum;
#[cfg(feature = "graphql")]
use syn::ItemStruct;
use syn::{DeriveInput, ItemImpl, parse_macro_input};
use syn::spanned::Spanned;

/// Check that an impl block has at least one method, or emit a macro-specific error.
///
/// `macro_name` should be the attribute name as written by the user (e.g. `"http"`).
macro_rules! check_not_empty_impl {
    ($impl_block:expr, $macro_name:literal) => {{
        let has_methods = $impl_block
            .items
            .iter()
            .any(|item| matches!(item, syn::ImplItem::Fn(_)));
        if !has_methods {
            // TODO: downgrade to warning once proc_macro_warning stabilizes (https://github.com/rust-lang/rust/issues/54140)
            return syn::Error::new(
                $impl_block.brace_token.span.open(),
                concat!(
                    "#[", $macro_name, "] applied to an empty impl block — no routes will be generated.\n",
                    "Add at least one method, or remove the attribute."
                ),
            )
            .to_compile_error()
            .into();
        }
    }};
}

/// Parse an impl block from the token stream, or emit a macro-specific error.
///
/// `macro_name` should be the attribute name as written by the user (e.g. `"http"`).
macro_rules! parse_impl_block {
    ($item:expr, $macro_name:literal) => {{
        let tokens: TokenStream = $item;
        match syn::parse::<ItemImpl>(tokens) {
            Ok(b) => b,
            Err(_) => {
                return syn::Error::new(
                    proc_macro2::Span::call_site(),
                    concat!(
                        "#[", $macro_name, "] can only be applied to impl blocks.\n\n",
                        "Example:\n  #[", $macro_name, "]\n  impl MyService { ... }"
                    ),
                )
                .to_compile_error()
                .into();
            }
        }
    }};
}

pub(crate) use server_less_parse::did_you_mean;

/// When `SERVER_LESS_DEBUG=1` is set at build time, print the generated token
/// stream to stderr so implementors can inspect macro output without `cargo expand`.
fn debug_emit(macro_name: &str, type_name: &str, tokens: &TokenStream2) {
    if std::env::var("SERVER_LESS_DEBUG").as_deref() == Ok("1") {
        eprintln!("--- server-less: #[{macro_name}] on {type_name} ---");
        eprintln!("{tokens}");
        eprintln!("--- end #[{macro_name}] on {type_name} ---");
    }
}

fn type_name(ty: &syn::Type) -> String {
    quote::quote!(#ty).to_string()
}

/// Strip the first `impl` block from a token stream.
///
/// Preset macros call multiple expand functions, each of which emits the
/// original impl block followed by generated code. To avoid duplicate method
/// definitions, the preset emits the impl block from the first expand call
/// and strips it from subsequent calls.
fn strip_first_impl(tokens: TokenStream2) -> TokenStream2 {
    let file: syn::File = match syn::parse2(tokens.clone()) {
        Ok(file) => file,
        Err(err) => {
            // Emit the original tokens (so the user's code is preserved) plus
            // a compile_error! pointing at the parse failure.  This surfaces the
            // real problem instead of silently dropping generated impls.
            let msg = format!("server-less: preset macro failed to parse generated tokens: {err}");
            return quote::quote! {
                #tokens
                ::core::compile_error!(#msg);
            };
        }
    };

    let mut found_first = false;
    let remaining: Vec<_> = file
        .items
        .into_iter()
        .filter(|item| {
            if !found_first && matches!(item, syn::Item::Impl(_)) {
                found_first = true;
                return false;
            }
            true
        })
        .collect();

    quote::quote! { #(#remaining)* }
}

/// Priority-ordered list of protocol macro attribute names.
///
/// When multiple protocol macros are stacked on the same impl block, Rust expands
/// each independently (outputs are concatenated, not pipelined).  To avoid emitting
/// the impl block multiple times, exactly ONE macro — the one with the highest
/// priority that's present — takes responsibility for emitting it.
const PROTOCOL_PRIORITY: &[&str] = &[
    // Runtime protocols (higher priority — emit the impl block)
    "cli", "http", "mcp", "jsonrpc", "ws", "graphql",
    // Spec generators
    "openapi", "openrpc",
    // Schema generators (lower priority — defer impl block to runtime macros)
    "grpc", "capnp", "thrift", "smithy", "connect", "asyncapi", "jsonschema", "markdown",
];

/// Returns `true` if this protocol macro should emit the original impl block.
///
/// A macro emits the impl when no higher-priority protocol sibling is present on
/// the same impl block.  This ensures exactly one copy is emitted when macros are
/// stacked, preventing duplicate method definitions.
pub(crate) fn is_protocol_impl_emitter(impl_block: &ItemImpl, current: &str) -> bool {
    let current_pos = PROTOCOL_PRIORITY
        .iter()
        .position(|&p| p == current)
        .expect("BUG: protocol not in PROTOCOL_PRIORITY — update the list when adding a new protocol");
    // Emit if no sibling with LOWER index (higher priority) is present.
    !impl_block.attrs.iter().any(|attr| {
        PROTOCOL_PRIORITY[..current_pos]
            .iter()
            .any(|name| attr.path().is_ident(name))
    })
}

/// Returns an error if the impl block has generic type parameters.
/// Protocol macros do not yet support generic impl blocks.
pub(crate) fn reject_generic_impl(impl_block: &syn::ItemImpl) -> syn::Result<()> {
    if !impl_block.generics.params.is_empty() {
        let span = impl_block.generics.params.first()
            .map(|p| p.span())
            .unwrap_or_else(|| impl_block.generics.span());
        return Err(syn::Error::new(
            span,
            "server-less macros do not yet support generic impl blocks — \
             remove the type parameters or implement the trait manually; \
             hint: consider using a concrete type, \
             e.g. `impl MyService<ConcreteType> { ... }`",
        ));
    }
    Ok(())
}


#[cfg(feature = "asyncapi")]
mod asyncapi;
#[cfg(feature = "capnp")]
mod capnp;
#[cfg(feature = "cli")]
mod cli;
#[cfg(feature = "connect")]
mod connect;
mod context;
mod error;
#[cfg(feature = "graphql")]
mod graphql;
#[cfg(feature = "graphql")]
mod graphql_enum;
#[cfg(feature = "graphql")]
mod graphql_input;
#[cfg(feature = "grpc")]
mod grpc;
#[cfg(feature = "health")]
mod health;
#[cfg(feature = "http")]
mod http;
#[cfg(feature = "jsonrpc")]
mod jsonrpc;
#[cfg(feature = "jsonschema")]
mod jsonschema;
#[cfg(feature = "markdown")]
mod markdown;
#[cfg(feature = "mcp")]
mod mcp;
#[cfg(any(feature = "http", feature = "openapi"))]
mod openapi;
#[cfg(any(feature = "http", feature = "openapi"))]
mod openapi_gen;
#[cfg(feature = "openrpc")]
mod openrpc;
#[cfg(feature = "smithy")]
mod smithy;
#[cfg(feature = "thrift")]
mod thrift;
#[cfg(feature = "ws")]
mod ws;

mod app;
#[cfg(feature = "config")]
mod config_cmd;
#[cfg(feature = "config")]
mod config_derive;
mod server_attrs;

// Blessed preset modules
#[cfg(feature = "cli")]
mod program;
#[cfg(feature = "jsonrpc")]
mod rpc_preset;
#[cfg(feature = "http")]
mod server;
#[cfg(feature = "mcp")]
mod tool;

/// Generate HTTP handlers from an impl block.
///
/// # Basic Usage
///
/// ```ignore
/// use server_less::http;
///
/// #[http]
/// impl UserService {
///     async fn create_user(&self, name: String) -> User { /* ... */ }
/// }
/// ```
///
/// # With URL Prefix
///
/// ```ignore
/// #[http(prefix = "/api/v1")]
/// impl UserService {
///     // POST /api/v1/users
///     async fn create_user(&self, name: String) -> User { /* ... */ }
/// }
/// ```
///
/// # Per-Method Route Overrides
///
/// ```ignore
/// #[http]
/// impl UserService {
///     // Override HTTP method: GET /data becomes POST /data
///     #[route(method = "POST")]
///     async fn get_data(&self, payload: String) -> String { /* ... */ }
///
///     // Override path: POST /users becomes POST /custom-endpoint
///     #[route(path = "/custom-endpoint")]
///     async fn create_user(&self, name: String) -> User { /* ... */ }
///
///     // Override both
///     #[route(method = "PUT", path = "/special/{id}")]
///     async fn do_something(&self, id: String) -> String { /* ... */ }
///
///     // Skip route generation (internal methods)
///     #[route(skip)]
///     fn internal_helper(&self) -> String { /* ... */ }
///
///     // Hide from OpenAPI but still generate route
///     #[route(hidden)]
///     fn secret_endpoint(&self) -> String { /* ... */ }
/// }
/// ```
///
/// # Parameter Handling
///
/// ```ignore
/// #[http]
/// impl BlogService {
///     // Path parameters (id, post_id, etc. go in URL)
///     async fn get_post(&self, post_id: u32) -> Post { /* ... */ }
///     // GET /posts/{post_id}
///
///     // Query parameters (GET methods use query string)
///     async fn search_posts(&self, query: String, tag: Option<String>) -> Vec<Post> {
///         /* ... */
///     }
///     // GET /posts?query=rust&tag=tutorial
///
///     // Body parameters (POST/PUT/PATCH use JSON body)
///     async fn create_post(&self, title: String, content: String) -> Post {
///         /* ... */
///     }
///     // POST /posts with body: {"title": "...", "content": "..."}
/// }
/// ```
///
/// # Error Handling
///
/// ```ignore
/// #[http]
/// impl UserService {
///     // Return Result for error handling
///     async fn get_user(&self, id: u32) -> Result<User, MyError> {
///         if id == 0 {
///             return Err(MyError::InvalidId);
///         }
///         Ok(User { id, name: "Alice".into() })
///     }
///
///     // Return Option - None becomes 404
///     async fn find_user(&self, email: String) -> Option<User> {
///         // Returns 200 with user or 404 if None
///         None
///     }
/// }
/// ```
///
/// # Server-Sent Events (SSE) Streaming
///
/// Return `impl Stream<Item = T>` to enable Server-Sent Events streaming.
///
/// **Important for Rust 2024:** You must add `+ use<>` to impl Trait return types
/// to explicitly capture all generic parameters in scope. This is required by the
/// Rust 2024 edition's stricter lifetime capture rules.
///
/// ```ignore
/// use futures::stream::{self, Stream};
///
/// #[http]
/// impl DataService {
///     // Simple stream - emits values immediately
///     // Note the `+ use<>` syntax for Rust 2024
///     fn stream_numbers(&self, count: u32) -> impl Stream<Item = u32> + use<> {
///         stream::iter(0..count)
///     }
///
///     // Async stream with delays
///     async fn stream_events(&self, n: u32) -> impl Stream<Item = Event> + use<> {
///         stream::unfold(0, move |count| async move {
///             if count >= n {
///                 return None;
///             }
///             tokio::time::sleep(Duration::from_secs(1)).await;
///             Some((Event { id: count }, count + 1))
///         })
///     }
/// }
/// ```
///
/// Clients receive data as SSE:
/// ```text
/// data: {"id": 0}
///
/// data: {"id": 1}
///
/// data: {"id": 2}
/// ```
///
/// **Why `+ use<>`?**
/// - Rust 2024 requires explicit capture of generic parameters in return position impl Trait
/// - `+ use<>` captures all type parameters and lifetimes from the function context
/// - Without it, you'll get compilation errors about uncaptured parameters
/// - See: examples/streaming_service.rs for a complete working example
///
/// # Real-World Example
///
/// ```ignore
/// #[http(prefix = "/api/v1")]
/// impl UserService {
///     // GET /api/v1/users?page=0&limit=10
///     async fn list_users(
///         &self,
///         #[param(default = 0)] page: u32,
///         #[param(default = 20)] limit: u32,
///     ) -> Vec<User> {
///         /* ... */
///     }
///
///     // GET /api/v1/users/{user_id}
///     async fn get_user(&self, user_id: u32) -> Result<User, ApiError> {
///         /* ... */
///     }
///
///     // POST /api/v1/users with body: {"name": "...", "email": "..."}
///     #[response(status = 201)]
///     #[response(header = "Location", value = "/api/v1/users/{id}")]
///     async fn create_user(&self, name: String, email: String) -> Result<User, ApiError> {
///         /* ... */
///     }
///
///     // PUT /api/v1/users/{user_id}
///     async fn update_user(
///         &self,
///         user_id: u32,
///         name: Option<String>,
///         email: Option<String>,
///     ) -> Result<User, ApiError> {
///         /* ... */
///     }
///
///     // DELETE /api/v1/users/{user_id}
///     #[response(status = 204)]
///     async fn delete_user(&self, user_id: u32) -> Result<(), ApiError> {
///         /* ... */
///     }
/// }
/// ```
///
/// # Generated Methods
/// - `http_router() -> axum::Router` - Complete router with all endpoints
/// - `http_openapi_spec() -> serde_json::Value` - HTTP-only OpenAPI 3.0 specification (unless `openapi = false`)
///
/// # OpenAPI Control
///
/// By default, `#[http]` generates both HTTP routes and OpenAPI specs. You can disable
/// OpenAPI generation:
///
/// ```ignore
/// #[http(openapi = false)]  // No http_openapi_spec() method generated
/// impl MyService { /* ... */ }
/// ```
///
/// For standalone OpenAPI generation without HTTP routing, see `#[openapi]`.
#[cfg(feature = "http")]
#[proc_macro_attribute]
pub fn http(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as http::HttpArgs);
    let impl_block = parse_impl_block!(item, "http");
    check_not_empty_impl!(impl_block, "http");
    let name = type_name(&impl_block.self_ty);

    match http::expand_http(args, impl_block) {
        Ok(tokens) => {
            debug_emit("http", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate OpenAPI specification without HTTP routing.
///
/// Generates OpenAPI 3.0 specs using the same naming conventions as `#[http]`,
/// but without creating route handlers. Useful for:
/// - Schema-first development
/// - Documentation-only use cases
/// - Separate OpenAPI generation from HTTP routing
///
/// # Basic Usage
///
/// ```ignore
/// use server_less::openapi;
///
/// #[openapi]
/// impl UserService {
///     /// Create a new user
///     fn create_user(&self, name: String, email: String) -> User { /* ... */ }
///
///     /// Get user by ID
///     fn get_user(&self, id: String) -> Option<User> { /* ... */ }
/// }
///
/// // Generate spec:
/// let spec = UserService::openapi_spec();
/// ```
///
/// # With URL Prefix
///
/// ```ignore
/// #[openapi(prefix = "/api/v1")]
/// impl UserService { /* ... */ }
/// ```
///
/// # Generated Methods
///
/// - `openapi_spec() -> serde_json::Value` - OpenAPI 3.0 specification
///
/// # Combining with #[http]
///
/// If you want separate control over OpenAPI generation:
///
/// ```ignore
/// // Option 1: Disable OpenAPI in http, use standalone macro
/// #[http(openapi = false)]
/// #[openapi(prefix = "/api")]
/// impl MyService { /* ... */ }
///
/// // Option 2: Just use http with default (openapi = true)
/// #[http]
/// impl MyService { /* ... */ }
/// ```
#[cfg(any(feature = "http", feature = "openapi"))]
#[proc_macro_attribute]
pub fn openapi(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as openapi::OpenApiArgs);
    let impl_block = parse_impl_block!(item, "openapi");
    let name = type_name(&impl_block.self_ty);

    match openapi::expand_openapi(args, impl_block) {
        Ok(tokens) => {
            debug_emit("openapi", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate a CLI application from an impl block.
///
/// # Basic Usage
///
/// ```ignore
/// use server_less::cli;
///
/// #[cli]
/// impl MyApp {
///     fn create_user(&self, name: String) { /* ... */ }
/// }
/// ```
///
/// # With All Options
///
/// ```ignore
/// #[cli(
///     name = "myapp",
///     version = "1.0.0",
///     description = "My awesome application"
/// )]
/// impl MyApp {
///     /// Create a new user (becomes: myapp create-user <NAME>)
///     fn create_user(&self, name: String) { /* ... */ }
///
///     /// Optional flags use Option<T>
///     fn list_users(&self, limit: Option<usize>) { /* ... */ }
/// }
/// ```
///
/// # Generated Methods
/// - `cli_command() -> clap::Command` - Complete CLI application
/// - `cli_run(&self) -> Result<(), ...>` - Execute CLI and handle result (sync entry point with tokio)
/// - `cli_run_with(&self, matches: &ArgMatches) -> Result<(), ...>` - Execute a pre-parsed command
/// - `cli_run_async(&self) -> impl Future<...>` - Runtime-agnostic async entry point
/// - `cli_run_with_async(&self, matches: &ArgMatches) -> impl Future<...>` - Async with pre-parsed matches
#[cfg(feature = "cli")]
#[proc_macro_attribute]
pub fn cli(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as cli::CliArgs);
    let impl_block = parse_impl_block!(item, "cli");
    check_not_empty_impl!(impl_block, "cli");
    let name = type_name(&impl_block.self_ty);

    match cli::expand_cli(args, impl_block) {
        Ok(tokens) => {
            debug_emit("cli", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate MCP (Model Context Protocol) tools from an impl block.
///
/// # Basic Usage
///
/// ```ignore
/// use server_less::mcp;
///
/// #[mcp]
/// impl FileTools {
///     fn read_file(&self, path: String) -> String { /* ... */ }
/// }
/// ```
///
/// # With Namespace
///
/// ```ignore
/// #[mcp(namespace = "file")]
/// impl FileTools {
///     // Exposed as "file_read_file" tool
///     fn read_file(&self, path: String) -> String { /* ... */ }
/// }
/// ```
///
/// # Streaming Support
///
/// Methods returning `impl Stream<Item = T>` are automatically collected into arrays:
///
/// ```ignore
/// use futures::stream::{self, Stream};
///
/// #[mcp]
/// impl DataService {
///     // Returns JSON array: [0, 1, 2, 3, 4]
///     fn stream_numbers(&self, count: u32) -> impl Stream<Item = u32> + use<> {
///         stream::iter(0..count)
///     }
/// }
///
/// // Call with:
/// service.mcp_call_async("stream_numbers", json!({"count": 5})).await
/// // Returns: [0, 1, 2, 3, 4]
/// ```
///
/// **Note:** Streaming methods require `mcp_call_async`, not `mcp_call`.
///
/// # Generated Methods
/// - `mcp_tools() -> Vec<serde_json::Value>` - Tool definitions
/// - `mcp_call(&self, name, args) -> Result<Value, String>` - Execute tool (sync only)
/// - `mcp_call_async(&self, name, args).await` - Execute tool (supports async & streams)
#[cfg(feature = "mcp")]
#[proc_macro_attribute]
pub fn mcp(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as mcp::McpArgs);
    let impl_block = parse_impl_block!(item, "mcp");
    check_not_empty_impl!(impl_block, "mcp");
    let name = type_name(&impl_block.self_ty);

    match mcp::expand_mcp(args, impl_block) {
        Ok(tokens) => {
            debug_emit("mcp", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate WebSocket JSON-RPC handlers from an impl block.
///
/// Methods are exposed as JSON-RPC methods over WebSocket connections.
/// Supports both sync and async methods.
///
/// # Basic Usage
///
/// ```ignore
/// use server_less::ws;
///
/// #[ws(path = "/ws")]
/// impl ChatService {
///     fn send_message(&self, room: String, content: String) -> Message {
///         // ...
///     }
/// }
/// ```
///
/// # With Async Methods
///
/// ```ignore
/// #[ws(path = "/ws")]
/// impl ChatService {
///     // Async methods work seamlessly
///     async fn send_message(&self, room: String, content: String) -> Message {
///         // Can await database, network calls, etc.
///     }
///
///     // Mix sync and async
///     fn get_rooms(&self) -> Vec<String> {
///         // Synchronous method
///     }
/// }
/// ```
///
/// # Error Handling
///
/// ```ignore
/// #[ws(path = "/ws")]
/// impl ChatService {
///     fn send_message(&self, room: String, content: String) -> Result<Message, ChatError> {
///         if room.is_empty() {
///             return Err(ChatError::InvalidRoom);
///         }
///         Ok(Message::new(room, content))
///     }
/// }
/// ```
///
/// # Client Usage
///
/// Clients send JSON-RPC 2.0 messages over WebSocket:
///
/// ```json
/// // Request
/// {
///   "jsonrpc": "2.0",
///   "method": "send_message",
///   "params": {"room": "general", "content": "Hello!"},
///   "id": 1
/// }
///
/// // Response
/// {
///   "jsonrpc": "2.0",
///   "result": {"id": 123, "room": "general", "content": "Hello!"},
///   "id": 1
/// }
/// ```
///
/// # Generated Methods
/// - `ws_router() -> axum::Router` - Router with WebSocket endpoint
/// - `ws_handle_message(msg) -> String` - Sync message handler
/// - `ws_handle_message_async(msg) -> String` - Async message handler
/// - `ws_methods() -> Vec<String>` - List of available methods
#[cfg(feature = "ws")]
#[proc_macro_attribute]
pub fn ws(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as ws::WsArgs);
    let impl_block = parse_impl_block!(item, "ws");
    check_not_empty_impl!(impl_block, "ws");
    let name = type_name(&impl_block.self_ty);

    match ws::expand_ws(args, impl_block) {
        Ok(tokens) => {
            debug_emit("ws", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate JSON-RPC 2.0 handlers over HTTP.
///
/// # Example
///
/// ```ignore
/// use server_less::jsonrpc;
///
/// struct Calculator;
///
/// #[jsonrpc]
/// impl Calculator {
///     /// Add two numbers
///     fn add(&self, a: i32, b: i32) -> i32 {
///         a + b
///     }
///
///     /// Multiply two numbers
///     fn multiply(&self, a: i32, b: i32) -> i32 {
///         a * b
///     }
/// }
///
/// // POST /rpc with {"jsonrpc": "2.0", "method": "add", "params": {"a": 1, "b": 2}, "id": 1}
/// // Returns: {"jsonrpc": "2.0", "result": 3, "id": 1}
/// ```
///
/// This generates:
/// - `Calculator::jsonrpc_router()` returning an axum Router
/// - `Calculator::jsonrpc_handle_async(request)` to handle JSON-RPC requests (async)
/// - `Calculator::jsonrpc_methods()` listing available methods
///
/// Supports JSON-RPC 2.0 features:
/// - Named and positional parameters
/// - Batch requests (array of requests)
/// - Notifications (requests without id)
#[cfg(feature = "jsonrpc")]
#[proc_macro_attribute]
pub fn jsonrpc(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as jsonrpc::JsonRpcArgs);
    let impl_block = parse_impl_block!(item, "jsonrpc");
    check_not_empty_impl!(impl_block, "jsonrpc");
    let name = type_name(&impl_block.self_ty);

    match jsonrpc::expand_jsonrpc(args, impl_block) {
        Ok(tokens) => {
            debug_emit("jsonrpc", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate OpenRPC specification for JSON-RPC services.
///
/// OpenRPC is to JSON-RPC what OpenAPI is to REST APIs.
///
/// # Example
///
/// ```ignore
/// use server_less::openrpc;
///
/// struct Calculator;
///
/// #[openrpc(title = "Calculator API", version = "1.0.0")]
/// impl Calculator {
///     /// Add two numbers
///     fn add(&self, a: i32, b: i32) -> i32 { a + b }
/// }
///
/// // Get OpenRPC spec as JSON
/// let spec = Calculator::openrpc_spec();
/// let json = Calculator::openrpc_json();
///
/// // Write to file
/// Calculator::write_openrpc("openrpc.json")?;
/// ```
#[cfg(feature = "openrpc")]
#[proc_macro_attribute]
pub fn openrpc(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as openrpc::OpenRpcArgs);
    let impl_block = parse_impl_block!(item, "openrpc");
    check_not_empty_impl!(impl_block, "openrpc");
    let name = type_name(&impl_block.self_ty);

    match openrpc::expand_openrpc(args, impl_block) {
        Ok(tokens) => {
            debug_emit("openrpc", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate Markdown API documentation from an impl block.
///
/// Creates human-readable documentation that can be used with
/// any static site generator (VitePress, Docusaurus, MkDocs, etc.).
///
/// # Example
///
/// ```ignore
/// use server_less::markdown;
///
/// struct UserService;
///
/// #[markdown(title = "User API")]
/// impl UserService {
///     /// Create a new user
///     fn create_user(&self, name: String, email: String) -> User { ... }
///
///     /// Get user by ID
///     fn get_user(&self, id: String) -> Option<User> { ... }
/// }
///
/// // Get markdown string
/// let docs = UserService::markdown_docs();
///
/// // Write to file
/// UserService::write_markdown("docs/api.md")?;
/// ```
#[cfg(feature = "markdown")]
#[proc_macro_attribute]
pub fn markdown(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as markdown::MarkdownArgs);
    let impl_block = parse_impl_block!(item, "markdown");
    check_not_empty_impl!(impl_block, "markdown");
    let name = type_name(&impl_block.self_ty);

    match markdown::expand_markdown(args, impl_block) {
        Ok(tokens) => {
            debug_emit("markdown", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate AsyncAPI specification for event-driven services.
///
/// AsyncAPI is to WebSockets/messaging what OpenAPI is to REST.
///
/// # Example
///
/// ```ignore
/// use server_less::asyncapi;
///
/// struct ChatService;
///
/// #[asyncapi(title = "Chat API", server = "ws://localhost:8080")]
/// impl ChatService {
///     /// Send a message to a room
///     fn send_message(&self, room: String, content: String) -> bool { true }
///
///     /// Get message history
///     fn get_history(&self, room: String, limit: Option<u32>) -> Vec<String> { vec![] }
/// }
///
/// // Get AsyncAPI spec
/// let spec = ChatService::asyncapi_spec();
/// let json = ChatService::asyncapi_json();
///
/// // Write to file
/// ChatService::write_asyncapi("asyncapi.json")?;
/// ```
#[cfg(feature = "asyncapi")]
#[proc_macro_attribute]
pub fn asyncapi(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as asyncapi::AsyncApiArgs);
    let impl_block = parse_impl_block!(item, "asyncapi");
    check_not_empty_impl!(impl_block, "asyncapi");
    let name = type_name(&impl_block.self_ty);

    match asyncapi::expand_asyncapi(args, impl_block) {
        Ok(tokens) => {
            debug_emit("asyncapi", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate Connect protocol schema from an impl block.
///
/// Connect is a modern RPC protocol from Buf that works over HTTP/1.1, HTTP/2, and HTTP/3.
/// The generated schema is compatible with connect-go, connect-es, connect-swift, etc.
///
/// # Example
///
/// ```ignore
/// use server_less::connect;
///
/// struct UserService;
///
/// #[connect(package = "users.v1")]
/// impl UserService {
///     fn get_user(&self, id: String) -> User { ... }
/// }
///
/// // Get schema and endpoint paths
/// let schema = UserService::connect_schema();
/// let paths = UserService::connect_paths(); // ["/users.v1.UserService/GetUser", ...]
/// ```
#[cfg(feature = "connect")]
#[proc_macro_attribute]
pub fn connect(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as connect::ConnectArgs);
    let impl_block = parse_impl_block!(item, "connect");
    check_not_empty_impl!(impl_block, "connect");
    let name = type_name(&impl_block.self_ty);

    match connect::expand_connect(args, impl_block) {
        Ok(tokens) => {
            debug_emit("connect", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate Protocol Buffers schema from an impl block.
///
/// # Example
///
/// ```ignore
/// use server_less::grpc;
///
/// struct UserService;
///
/// #[grpc(package = "users")]
/// impl UserService {
///     /// Get user by ID
///     fn get_user(&self, id: String) -> User { ... }
///
///     /// Create a new user
///     fn create_user(&self, name: String, email: String) -> User { ... }
/// }
///
/// // Get the proto schema
/// let proto = UserService::grpc_schema();
///
/// // Write to file for use with tonic-build
/// UserService::write_grpc("proto/users.proto")?;
/// ```
///
/// The generated schema can be used with tonic-build in your build.rs
/// to generate the full gRPC client/server implementation.
#[cfg(feature = "grpc")]
#[proc_macro_attribute]
pub fn grpc(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as grpc::GrpcArgs);
    let impl_block = parse_impl_block!(item, "grpc");
    check_not_empty_impl!(impl_block, "grpc");
    let name = type_name(&impl_block.self_ty);

    match grpc::expand_grpc(args, impl_block) {
        Ok(tokens) => {
            debug_emit("grpc", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate Cap'n Proto schema from an impl block.
///
/// # Example
///
/// ```ignore
/// use server_less::capnp;
///
/// struct UserService;
///
/// #[capnp(id = "0x85150b117366d14b")]
/// impl UserService {
///     /// Get user by ID
///     fn get_user(&self, id: String) -> String { ... }
///
///     /// Create a new user
///     fn create_user(&self, name: String, email: String) -> String { ... }
/// }
///
/// // Get the Cap'n Proto schema
/// let schema = UserService::capnp_schema();
///
/// // Write to file for use with capnpc
/// UserService::write_capnp("schema/users.capnp")?;
/// ```
///
/// The generated schema can be used with capnpc to generate
/// the full Cap'n Proto serialization code.
#[cfg(feature = "capnp")]
#[proc_macro_attribute]
pub fn capnp(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as capnp::CapnpArgs);
    let impl_block = parse_impl_block!(item, "capnp");
    check_not_empty_impl!(impl_block, "capnp");
    let name = type_name(&impl_block.self_ty);

    match capnp::expand_capnp(args, impl_block) {
        Ok(tokens) => {
            debug_emit("capnp", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate Apache Thrift schema from an impl block.
///
/// # Example
///
/// ```ignore
/// use server_less::thrift;
///
/// struct UserService;
///
/// #[thrift(namespace = "users")]
/// impl UserService {
///     /// Get user by ID
///     fn get_user(&self, id: String) -> String { ... }
///
///     /// Create a new user
///     fn create_user(&self, name: String, email: String) -> String { ... }
/// }
///
/// // Get the Thrift schema
/// let schema = UserService::thrift_schema();
///
/// // Write to file for use with thrift compiler
/// UserService::write_thrift("idl/users.thrift")?;
/// ```
///
/// The generated schema can be used with the Thrift compiler to generate
/// client/server code in various languages.
#[cfg(feature = "thrift")]
#[proc_macro_attribute]
pub fn thrift(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as thrift::ThriftArgs);
    let impl_block = parse_impl_block!(item, "thrift");
    check_not_empty_impl!(impl_block, "thrift");
    let name = type_name(&impl_block.self_ty);

    match thrift::expand_thrift(args, impl_block) {
        Ok(tokens) => {
            debug_emit("thrift", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate Smithy IDL schema from an impl block.
///
/// Smithy is AWS's open-source interface definition language for defining APIs.
/// The generated schema follows Smithy 2.0 specification.
///
/// # Example
///
/// ```ignore
/// use server_less::smithy;
///
/// struct UserService;
///
/// #[smithy(namespace = "com.example.users")]
/// impl UserService {
///     /// Get user by ID
///     fn get_user(&self, id: String) -> User { ... }
///
///     /// Create a new user
///     fn create_user(&self, name: String, email: String) -> User { ... }
/// }
///
/// // Get Smithy schema
/// let schema = UserService::smithy_schema();
/// // Write to file
/// UserService::write_smithy("service.smithy")?;
/// ```
///
/// The generated schema can be used with the Smithy toolchain for code generation.
#[cfg(feature = "smithy")]
#[proc_macro_attribute]
pub fn smithy(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as smithy::SmithyArgs);
    let impl_block = parse_impl_block!(item, "smithy");
    check_not_empty_impl!(impl_block, "smithy");
    let name = type_name(&impl_block.self_ty);

    match smithy::expand_smithy(args, impl_block) {
        Ok(tokens) => {
            debug_emit("smithy", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate JSON Schema from an impl block.
///
/// Generates JSON Schema definitions for request/response types.
/// Useful for API validation, documentation, and tooling.
///
/// # Example
///
/// ```ignore
/// use server_less::jsonschema;
///
/// struct UserService;
///
/// #[jsonschema(title = "User API")]
/// impl UserService {
///     /// Get user by ID
///     fn get_user(&self, id: String) -> User { ... }
///
///     /// Create a new user
///     fn create_user(&self, name: String, email: String) -> User { ... }
/// }
///
/// // Get JSON Schema
/// let schema = UserService::json_schema();
/// // Write to file
/// UserService::write_json_schema("schema.json")?;
/// ```
#[cfg(feature = "jsonschema")]
#[proc_macro_attribute]
pub fn jsonschema(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as jsonschema::JsonSchemaArgs);
    let impl_block = parse_impl_block!(item, "jsonschema");
    check_not_empty_impl!(impl_block, "jsonschema");
    let name = type_name(&impl_block.self_ty);

    match jsonschema::expand_jsonschema(args, impl_block) {
        Ok(tokens) => {
            debug_emit("jsonschema", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Generate GraphQL schema from an impl block using async-graphql.
///
/// Methods are automatically classified as Queries or Mutations based on naming:
/// - Queries: `get_*`, `list_*`, `find_*`, `search_*`, `fetch_*`, `query_*`
/// - Mutations: everything else (create, update, delete, etc.)
///
/// # Basic Usage
///
/// ```ignore
/// use server_less::graphql;
///
/// #[graphql]
/// impl UserService {
///     // Query: returns single user
///     async fn get_user(&self, id: String) -> Option<User> {
///         // ...
///     }
///
///     // Query: returns list of users
///     async fn list_users(&self) -> Vec<User> {
///         // ...
///     }
///
///     // Mutation: creates new user
///     async fn create_user(&self, name: String, email: String) -> User {
///         // ...
///     }
/// }
/// ```
///
/// # Type Mappings
///
/// - `String`, `i32`, `bool`, etc. → GraphQL scalars
/// - `Option<T>` → nullable GraphQL field
/// - `Vec<T>` → GraphQL list `[T]`
/// - Custom structs → GraphQL objects (must derive SimpleObject)
///
/// ```ignore
/// use async_graphql::SimpleObject;
///
/// #[derive(SimpleObject)]
/// struct User {
///     id: String,
///     name: String,
///     email: Option<String>,  // Nullable field
/// }
///
/// #[graphql]
/// impl UserService {
///     async fn get_user(&self, id: String) -> Option<User> {
///         // Returns User object with proper GraphQL schema
///     }
///
///     async fn list_users(&self) -> Vec<User> {
///         // Returns [User] in GraphQL
///     }
/// }
/// ```
///
/// # GraphQL Queries
///
/// ```graphql
/// # Query single user
/// query {
///   getUser(id: "123") {
///     id
///     name
///     email
///   }
/// }
///
/// # List all users
/// query {
///   listUsers {
///     id
///     name
///   }
/// }
///
/// # Mutation
/// mutation {
///   createUser(name: "Alice", email: "alice@example.com") {
///     id
///     name
///   }
/// }
/// ```
///
/// # Custom Scalars
///
/// Common custom scalar types are automatically supported:
///
/// ```ignore
/// use chrono::{DateTime, Utc};
/// use uuid::Uuid;
///
/// #[graphql]
/// impl EventService {
///     // UUID parameter
///     async fn get_event(&self, event_id: Uuid) -> Option<Event> { /* ... */ }
///
///     // DateTime parameter
///     async fn list_events(&self, since: DateTime<Utc>) -> Vec<Event> { /* ... */ }
///
///     // JSON parameter
///     async fn search_events(&self, filter: serde_json::Value) -> Vec<Event> { /* ... */ }
/// }
/// ```
///
/// Supported custom scalars:
/// - `chrono::DateTime<Utc>` → DateTime
/// - `uuid::Uuid` → UUID
/// - `url::Url` → Url
/// - `serde_json::Value` → JSON
///
/// # Generated Methods
/// - `graphql_schema() -> Schema` - async-graphql Schema
/// - `graphql_router() -> axum::Router` - Router with /graphql endpoint
/// - `graphql_sdl() -> String` - Schema Definition Language string
#[cfg(feature = "graphql")]
#[proc_macro_attribute]
pub fn graphql(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as graphql::GraphqlArgs);
    let impl_block = parse_impl_block!(item, "graphql");
    check_not_empty_impl!(impl_block, "graphql");
    let name = type_name(&impl_block.self_ty);

    match graphql::expand_graphql(args, impl_block) {
        Ok(tokens) => {
            debug_emit("graphql", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Define a GraphQL enum type.
///
/// Generates a GraphQL Enum type definition from a Rust enum.
/// Only unit variants (no fields) are supported.
///
/// # Example
///
/// ```ignore
/// use server_less::graphql_enum;
///
/// #[graphql_enum]
/// #[derive(Clone, Debug)]
/// enum Status {
///     /// User is active
///     Active,
///     /// User is inactive
///     Inactive,
///     /// Awaiting approval
///     Pending,
/// }
///
/// // Then register with #[graphql]:
/// #[graphql(enums(Status))]
/// impl MyService {
///     pub fn get_status(&self) -> Status { Status::Active }
/// }
/// ```
///
/// # Generated Methods
///
/// - `__graphql_enum_type() -> async_graphql::dynamic::Enum` - Enum type definition
/// - `__to_graphql_value(&self) -> async_graphql::Value` - Convert to GraphQL value
///
/// # Variant Naming
///
/// Variant names are converted to SCREAMING_SNAKE_CASE for GraphQL:
/// - `Active` → `ACTIVE`
/// - `InProgress` → `IN_PROGRESS`
#[cfg(feature = "graphql")]
#[proc_macro_attribute]
pub fn graphql_enum(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let item_enum = parse_macro_input!(item as ItemEnum);
    let name = item_enum.ident.to_string();

    match graphql_enum::expand_graphql_enum(item_enum) {
        Ok(tokens) => {
            debug_emit("graphql_enum", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Define a GraphQL input type.
///
/// Generates a GraphQL InputObject type definition from a Rust struct.
/// The struct must implement `serde::Deserialize` for input parsing.
///
/// # Example
///
/// ```ignore
/// use server_less::graphql_input;
/// use serde::Deserialize;
///
/// #[graphql_input]
/// #[derive(Clone, Debug, Deserialize)]
/// struct CreateUserInput {
///     /// User's name
///     name: String,
///     /// User's email address
///     email: String,
///     /// Optional age
///     age: Option<i32>,
/// }
///
/// // Then register with #[graphql]:
/// #[graphql(inputs(CreateUserInput))]
/// impl UserService {
///     pub fn create_user(&self, input: CreateUserInput) -> User { /* ... */ }
/// }
/// ```
///
/// # Generated Methods
///
/// - `__graphql_input_type() -> async_graphql::dynamic::InputObject` - Input type definition
/// - `__from_graphql_value(value) -> Result<Self, String>` - Parse from GraphQL value
///
/// # Field Naming
///
/// Field names are converted to camelCase for GraphQL:
/// - `user_name` → `userName`
/// - `email_address` → `emailAddress`
#[cfg(feature = "graphql")]
#[proc_macro_attribute]
pub fn graphql_input(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let item_struct = parse_macro_input!(item as ItemStruct);
    let name = item_struct.ident.to_string();

    match graphql_input::expand_graphql_input(item_struct) {
        Ok(tokens) => {
            debug_emit("graphql_input", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Coordinate multiple protocol handlers into a single server.
///
/// # Example
///
/// ```ignore
/// use server_less::{http, ws, jsonrpc, serve};
///
/// struct MyService;
///
/// #[http]
/// #[ws]
/// #[jsonrpc]
/// #[serve(http, ws, jsonrpc)]
/// impl MyService {
///     fn list_items(&self) -> Vec<String> { vec![] }
/// }
///
/// // Now you can:
/// // - service.serve("0.0.0.0:3000").await  // start server
/// // - service.router()                     // get combined router
/// ```
///
/// # Arguments
///
/// - `http` - Include the HTTP router (REST API)
/// - `ws` - Include the WebSocket router (WS JSON-RPC)
/// - `jsonrpc` - Include the JSON-RPC HTTP router
/// - `graphql` - Include the GraphQL router
/// - `health = "/path"` - Custom health check path (default: `/health`)
#[cfg(feature = "http")]
#[proc_macro_attribute]
pub fn serve(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as http::ServeArgs);
    let impl_block = parse_impl_block!(item, "serve");
    check_not_empty_impl!(impl_block, "serve");
    let name = type_name(&impl_block.self_ty);

    match http::expand_serve(args, impl_block) {
        Ok(tokens) => {
            debug_emit("serve", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Helper attribute for method-level HTTP route customization.
///
/// This attribute is used within `#[http]` impl blocks to customize
/// individual method routing. It is a no-op on its own.
///
/// # Example
///
/// ```ignore
/// #[http(prefix = "/api")]
/// impl MyService {
///     #[route(method = "POST", path = "/custom")]
///     fn my_method(&self) { }
///
///     #[route(skip)]
///     fn internal_method(&self) { }
///
///     #[route(hidden)]  // Hidden from OpenAPI but still routed
///     fn secret(&self) { }
/// }
/// ```
#[cfg(feature = "http")]
#[proc_macro_attribute]
pub fn route(_attr: TokenStream, item: TokenStream) -> TokenStream {
    // Pass through unchanged - the #[http] macro parses these attributes
    item
}

/// Helper attribute for method-level HTTP response customization.
///
/// This attribute is used within `#[http]` impl blocks to customize
/// individual method responses. It is a no-op on its own.
///
/// # Supported Options
///
/// - `status = <code>` - Custom HTTP status code (e.g., 201, 204)
/// - `content_type = "<type>"` - Custom content type
/// - `header = "<name>", value = "<value>"` - Add custom response header
///
/// Multiple `#[response(...)]` attributes can be combined on a single method.
///
/// # Examples
///
/// ```ignore
/// #[http(prefix = "/api")]
/// impl MyService {
///     // Custom status code for creation
///     #[response(status = 201)]
///     fn create_item(&self, name: String) -> Item { /* ... */ }
///
///     // No content response
///     #[response(status = 204)]
///     fn delete_item(&self, id: String) { /* ... */ }
///
///     // Binary response with custom content type
///     #[response(content_type = "application/octet-stream")]
///     fn download(&self, id: String) -> Vec<u8> { /* ... */ }
///
///     // Add custom headers
///     #[response(header = "X-Custom", value = "foo")]
///     fn with_header(&self) -> String { /* ... */ }
///
///     // Combine multiple response attributes
///     #[response(status = 201)]
///     #[response(header = "Location", value = "/api/items/123")]
///     #[response(header = "X-Request-Id", value = "abc")]
///     fn create_with_headers(&self, name: String) -> Item { /* ... */ }
/// }
/// ```
#[cfg(feature = "http")]
#[proc_macro_attribute]
pub fn response(_attr: TokenStream, item: TokenStream) -> TokenStream {
    // Pass through unchanged - the #[http] macro parses these attributes
    item
}

/// Helper attribute for parameter-level HTTP customization.
///
/// This attribute is used on function parameters within `#[http]` impl blocks
/// to customize parameter extraction and naming. It is a no-op on its own.
///
/// # Supported Options
///
/// - `name = "<wire_name>"` - Use a different name on the wire (e.g., `q` instead of `query`)
/// - `default = <value>` - Provide a default value for optional parameters
/// - `query` - Force parameter to come from query string
/// - `path` - Force parameter to come from URL path
/// - `body` - Force parameter to come from request body
/// - `header` - Extract parameter from HTTP header
///
/// # Location Inference
///
/// When no location is specified, parameters are inferred based on conventions:
/// - Parameters named `id` or ending in `_id` → path parameters
/// - POST/PUT/PATCH methods → body parameters
/// - GET/DELETE methods → query parameters
///
/// # Examples
///
/// ```ignore
/// #[http(prefix = "/api")]
/// impl SearchService {
///     // Rename parameter: code uses `query`, API accepts `q`
///     fn search(&self, #[param(name = "q")] query: String) -> Vec<Result> {
///         /* ... */
///     }
///
///     // Default value for pagination
///     fn list_items(
///         &self,
///         #[param(default = 0)] offset: u32,
///         #[param(default = 10)] limit: u32,
///     ) -> Vec<Item> {
///         /* ... */
///     }
///
///     // Extract API key from header
///     fn protected_endpoint(
///         &self,
///         #[param(header, name = "X-API-Key")] api_key: String,
///         data: String,
///     ) -> String {
///         /* ... */
///     }
///
///     // Override location inference: force to query even though method is POST
///     fn search_posts(
///         &self,
///         #[param(query)] filter: String,
///         #[param(body)] content: String,
///     ) -> Vec<Post> {
///         /* ... */
///     }
///
///     // Combine multiple options
///     fn advanced(
///         &self,
///         #[param(query, name = "page", default = 1)] page_num: u32,
///     ) -> Vec<Item> {
///         /* ... */
///     }
/// }
/// ```
///
/// # OpenAPI Integration
///
/// - Parameters with `name` are documented with their wire names
/// - Parameters with `default` are marked as not required
/// - Location overrides are reflected in OpenAPI specs
#[cfg(any(feature = "http", feature = "cli", feature = "mcp"))]
#[proc_macro_attribute]
pub fn param(_attr: TokenStream, item: TokenStream) -> TokenStream {
    // Pass through unchanged - the #[http]/[cli]/[mcp] macros parse these attributes
    item
}

// ============================================================================
// Blessed Presets
// ============================================================================

/// Blessed preset: HTTP server with OpenAPI and serve.
///
/// Combines `#[http]` (with OpenAPI enabled by default) + `#[serve(http)]` into
/// a single attribute.  OpenAPI generation can be toggled with `openapi = false`.
///
/// # Example
///
/// ```ignore
/// use server_less::server;
///
/// #[derive(Clone)]
/// struct MyApi;
///
/// #[server]
/// impl MyApi {
///     pub fn list_items(&self) -> Vec<String> { vec![] }
///     pub fn create_item(&self, name: String) -> String { name }
/// }
///
/// // Equivalent to:
/// // #[http]
/// // #[serve(http)]
/// // impl MyApi { ... }
/// ```
///
/// # Options
///
/// - `prefix` - URL prefix (e.g., `#[server(prefix = "/api")]`)
/// - `openapi` - Toggle OpenAPI generation (default: true)
/// - `health` - Custom health check path (default: `/health`)
/// - `config` - Config struct type for config subcommand wiring (e.g., `#[server(config = MyConfig)]`)
/// - `config_cmd` - Config subcommand name override or `false` to disable (default: `"config"`)
/// - `name` - App name (forwarded from `#[app]`; default: kebab-case struct name)
/// - `description` - App description for CLI help and OpenAPI info
/// - `version` - Version string; `false` disables `--version` (default: `CARGO_PKG_VERSION`)
/// - `homepage` - URL used in OpenAPI and OpenRPC info fields
///
/// # `#[server(skip)]` — Dual Role
///
/// When `#[server(skip)]` appears on an **impl block**, it is parsed as a preset
/// option and disables serving (equivalent to `#[http]` without `#[serve]`).
///
/// When `#[server(skip)]` appears on a **method** inside another protocol impl
/// block (e.g. inside `#[http]`), it acts as a per-method marker telling the
/// enclosing macro to skip route generation for that method.  In this form,
/// `#[server]` is passed through unchanged — the outer macro reads it directly
/// from the item tokens.
#[cfg(feature = "http")]
#[proc_macro_attribute]
pub fn server(attr: TokenStream, item: TokenStream) -> TokenStream {
    // When applied to a method inside an impl block (e.g. `#[server(skip)]`),
    // pass through unchanged.  The enclosing protocol macro reads these
    // attributes from the ItemImpl tokens; `#[server]` just needs to not error.
    let item2: proc_macro2::TokenStream = item.clone().into();
    if syn::parse2::<ItemImpl>(item2).is_err() {
        return item;
    }
    let args = parse_macro_input!(attr as server::ServerArgs);
    let impl_block = parse_macro_input!(item as ItemImpl);
    let name = type_name(&impl_block.self_ty);

    match server::expand_server(args, impl_block) {
        Ok(tokens) => {
            debug_emit("server", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Blessed preset: JSON-RPC server with OpenRPC spec and serve.
///
/// Combines `#[jsonrpc]` + `#[openrpc]` + `#[serve(jsonrpc)]` into a single attribute.
/// OpenRPC and serve are included when their features are enabled, and gracefully
/// omitted otherwise.
///
/// # Example
///
/// ```ignore
/// use server_less::rpc;
///
/// #[derive(Clone)]
/// struct Calculator;
///
/// #[rpc]
/// impl Calculator {
///     pub fn add(&self, a: i32, b: i32) -> i32 { a + b }
///     pub fn multiply(&self, a: i32, b: i32) -> i32 { a * b }
/// }
/// ```
///
/// # Options
///
/// - `path` - JSON-RPC endpoint path (e.g., `#[rpc(path = "/api")]`)
/// - `openrpc` - Toggle OpenRPC spec generation (default: true)
/// - `health` - Custom health check path (default: `/health`)
#[cfg(feature = "jsonrpc")]
#[proc_macro_attribute]
pub fn rpc(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as rpc_preset::RpcArgs);
    let impl_block = parse_impl_block!(item, "rpc");
    check_not_empty_impl!(impl_block, "rpc");
    let name = type_name(&impl_block.self_ty);

    match rpc_preset::expand_rpc(args, impl_block) {
        Ok(tokens) => {
            debug_emit("rpc", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Blessed preset: MCP tools with JSON Schema.
///
/// Combines `#[mcp]` + `#[jsonschema]` into a single attribute.
/// JSON Schema is included when the feature is enabled, and gracefully
/// omitted otherwise.
///
/// # Example
///
/// ```ignore
/// use server_less::tool;
///
/// struct FileTools;
///
/// #[tool(namespace = "file")]
/// impl FileTools {
///     pub fn read_file(&self, path: String) -> String { String::new() }
///     pub fn write_file(&self, path: String, content: String) -> bool { true }
/// }
/// ```
///
/// # Options
///
/// - `namespace` - MCP tool namespace prefix
/// - `jsonschema` - Toggle JSON Schema generation (default: true)
#[cfg(feature = "mcp")]
#[proc_macro_attribute]
pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as tool::ToolArgs);
    let impl_block = parse_impl_block!(item, "tool");
    check_not_empty_impl!(impl_block, "tool");
    let name = type_name(&impl_block.self_ty);

    match tool::expand_tool(args, impl_block) {
        Ok(tokens) => {
            debug_emit("tool", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Blessed preset: CLI application with Markdown docs.
///
/// Combines `#[cli]` + `#[markdown]` into a single attribute.
/// Markdown docs are included when the feature is enabled, and gracefully
/// omitted otherwise.
///
/// Named `program` instead of `cli` to avoid collision with the existing
/// `#[cli]` attribute macro.
///
/// # Example
///
/// ```ignore
/// use server_less::program;
///
/// struct MyApp;
///
/// #[program(name = "myctl", version = "1.0.0")]
/// impl MyApp {
///     pub fn create_user(&self, name: String) { println!("Created {}", name); }
///     pub fn list_users(&self) { println!("Listing users..."); }
/// }
/// ```
///
/// # Options
///
/// - `name` - CLI application name
/// - `version` - CLI version string
/// - `description` - CLI description
/// - `markdown` - Toggle Markdown docs generation (default: true)
#[cfg(feature = "cli")]
#[proc_macro_attribute]
pub fn program(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as program::ProgramArgs);
    let impl_block = parse_impl_block!(item, "program");
    check_not_empty_impl!(impl_block, "program");
    let name = type_name(&impl_block.self_ty);

    match program::expand_program(args, impl_block) {
        Ok(tokens) => {
            debug_emit("program", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Derive macro for error types that implement `IntoErrorCode`.
///
/// # Example
///
/// ```ignore
/// use server_less::ServerlessError;
///
/// #[derive(ServerlessError)]
/// enum MyError {
///     #[error(code = NotFound, message = "User not found")]
///     UserNotFound,
///     #[error(code = 400)]  // HTTP status also works
///     InvalidInput(String),
///     // Code inferred from variant name
///     Unauthorized,
/// }
/// ```
///
/// This generates:
/// - `impl IntoErrorCode for MyError`
/// - `impl Display for MyError`
/// - `impl Error for MyError`
///
/// # Attributes
///
/// - `#[error(code = X)]` - Set error code (ErrorCode variant or HTTP status)
/// - `#[error(message = "...")]` - Set custom message
///
/// Without attributes, the error code is inferred from the variant name.
#[proc_macro_derive(ServerlessError, attributes(error))]
pub fn serverless_error(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident.to_string();

    match error::expand_serverless_error(input) {
        Ok(tokens) => {
            debug_emit("ServerlessError", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Derive a standalone health-check endpoint.
///
/// Generates a `health_router()` method returning an `axum::Router` with a single
/// `GET` route (default `/health`) that responds with a fixed status string
/// (default `"ok"`). The `#[server]` preset already mounts a `/health` route; use
/// this derive to add one to a hand-rolled router.
///
/// # Attributes
///
/// - `#[health(path = "/healthz")]` — override the route path (default `/health`)
/// - `#[health(status = "alive")]` — override the response body (default `"ok"`)
///
/// # Example
///
/// ```ignore
/// #[derive(HealthCheck)]
/// #[health(path = "/healthz", status = "alive")]
/// struct Probe;
///
/// let app = Probe.health_router();
/// ```
#[cfg(feature = "health")]
#[proc_macro_derive(HealthCheck, attributes(health))]
pub fn health_check(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident.to_string();

    match health::expand_health_check(input) {
        Ok(tokens) => {
            debug_emit("HealthCheck", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}

/// Attach protocol-neutral application metadata to an impl block.
///
/// `#[app]` is consumed by all protocol macros on the same impl block
/// (`#[server]`, `#[cli]`, `#[http]`, `#[program]`, etc.).  It does not
/// generate code itself — it passes metadata downstream via an internal
/// `#[__app_meta]` helper attribute that the consuming macro removes.
///
/// # Fields
///
/// | Field | Default | Effect |
/// |-------|---------|--------|
/// | `name` | inferred from struct name (kebab-case) | App name used in config file path, CLI header, spec titles |
/// | `description` | none | Human-readable description for CLI `--help`, OpenAPI info, etc. |
/// | `version` | `env!("CARGO_PKG_VERSION")` | Version string; powers `--version`; `false` disables version entirely |
/// | `homepage` | none | URL used in OpenAPI `info.contact.url`, OpenRPC info, etc. |
///
/// # Example
///
/// ```ignore
/// #[app(
///     name = "myapp",
///     description = "Does the thing",
///     version = "2.1.0",
///     homepage = "https://myapp.example.com",
/// )]
/// #[server]
/// impl MyApi {
///     fn list_items(&self) -> Vec<Item> { ... }
/// }
/// ```
///
/// All preset macros also accept these fields inline as a shorthand:
///
/// ```ignore
/// #[server(name = "myapp", description = "Does the thing")]
/// impl MyApi { ... }
/// ```
#[proc_macro_attribute]
pub fn app(args: TokenStream, item: TokenStream) -> TokenStream {
    let args = proc_macro2::TokenStream::from(args);
    let input = parse_impl_block!(item, "app");
    match app::expand_app(args, input) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Internal helper attribute — do not use directly.
///
/// `#[__app_meta]` is injected by `#[app]` and consumed by downstream
/// protocol macros.  If it reaches the final compile step unconsumed
/// (e.g. you wrote `#[app(...)]` without any protocol macro), it is a
/// no-op that strips itself from the item.
#[proc_macro_attribute]
pub fn __app_meta(args: TokenStream, item: TokenStream) -> TokenStream {
    let args = proc_macro2::TokenStream::from(args);
    let input = parse_impl_block!(item, "__app_meta");
    app::expand_app_meta_passthrough(args, input).into()
}

/// Derive config loading from multiple sources for a struct.
///
/// `#[derive(Config)]` generates a [`server_less_core::config::ConfigLoad`]
/// implementation that loads values from defaults, TOML files, and environment
/// variables, with a configurable precedence order.
///
/// # Example
///
/// ```rust,ignore
/// use server_less::Config;
///
/// #[derive(Config)]
/// struct AppConfig {
///     #[param(default = "localhost")]
///     host: String,
///     #[param(default = 8080)]
///     port: u16,
///     #[param(env = "DATABASE_URL")]
///     database_url: String,
///     timeout_secs: Option<u64>,
/// }
///
/// let cfg = AppConfig::load(&[
///     ConfigSource::Defaults,
///     ConfigSource::File("app.toml".into()),
///     ConfigSource::Env { prefix: Some("APP".into()) },
/// ])?;
/// ```
///
/// # Field attributes
///
/// - `#[param(default = value)]` — compile-time default; field becomes optional in sources
/// - `#[param(env = "VAR")]` — exact env var name (overrides `{PREFIX}_{FIELD}` generation)
/// - `#[param(file_key = "a.b.c")]` — dotted TOML key override (default: field name)
/// - `#[param(help = "...")]` — description used by `config show --schema` and doc generators
#[cfg(feature = "config")]
#[proc_macro_derive(Config, attributes(param))]
pub fn derive_config(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident.to_string();
    match config_derive::expand_config(input) {
        Ok(tokens) => {
            debug_emit("Config", &name, &tokens);
            tokens.into()
        }
        Err(err) => err.to_compile_error().into(),
    }
}