autumn-macros 0.9.0

Proc macros for the Autumn web framework
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
#![allow(clippy::collapsible_else_if)]
//! # Autumn Macros
//!
//! Proc macros for the Autumn web framework.
//!
//! This crate provides:
//! - Route annotation macros (`#[get]`, `#[post]`, etc.)
//! - The `routes![]` collection macro
//! - The `#[autumn_web::main]` entry point macro (S-008)
//!
//! The database-layer macros (`#[model]`, `#[repository]`, `#[service]`)
//! live in the sibling crates `autumn-macros-model` and
//! `autumn-macros-repository`, so a build that never touches the database
//! never compiles their codegen. All three crates share parsing, path
//! rewriting, schema, and naming helpers through `autumn-macros-support`.
//!
//! Users should not depend on this crate directly — use `autumn-web` instead,
//! which re-exports everything.
//!
//! # Renamed or multi-versioned `autumn-web` dependencies (#1828)
//!
//! Every macro generates code that ultimately refers back to types in
//! `autumn-web` via absolute (`::`-rooted) paths like `::autumn_web::Route`.
//! By default that name is resolved automatically — via
//! [`proc-macro-crate`](https://docs.rs/proc-macro-crate) — from the
//! invoking crate's own `Cargo.toml`, so renaming the dependency (`web = {
//! package = "autumn-web" }`) just works with no macro changes.
//!
//! A crate that must depend on **two** differently-keyed copies of
//! `autumn-web` at once (e.g. mid-upgrade) is inherently ambiguous for that
//! automatic detection. Every attribute macro (`#[get]`, `#[model]`,
//! `#[repository]`, …) therefore also accepts an explicit `crate = "..."`
//! argument naming the extern-prelude identifier to use instead, e.g.
//! `#[get("/x", crate = "autumn_web_05")]`.

mod agent_authority;
mod api_doc;
mod authorize;
mod cached;
mod cached_impl;
mod collect;
mod edge;
mod edge_routes_macro;
mod event;
mod feature_flag;
mod graph;
mod i18n;
mod idempotency_guard;
mod inbound_mail;
mod job;
mod jobs_macro;
mod lifecycle;
mod listener;
mod listeners_macro;
mod mail_previews_macro;
mod mailer;
mod mailer_preview;
mod main_macro;
mod oauth2_callback;
mod obligation;
mod one_off_task;
mod one_off_tasks_macro;
mod openapi_schema;
mod param_helpers;
mod parse;
mod paths_macro;
mod public;
mod query_budget;
mod request_gate;
mod route;
mod routes_macro;
mod scheduled;
mod secured;
mod sim_test;
mod static_route;
mod static_routes_macro;
mod step_up;
mod story_macro;
mod tasks_macro;
mod throttle;
mod wire;
mod ws;

use proc_macro::TokenStream;

/// Annotate an async function as a GET route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function that
/// returns a `Route` pairing the path with an Axum
/// handler. In debug builds, `#[axum::debug_handler]` is automatically
/// applied for improved error messages. This has zero cost in release
/// builds.
///
/// # Example
///
/// ```ignore
/// use autumn_web::get;
///
/// #[get("/hello")]
/// async fn hello() -> &'static str {
///     "Hello, Autumn!"
/// }
/// ```
///
/// # Route-level SEO defaults
///
/// A `seo(...)` argument declares per-page meta tag values once on the route
/// instead of rebuilding them in every handler. Take a `SeoMeta` parameter and
/// it arrives pre-populated; the builder is consuming, so the handler refines
/// the defaults with per-request data:
///
/// ```ignore
/// use autumn_web::get;
/// use autumn_web::seo::SeoMeta;
///
/// #[get("/about", seo(title = "About • My Blog", description = "Learn about us"))]
/// async fn about(seo: SeoMeta) -> Markup {
///     html! { head { (seo.render()) } }
/// }
///
/// #[get("/posts/{slug}", seo(og_type = "article"))]
/// async fn show(slug: Path<String>, seo: SeoMeta) -> Markup {
///     let seo = seo.title(format!("{} • Blog", *slug));
///     html! { head { (seo.render()) } }
/// }
/// ```
///
/// Accepted keys mirror the `SeoMeta` builder: `title`, `description`,
/// `canonical`, `og_title`, `og_description`, `og_image`, `og_type`, `og_url`,
/// `twitter_card`, `twitter_title`, `twitter_description`, `twitter_image`,
/// and `robots`. Values must be string literals; an unknown, repeated, or
/// empty `seo(...)` is a compile error. Every HTTP route macro accepts the
/// argument, as does [`macro@static_get`]; [`macro@ws`] does not, since a
/// WebSocket upgrade serves no crawlable document.
///
/// The argument supplies *values*, not markup: a handler that never takes a
/// `SeoMeta` parameter renders nothing regardless of what the attribute
/// declares.
#[proc_macro_attribute]
pub fn get(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        route::route_macro("GET", "get", attr, item)
    })
    .into()
}

/// Annotate an async function as a POST route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function that
/// returns a `Route` pairing the path with an Axum
/// handler. In debug builds, `#[axum::debug_handler]` is automatically
/// applied for improved error messages. This has zero cost in release
/// builds.
///
/// # Example
///
/// ```ignore
/// use autumn_web::post;
///
/// #[post("/items")]
/// async fn create_item() -> &'static str {
///     "created"
/// }
/// ```
#[proc_macro_attribute]
pub fn post(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        route::route_macro("POST", "post", attr, item)
    })
    .into()
}

/// Annotate an async function as a PUT route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function that
/// returns a `Route` pairing the path with an Axum
/// handler. In debug builds, `#[axum::debug_handler]` is automatically
/// applied for improved error messages. This has zero cost in release
/// builds.
///
/// # Example
///
/// ```ignore
/// use autumn_web::put;
///
/// #[put("/items/{id}")]
/// async fn update_item() -> &'static str {
///     "updated"
/// }
/// ```
#[proc_macro_attribute]
pub fn put(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        route::route_macro("PUT", "put", attr, item)
    })
    .into()
}

/// Annotate an async function as a PATCH route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function and a typed
/// `__autumn_path_{name}(…) -> String` path helper.
///
/// # Example
///
/// ```ignore
/// use autumn_web::patch;
///
/// #[patch("/items/{id}")]
/// async fn patch_item() -> &'static str {
///     "patched"
/// }
/// ```
#[proc_macro_attribute]
pub fn patch(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        route::route_macro("PATCH", "patch", attr, item)
    })
    .into()
}

/// Annotate an async function as a DELETE route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function that
/// returns a `Route` pairing the path with an Axum
/// handler. In debug builds, `#[axum::debug_handler]` is automatically
/// applied for improved error messages. This has zero cost in release
/// builds.
///
/// # Example
///
/// ```ignore
/// use autumn_web::delete;
///
/// #[delete("/items/{id}")]
/// async fn remove_item() -> &'static str {
///     "removed"
/// }
/// ```
#[proc_macro_attribute]
pub fn delete(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        route::route_macro("DELETE", "delete", attr, item)
    })
    .into()
}

/// Annotate an OAuth2/OIDC callback handler.
///
/// This is a convenience alias for `#[get(\"...\")]`, intended for OAuth
/// callback endpoints such as `/auth/github/callback`.
#[proc_macro_attribute]
pub fn oauth2_callback(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        oauth2_callback::oauth2_callback_macro(attr, item)
    })
    .into()
}

/// Collect annotated route handlers into a `Vec<Route>`.
///
/// Each handler must have been annotated with a route macro (`#[get]`,
/// `#[post]`, etc.) which generates a companion
/// `__autumn_route_info_{name}()` function.
///
/// # Example
///
/// ```ignore
/// use autumn_web::{get, post, routes};
///
/// #[get("/hello")]
/// async fn hello() -> &'static str { "hello" }
///
/// #[post("/create")]
/// async fn create() -> &'static str { "created" }
///
/// let all_routes = routes![hello, create];
/// ```
#[proc_macro]
pub fn routes(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(routes_macro::routes_macro(input.into())).into()
}

/// Emit a `pub mod paths { … }` that re-exports each handler's typed path helper.
///
/// Takes the same comma-separated handler list as [`routes!`]. Each entry
/// exposes its `__autumn_path_{name}` companion under the short name:
///
/// ```ignore
/// autumn_web::paths![show_post, create_post, posts::index];
/// // expands to:
/// pub mod paths {
///     pub use super::__autumn_path_show_post as show_post;
///     pub use super::__autumn_path_create_post as create_post;
///     pub use super::posts::__autumn_path_index as index;
/// }
/// ```
///
/// Call this once at the top of the module where your handlers live (or a
/// sibling module) so consumers can write `use crate::routes::paths;` and
/// then `paths::show_post(id)`.
#[proc_macro]
pub fn paths(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(paths_macro::paths_macro(input.into())).into()
}

/// Set up the async runtime for an Autumn application.
///
/// This is a thin wrapper around `#[tokio::main]`. The real
/// framework setup happens in `autumn_web::app().run()`.
///
/// # Example
///
/// ```ignore
/// #[autumn_web::main]
/// async fn main() {
///     autumn_web::app()
///         .routes(routes![hello])
///         .run()
///         .await;
/// }
/// ```
///
/// # Runtime arguments
///
/// All optional; with none of them the runtime is
/// `Builder::new_multi_thread().enable_all()`, tokio's own defaults.
///
/// | Argument | Value | Effect |
/// | --- | --- | --- |
/// | `flavor` | `"multi_thread"` (default) or `"current_thread"` | picks the `Builder` constructor |
/// | `worker_threads` | `usize` expression | `Builder::worker_threads` (multi-thread only) |
/// | `max_blocking_threads` | `usize` expression | `Builder::max_blocking_threads` |
/// | `thread_name` | `Into<String>` expression | `Builder::thread_name` |
/// | `thread_stack_size` | `usize` expression | `Builder::thread_stack_size` |
/// | `thread_keep_alive` | duration string, e.g. `"30s"` | `Builder::thread_keep_alive` |
/// | `configure` | path to `fn(&mut tokio::runtime::Builder)` | runs last, after the arguments above |
///
/// ```ignore
/// fn tune_runtime(builder: &mut autumn_web::reexports::tokio::runtime::Builder) {
///     builder.on_thread_start(|| eprintln!("runtime thread started"));
/// }
///
/// #[autumn_web::main(worker_threads = 4, thread_name = "autumn-worker", configure = tune_runtime)]
/// async fn main() {
///     autumn_web::app().routes(routes![hello]).run().await;
/// }
/// ```
///
/// The numeric arguments take arbitrary expressions, not just literals, so
/// `worker_threads = std::thread::available_parallelism().map_or(4, |n| n.get())`
/// works. `configure` is the escape hatch for `Builder` methods this list does
/// not name.
#[proc_macro_attribute]
pub fn main(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        main_macro::main_macro(attr, item)
    })
    .into()
}

/// Annotate an async function as a deterministic simulation test (S-1797, W1).
///
/// Expands into a synchronous `#[test]` function that reads a seed from the
/// `AUTUMN_SIM_SEED` environment variable (hex `0x..` or decimal, default `0`),
/// builds a paused current-thread tokio runtime, constructs a
/// `autumn_web::sim::Sim` from the seed, runs the async body, and prints a
/// copy-pasteable replay line on panic before re-propagating the failure.
///
/// The annotated function must be `async` and take exactly one argument — the
/// [`Sim`](../autumn_web/sim/struct.Sim.html) handle.
///
/// # Example
///
/// ```ignore
/// use autumn_web::sim::Sim;
/// use autumn_web::sim_test;
///
/// #[sim_test]
/// async fn deterministic(mut sim: Sim) {
///     assert_eq!(sim.seed, 0);
/// }
/// ```
#[proc_macro_attribute]
pub fn sim_test(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        sim_test::sim_test_macro(attr, item)
    })
    .into()
}

/// Annotate an async inbound mail handler function.
///
/// Generates a companion `{name}_handler_info()` function that returns an
/// `InboundMailHandlerInfo` ready to be passed to `InboundMailRouter::handler`.
///
/// # Attributes
///
/// - `to = "address@example.com"` — exact recipient match.
/// - `to = "replies+{token}@app.example"` — plus-address routing; the captured
///   token is available via `InboundEmail::plus_token()`.
/// - `to = "prefix+*"` — local-part prefix match.
/// - `processing = "sync"` | `"background"` (default: `"background"`).
///
/// # Example
///
/// ```rust,ignore
/// #[inbound_mail(to = "support@company.com")]
/// async fn handle_support(email: InboundEmail) -> AutumnResult<()> {
///     tracing::info!(from = %email.from, "support email received");
///     Ok(())
/// }
///
/// // Registration:
/// InboundMailRouter::new()
///     .handler(handle_support_handler_info())
/// ```
#[proc_macro_attribute]
pub fn inbound_mail(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        inbound_mail::inbound_mail_macro(attr, item)
    })
    .into()
}

/// Generate `send_*` and `deliver_later_*` helpers for a mailer impl block.
#[proc_macro_attribute]
pub fn mailer(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        mailer::mailer_macro(attr, item)
    })
    .into()
}

/// Register zero-argument mail preview methods for the dev mail preview UI.
#[proc_macro_attribute]
pub fn mailer_preview(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        mailer_preview::mailer_preview_macro(attr, item)
    })
    .into()
}

/// Collect `#[mailer_preview]` impl blocks into runtime preview registrations.
#[proc_macro]
pub fn mail_previews(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(mail_previews_macro::mail_previews_macro(
        input.into(),
    ))
    .into()
}

/// Define a widget story for the `/_stories` gallery:
/// `story!{ "Group", "Name", { ... } }`.
///
/// The brace-delimited block is **both** executed for the live render and
/// captured byte-for-byte (comments and formatting included) as the displayed
/// source snippet, so the shown code is provably the code that rendered. The
/// block must be a self-contained expression evaluating to `maud::Markup`:
/// it is coerced to a plain `fn() -> Markup`, so capturing anything from the
/// surrounding environment is a compile error.
#[proc_macro]
pub fn story(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(story_macro::story_macro(input.into())).into()
}

/// Derive a field-accurate `OpenApiSchema` impl for a plain struct with named
/// fields, or a unit-variant enum (issue #1972).
///
/// Use it on a handler-arg type — a `Query<T>` param struct, a non-`#[model]`
/// `Json<T>` request body, or an enum appearing in either — so its `OpenAPI`
/// component schema and MCP tool `inputSchema` describe the real contract
/// instead of degrading to a generic `{"type":"object"}` placeholder, without a
/// hand-written impl or an `OpenApiConfig::register_schema` call.
///
/// **Structs**: each field becomes a JSON-schema property (nullable `Option<T>`,
/// `Vec<T>` arrays, inline primitives, `$ref`s for other named types) and every
/// non-`Option` field is `required` — mirroring the schema `#[model]` already
/// generates.
///
/// **Enums**: all-unit-variant enums become the closed string set
/// `{"type":"string","enum":[…]}` that serde puts on the wire, honoring
/// `#[serde(rename)]` / `#[serde(rename_all)]` / `#[serde(skip)]`. A
/// data-carrying variant is a compile error rather than a guess: serde's
/// representation for those depends on `#[serde(tag/content/untagged)]`, so an
/// inferred shape could confidently advertise a contract the handler does not
/// accept. Write the impl by hand and register it for that case.
///
/// **Two copies of `autumn-web`**: use `#[openapi_schema(crate = "name")]` to
/// name the copy that the generated code must use. A derive cannot take
/// arguments, so a helper attribute carries the override.
///
/// # Examples
///
/// ```ignore
/// use autumn_web::openapi::OpenApiSchema;
///
/// #[derive(serde::Deserialize, OpenApiSchema)]
/// struct SearchParams {
///     q: String,
///     limit: Option<i32>,
///     status: Option<Status>,
/// }
///
/// #[derive(serde::Deserialize, OpenApiSchema)]
/// #[serde(rename_all = "snake_case")]
/// enum Status {
///     Open,
///     InProgress,
/// }
/// ```
#[proc_macro_derive(OpenApiSchema, attributes(openapi_schema))]
pub fn derive_openapi_schema(input: TokenStream) -> TokenStream {
    openapi_schema::derive_openapi_schema(input.into()).into()
}

/// Declare a scheduled background task.
///
/// # Examples
///
/// ```ignore
/// #[scheduled(every = "5m", name = "cleanup")]
/// async fn cleanup(state: AppState) -> AutumnResult<()> { Ok(()) }
///
/// #[scheduled(cron = "0 0 0 * * *", name = "nightly")]
/// async fn nightly(state: AppState) -> AutumnResult<()> { Ok(()) }
/// ```
///
/// Add `deferrable` to let a task wait while the cost signal is high
/// (`[cost] defer_threshold`). The tick takes its lease, then waits. It runs
/// when the signal falls. Later ticks fold into that run. See
/// `docs/guide/cost.md`.
///
/// ```ignore
/// #[scheduled(every = "15m", deferrable)]
/// async fn compact(state: AppState) -> AutumnResult<()> { Ok(()) }
/// ```
#[proc_macro_attribute]
pub fn scheduled(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        scheduled::scheduled_macro(attr, item)
    })
    .into()
}

/// Declare an on-demand background job.
///
/// Route latency-sensitive work to a named queue with `queue = "..."`. Workers
/// drain queues in the priority order configured under `[jobs] queues` in
/// `autumn.toml`, so a flood of low-priority jobs can't delay a critical one.
/// Jobs with no `queue` land on the `"default"` queue.
///
/// ```ignore
/// #[job(queue = "critical", max_attempts = 5)]
/// async fn send_password_reset(state: AppState, args: ResetArgs) -> AutumnResult<()> {
///     Ok(())
/// }
///
/// // autumn.toml — strict priority (or weighted: { critical = 4, default = 1 }):
/// // [jobs]
/// // queues = ["critical", "default", "low"]
/// SendPasswordResetJob::enqueue(ResetArgs { user_id: 1 }).await?;
/// ```
///
/// Accept an optional third `JobContext` argument to report progress and
/// record a terminal result/error for jobs enqueued with `enqueue_tracked`
/// (the companion struct gains `enqueue_tracked` / `enqueue_tracked_for`
/// alongside `enqueue`):
///
/// ```ignore
/// #[job(name = "export_orders")]
/// async fn export_orders(state: AppState, args: ExportArgs, ctx: JobContext) -> AutumnResult<()> {
///     ctx.set_progress(50, Some("Rows 1200/5000")).await?;
///     ctx.set_result(serde_json::json!({ "download_url": "/blob/abc.csv" }));
///     Ok(())
/// }
///
/// let handle = ExportOrdersJob::enqueue_tracked(ExportArgs { account_id: 1 }).await?;
/// println!("poll at {}", handle.status_path());
/// ```
///
/// Add `deferrable` to let a job wait while the cost signal is high
/// (`[cost] defer_threshold`). The job runs when the signal falls. The runtime
/// never drops it. It uses no attempt while it waits. Only the `local` jobs
/// backend defers jobs. Other backends run the job and log a warning at boot.
/// See `docs/guide/cost.md`.
///
/// ```ignore
/// #[job(deferrable)]
/// async fn rebuild_search_index(state: AppState, args: RebuildArgs) -> AutumnResult<()> {
///     Ok(())
/// }
/// ```
#[proc_macro_attribute]
pub fn job(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        job::job_macro(attr, item)
    })
    .into()
}

/// Declare a typed domain event.
///
/// Applies the serde + `Clone`/`Debug` derives the event bus needs and
/// implements `autumn_web::events::Event` with a stable `NAME` (the struct
/// name by default, or `#[event(name = "...")]`).
///
/// ```ignore
/// #[event]
/// struct UserSignedUp { user_id: i64 }
/// ```
#[proc_macro_attribute]
pub fn event(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        event::event_macro(attr, item)
    })
    .into()
}

/// Declare an event listener that reacts to a typed `#[event]`.
///
/// Runs **synchronously** (in-request) by default, or **durably** (enqueued on
/// the `#[job]` queue, surviving restarts with retry + DLQ) with `durable`.
///
/// ```ignore
/// #[listener(UserSignedUp, durable, max_attempts = 5)]
/// async fn send_welcome_email(state: AppState, event: UserSignedUp) -> AutumnResult<()> { Ok(()) }
/// ```
#[proc_macro_attribute]
pub fn listener(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        listener::listener_macro(attr, item)
    })
    .into()
}

/// Collect `#[listener]` handlers into a `Vec<ListenerInfo>`.
#[proc_macro]
pub fn listeners(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(listeners_macro::listeners_macro(input.into()))
        .into()
}

/// Declare a one-off operational task runnable with `autumn task <name>`.
#[proc_macro_attribute]
pub fn task(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        one_off_task::task_macro(attr, item)
    })
    .into()
}

/// Annotate an async function as a statically pre-rendered GET route.
///
/// Like `#[get]`, this generates a route companion function. Additionally,
/// it generates a `__autumn_static_meta_{name}()` companion that registers
/// the route for static HTML generation at build time.
///
/// Phase 1: path parameters are **not** supported. Use `#[get]` for
/// parameterized routes.
///
/// # Example
///
/// ```ignore
/// use autumn_web::static_get;
///
/// #[static_get("/about")]
/// async fn about() -> &'static str {
///     "About us"
/// }
/// ```
///
/// # Route-level SEO defaults
///
/// Accepts the same `seo(...)` argument as [`macro@get`], so pre-rendered
/// pages carry the declared meta tags. Static generation drives the same
/// router as the live server, so the values reach the handler identically in
/// both modes:
///
/// ```ignore
/// #[static_get("/about", seo(title = "About • My Blog", og_type = "website"))]
/// async fn about(seo: SeoMeta) -> Markup {
///     html! { head { (seo.render()) } }
/// }
/// ```
///
/// # Declared Content-Type
///
/// `content_type = "..."` sets the media type of the pre-rendered page:
///
/// ```ignore
/// #[static_get("/logo.png", content_type = "application/octet-stream")]
/// async fn logo() -> Vec<u8> {
///     logo_bytes()
/// }
/// ```
///
/// Build records the value as written. It replaces any header the handler
/// sets. Autumn does not swap it for the route extension type. Without the
/// argument, Autumn records the handler header, and replaces the axum
/// return-type defaults (`text/plain; charset=utf-8`, `application/octet-stream`)
/// with the extension type.
///
/// The value must be a non-empty media type in visible ASCII. The type only
/// applies to the page served from `dist/`. A live request that reaches the
/// handler gets the handler header. Compression follows the declared type.
#[proc_macro_attribute]
pub fn static_get(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        static_route::static_get_macro(attr, item)
    })
    .into()
}

/// Collect `#[scheduled]` task handlers into a `Vec<TaskInfo>`.
///
/// ```ignore
/// let all_tasks = tasks![cleanup, nightly];
/// ```
#[proc_macro]
pub fn tasks(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(tasks_macro::tasks_macro(input.into())).into()
}

/// Collect `#[job]` handlers into a `Vec<JobInfo>`.
#[proc_macro]
pub fn jobs(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(jobs_macro::jobs_macro(input.into())).into()
}

/// Collect `#[task]` handlers into a `Vec<OneOffTaskInfo>`.
#[proc_macro]
pub fn one_off_tasks(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(one_off_tasks_macro::one_off_tasks_macro(
        input.into(),
    ))
    .into()
}

/// Secure a route handler with authentication and optional role checks.
///
/// Applied before a route macro (`#[get]`, `#[post]`, etc.), this macro
/// injects an authentication guard at the top of the handler. The guard
/// checks the session for the configured auth key (default: `"user_id"`)
/// and, when roles are specified, verifies the user's role matches.
///
/// Returns `401 Unauthorized` if not authenticated, or `403 Forbidden`
/// if the user lacks the required role.
///
/// # Forms
///
/// - `#[secured]` -- require authentication only
/// - `#[secured("admin")]` -- require a specific role
/// - `#[secured("admin", "editor")]` -- require any of the listed roles
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[get("/admin")]
/// #[secured("admin")]
/// async fn admin_panel() -> AutumnResult<&'static str> {
///     Ok("welcome, admin")
/// }
/// ```
#[proc_macro_attribute]
pub fn secured(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        secured::secured_macro(attr, item)
    })
    .into()
}

/// Declare a route handler as deliberately public (unauthenticated).
///
/// `#[public]` injects no runtime guard — it is a compile-time *marker* that
/// records intent. The route macros surface it as `ApiDoc::public`, which the
/// build-time security classifier (`autumn routes audit`) uses to distinguish
/// a route that is *meant* to be open from one whose auth posture was simply
/// never declared. Applying it makes an otherwise-unclassified route pass the
/// audit gate, exactly like adding a [`#[secured]`](macro@secured) guard does.
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[get("/health")]
/// #[public]
/// async fn health() -> &'static str { "ok" }
/// ```
#[proc_macro_attribute]
pub fn public(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        public::public_macro(attr, item)
    })
    .into()
}

/// Declare a read-path route as eligible to run in the edge capsule (#1790).
///
/// `#[edge]` injects no runtime guard and does not rewrite the handler
/// signature — it is a compile-time *marker*, like
/// [`#[public]`](macro@public). The route macro reads it back and emits an
/// extra `__autumn_edge_route_{name}()` companion returning an
/// `autumn_edge::EdgeRoute`, while gating the native (`autumn_web`) companions
/// behind `#[cfg(not(target_arch = "wasm32"))]` so the same handler source
/// compiles for both the origin binary and the `wasm32-wasip1` capsule.
/// Marking a handler makes it *eligible*; listing it in
/// [`edge_routes!`](macro@edge_routes) is what puts it in the capsule.
///
/// # Forms
///
/// - `#[edge]` — the handler needs no platform seam
/// - `#[edge(needs(kv))]` — the handler reads the edge key-value cache
///   (`autumn_edge::EdgeCache`), which the host must provide; a request
///   arriving at an edge without that capability falls through to the origin
///
/// # Restrictions
///
/// The edge lane is read-path only and carries no session, auth, or database
/// state, so these are compile errors:
///
/// - a method other than `#[get]`;
/// - combining with `#[secured]`, `#[authorize]`, `#[step_up]`, or
///   `#[throttle]` (in either attribute order);
/// - `#[static_get]` (already pre-rendered), `#[ws]`, or `#[oauth2_callback]`.
///
/// # Example
///
/// ```ignore
/// use autumn_edge::prelude::{EdgeCache, Path};
/// use autumn_web::{edge, get};
///
/// #[get("/greet/{name}")]
/// #[edge]
/// async fn greet(Path(name): Path<String>) -> String {
///     format!("Hello, {name}!")
/// }
///
/// #[get("/note/{id}")]
/// #[edge(needs(kv))]
/// async fn note(Path(id): Path<String>, cache: EdgeCache) -> String {
///     cache.get_string(&id).unwrap_or_else(|| "not cached".to_owned())
/// }
/// ```
#[proc_macro_attribute]
pub fn edge(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        edge::edge_macro(attr, item)
    })
    .into()
}

/// Collect `#[edge]` handlers into a `Vec<EdgeRoute>` (#1790).
///
/// The edge-lane counterpart of [`routes!`](macro@routes): each entry resolves
/// to the handler's `__autumn_edge_route_{name}()` companion, so a handler that
/// was never marked `#[edge]` fails to resolve rather than silently vanishing
/// from the capsule.
///
/// ```ignore
/// use autumn_web::{edge, edge_routes, get};
///
/// #[get("/greet")]
/// #[edge]
/// async fn greet() -> &'static str { "hi" }
///
/// pub fn edge_routes() -> Vec<autumn_edge::EdgeRoute> {
///     edge_routes![greet]
/// }
/// ```
#[proc_macro]
pub fn edge_routes(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(edge_routes_macro::edge_routes_macro(input.into()))
        .into()
}

/// Require fresh ("step-up") authentication before a route handler runs.
///
/// The handler is guarded by a freshness check on the session's
/// `last_strong_auth_at` claim. When the claim is missing or older than
/// `max_age` the request is handled as follows:
///
/// - **Browser clients** (no `application/json` in `Accept`): redirect to
///   `/reauth?return_to=<current-path>`.
/// - **API / JSON clients** (`Accept: application/json`): `401 Unauthorized`
///   with an RFC 7807 problem-details body (`type` =
///   `"https://autumn.rs/probs/step-up-required"`) and a
///   `WWW-Authenticate: StepUp max-age=N` hint header.
///
/// # Forms
///
/// - `#[step_up]` — default max-age (5 minutes, or the global `[auth.step_up]`
///   config override)
/// - `#[step_up(max_age = "5m")]` — custom per-route max-age
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// // Requires re-authentication within the last 5 minutes.
/// #[delete("/account")]
/// #[step_up]
/// async fn destroy_account() -> AutumnResult<Redirect> {
///     // ... delete account ...
///     Ok(Redirect::to("/bye"))
/// }
///
/// // Custom max-age.
/// #[post("/auth/mfa/remove")]
/// #[step_up(max_age = "2m")]
/// async fn remove_mfa() -> AutumnResult<&'static str> {
///     Ok("MFA removed")
/// }
/// ```
#[proc_macro_attribute]
pub fn step_up(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        step_up::step_up_macro(attr, item)
    })
    .into()
}

/// Apply a per-route rate limit to a handler.
///
/// The handler is guarded by an additional rate limiter that composes with
/// (and, for the annotated route, is stricter than) the global limiter
/// configured under `[security.rate_limit]`. Requests denied by either
/// limiter respond with `429 Too Many Requests` including a `Retry-After`
/// header and the standard `x-ratelimit-*` headers.
///
/// # Forms
///
/// - `#[throttle(limit = 5, per = "1m")]` — inline limit; keying strategy
///   matches the global limiter.
/// - `#[throttle(limit = 5, per = "1m", key = "ip" | "principal" | "token")]`
///   — inline limit with an explicit key strategy override.
/// - `#[throttle("login")]` — reference a named limiter defined in
///   `[security.rate_limit.named.login]`.
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[post("/login")]
/// #[throttle(limit = 5, per = "1m", key = "ip")]
/// async fn login() -> AutumnResult<&'static str> {
///     Ok("welcome back")
/// }
/// ```
///
/// # Limitations
///
/// Like the sibling `#[secured]` / `#[step_up]` guards it mirrors, the throttle
/// check runs inside the handler after `FromRequestParts` extractors, but body
/// extractors (`Json` / `Form` / `Multipart`) are parsed by Axum *before* the
/// throttle check, so an over-limit client can still incur request-body parsing
/// before receiving its `429`. For hard pre-body protection, combine with the
/// global limiter layer under `[security.rate_limit]`.
///
/// # Attribute ordering
///
/// `#[throttle]` may be written above or below the route method attribute
/// (`#[get]` / `#[post]` / …) — both orders enforce throttling identically
/// (including idempotency-replay accounting) and both produce the same
/// `OpenAPI` response schema. When `#[throttle]` expands first it rewrites
/// the return type to `Response` (like the sibling `#[secured]` / `#[step_up]`
/// / `#[authorize]` guards), but the route macro recovers the original
/// `Json<T>` return type from the guard's generated body, so response-schema
/// inference does not depend on expansion order (#1677).
#[proc_macro_attribute]
pub fn throttle(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        throttle::throttle_macro(attr, item)
    })
    .into()
}

/// Bound the number of database queries a handler can issue — at compile time.
///
/// `#[query_budget(N)]` fails the build when any statically reachable path
/// through the handler can issue more than `N` queries. The canonical case is
/// the N+1: a repository or `Db` call inside a loop over a runtime-sized
/// collection. Because the gate runs during `cargo build`, it fires on every
/// branch — including the ones no test exercises.
///
/// # Example
///
/// ```ignore
/// use autumn_web::{get, query_budget};
///
/// #[get("/posts")]
/// #[query_budget(2)]
/// async fn index(repo: PgPostRepository) -> AutumnResult<Markup> {
///     let posts = repo.find_all().await?;                              // 1
///     let posts = repo.preload(posts, Post::preload().author()).await?; // 2
///     Ok(render(&posts))
/// }
/// ```
///
/// Written with a per-row `repo.find_author(...)` inside a `for` loop instead,
/// the same handler fails to compile with a diagnostic pointing at the loop.
///
/// # How the count is computed
///
/// * Straight-line statements **sum**; `if` / `match` arms take the
///   **maximum** (the worst reachable path).
/// * A loop whose body issues a query is **unbounded**, unless the iterable
///   has a literal compile-time bound (`for _ in 0..3`), in which case the
///   body cost is multiplied. A path that leaves the loop is paid once.
/// * A method chain rooted at a `Db` / repository handle is **one** query,
///   however many builder methods (`on_primary()`, `scoped()`, …) it carries.
/// * `.preload(rows, Post::preload().author().tags())` costs **one query per
///   association** — the batched `WHERE ... IN (...)` loads.
/// * A path that leaves early (`return`, `break`, `continue`) does not include
///   the cost of the code it skips.
/// * Anything opaque — a helper function or associated function handed the
///   handle (`Post::published(&mut db)`), a macro body that names it, a
///   closure that may run per element — is **reported**, never assumed
///   query-free.
///
/// # Escape hatches
///
/// * `#[query_budget(unbounded, reason = "…")]` — opt the whole handler out.
/// * `#[query_cost(N)]` on a statement — declare an opaque call's cost.
/// * `#[query_exempt(reason = "…")]` on a statement — drop it from the ledger.
///
/// Both statement annotations are consumed by this macro and never reach
/// rustc. See `docs/guide/query-budgets.md` for the full guide.
#[proc_macro_attribute]
pub fn query_budget(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        query_budget::query_budget_macro(attr, item)
    })
    .into()
}

/// Declare a handler agent-operable, under a named authority grant.
///
/// `#[agent_operable(grant = RefundDrafter)]` walks the handler body, derives
/// the effects it can prove — row writes, unbounded writes, cross-tenant
/// access, outbound HTTP, webhook fan-out, background jobs — and fails the
/// build when the named `authority_grant!` does not allow one of them. The
/// check is a `const` assertion respanned onto the offending call site, so it
/// works across crates and fires during `cargo build` on every branch,
/// including the ones no test exercises.
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// autumn_web::authority_grant! {
///     /// Draft-only refund authority for the support agent.
///     pub RefundDrafter {
///         writes: [Refund],
///         outbound: ["https://api.stripe.com/v1/refunds"],
///         jobs: [NotifyFinanceJob],
///         reversibility: compensable,
///     }
/// }
///
/// #[post("/refunds")]
/// #[api_doc(mcp, summary = "Draft a refund")]
/// #[agent_operable(grant = RefundDrafter)]
/// async fn draft_refund(
///     repo: PgRefundRepository,
///     payouts: PgPayoutRepository,
///     client: Client,
///     Json(body): Json<NewRefund>,
/// ) -> AutumnResult<Json<Refund>> {
///     let refund = repo.create(&body).await?;               // allowed: `writes: [Refund]`
///     client.post("https://api.stripe.com/v1/refunds")      // allowed: `outbound: [...]`
///         .json(&refund)
///         .send()
///         .await?;
///     NotifyFinanceJob::enqueue(NotifyFinanceArgs { refund_id: refund.id }).await?;
///     Ok(Json(refund))
/// }
/// ```
///
/// Adding `payouts.delete_all().await?` to that body fails the build: `payouts`
/// is a tracked repository handle, and the grant allows no unbounded write to
/// `Payout`.
///
/// # What is proved, and what is only declared
///
/// * A write, unbounded write or cross-tenant access reached through a handle
///   named in the signature is **proved**.
/// * An outbound call with a literal absolute URL is **proved**; one whose host
///   is resolved from config through a named client is **declared**.
/// * A webhook dispatch delivers to subscriber-supplied URLs, so it is granted
///   by topic (`webhooks: ["refund.drafted"]`), never by URL prefix.
/// * `rate` / `spend` caps are **declared**: this slice records them, it does
///   not enforce them.
/// * Anything opaque — a helper handed the handle, a `format!`-built URL, a
///   `tokio::spawn` that detaches the effect from the request it is audited
///   under — is reported, never assumed effect-free. A helper is opaque
///   whether it is free (`wipe(repo)`) or associated (`Billing::wipe(repo)`):
///   an associated function is another function's business too, and a static
///   finder that really only reads (`Post::find_published(&mut db)`) is
///   discharged with `#[agent_effect(none, reason = "…")]` rather than
///   assumed. A local alias for an effect verb (`let schedule =
///   NotifyFinanceJob::enqueue;`) is classified against the path it names.
///
/// # Escape hatch
///
/// `#[agent_effect(...)]` on a statement declares what the analysis cannot
/// read: `#[agent_effect(writes(Refund), reason = "…")]`, or
/// `#[agent_effect(none, reason = "…")]` for a statement verified
/// effect-free. Declared effects are still checked against the grant — the
/// hatch declares, it never grants — and a `reason` is mandatory. The
/// annotation is consumed by this macro and never reaches rustc.
///
/// See `docs/guide/agent-authority.md` for the full guide.
#[proc_macro_attribute]
pub fn agent_operable(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        agent_authority::agent_operable_macro(attr, item)
    })
    .into()
}

/// Gate a route handler on a named feature flag.
///
/// If the flag is disabled for the current actor, the handler responds with
/// `404 Not Found` by default. Provide a `fallback` function to return a
/// custom response instead.
///
/// The flag key is resolved against the `FeatureFlagService` stored in the
/// `AppState` extensions. Unknown flags are treated as **disabled**
/// (fail-closed).
///
/// # Forms
///
/// - `#[feature_flag("key")]` — return 404 when disabled
/// - `#[feature_flag("key", fallback = my_fn)]` — call `my_fn()` when disabled
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[get("/beta")]
/// #[feature_flag("beta_dashboard")]
/// async fn beta_dashboard() -> Markup {
///     html! { h1 { "Beta Dashboard" } }
/// }
/// ```
///
#[proc_macro_attribute]
pub fn feature_flag(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        feature_flag::feature_flag_macro(attr, item)
    })
    .into()
}

/// Enforce a record-level authorization policy on a route handler.
///
/// Resolves the `Policy`
/// registered for the named resource type and calls the matching
/// action method. Short-circuits with the configured deny response
/// (default `404`, optionally `403`) before the handler body runs.
///
/// Coexists with `#[secured]`: `#[secured]` answers "are you in?",
/// `#[authorize]` answers "are you allowed to act on *this record*?"
///
/// # Forms
///
/// ```ignore
/// // Resource arg is auto-detected by snake-cased type name (Post -> `post`).
/// #[authorize("update", resource = Post)]
/// async fn update_post(post: Post) -> AutumnResult<...> { ... }
///
/// // Explicit binding name (overrides the snake-case default).
/// #[authorize("delete", resource = Post, from = target)]
/// async fn destroy(target: Post) -> AutumnResult<...> { ... }
/// ```
#[proc_macro_attribute]
pub fn authorize(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        authorize::authorize_macro(attr, item)
    })
    .into()
}

/// Collect `#[static_get]` handlers into a `Vec<StaticRouteMeta>`.
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[static_get("/about")]
/// async fn about() -> &'static str { "About" }
///
/// let metas = static_routes![about];
/// ```
#[proc_macro]
pub fn static_routes(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(static_routes_macro::static_routes_macro(
        input.into(),
    ))
    .into()
}

/// Mark a typed handler as a service endpoint (issue #1755).
///
/// **Experimental** — see `STABILITY.md`.
///
/// Emits a marker type — `<name>_endpoint` — implementing
/// `autumn_web::wire::Endpoint`, and writes the endpoint's JSON wire
/// descriptor as a build artifact. The handler itself is untouched.
///
/// Everything comes from the handler's own signature and the route attribute
/// below it: the `Json<T>` parameter is the request shape, the `Json<T>` in the
/// return type is the response shape, and the route attribute supplies the
/// method and path.
///
/// # Placement
///
/// `#[endpoint]` must sit **above** the route attribute. A route attribute
/// placed outermost expands first and rewrites the signature, leaving nothing
/// to read.
///
/// ```rust,ignore
/// #[endpoint(service = "catalog")]
/// #[get("/items/{id}")]
/// async fn get_item(id: Path<String>) -> AutumnResult<Json<Item>> { … }
/// ```
///
/// # Arguments
///
/// | Argument | Required | Description |
/// |---|---|---|
/// | `service` | yes | The service this endpoint belongs to |
/// | `name` | no | Endpoint name; defaults to the handler's function name |
#[proc_macro_attribute]
pub fn endpoint(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        wire::endpoint::endpoint_macro(attr, &item)
    })
    .into()
}

/// Generate a typed client for another Autumn service's endpoints (issue #1755).
///
/// **Experimental** — see `STABILITY.md`.
///
/// ```rust,ignore
/// wire_client! {
///     name = CatalogClient,
///     endpoints = [
///         catalog::get_item_endpoint(id),
///         catalog::create_item_endpoint,
///     ],
/// }
/// ```
///
/// Each entry names an endpoint marker and, in parentheses, the path
/// parameters its route takes. Request and response types come from the
/// marker's associated types, so they are the callee's own types. A const
/// assertion holds the declared path parameters to the endpoint's real path.
#[proc_macro]
pub fn wire_client(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(wire::client::wire_client_macro(input.into()))
        .into()
}

/// Check every service call in a function against the callee's contract
/// (issue #1755).
///
/// **Experimental** — see `STABILITY.md`.
///
/// ```rust,ignore
/// #[contract_checked(client = CatalogClient)]
/// async fn page(catalog: CatalogClient, id: Path<String>) -> AutumnResult<Markup> {
///     let item = catalog.get_item(&*id, NoBody).await?;
///     Ok(html! { h1 { (item.name) } })
/// }
/// ```
///
/// Every response field the function names, and every request field an inline
/// literal sets, becomes a const assertion against the callee's own field
/// table. A field the endpoint no longer produces — or a required field a
/// `..rest` initializer omits — fails the build at the call site.
///
/// Repeat `client = …` for a function that calls more than one service. A
/// declared client with no value in the function is an error, so the attribute
/// can never pass by checking nothing.
#[proc_macro_attribute]
pub fn contract_checked(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        wire::checked::contract_checked_macro(attr, &item)
    })
    .into()
}

/// Derive a type's serde-visible wire shape (issue #1755).
///
/// **Experimental** — see `STABILITY.md`.
///
/// Emits two const field tables — what the type puts on the wire and what it
/// takes off it — and writes the type's JSON descriptor as a build artifact.
/// `#[contract_checked]` asserts against those tables.
///
/// The two tables differ under directional serde attributes, and that is the
/// point: a field carrying `#[serde(skip_serializing)]` is accepted but never
/// produced, so a caller reading it is broken even though the code compiles.
///
/// Refused rather than guessed at: generics, enums, tuple structs,
/// `#[serde(flatten)]`, and split `rename(serialize = …, deserialize = …)`.
#[proc_macro_derive(WireShape)]
pub fn derive_wire_shape(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    let parsed = syn::parse_macro_input!(input as syn::DeriveInput);
    let out = match wire::shape::derive_wire_shape(&parsed) {
        Ok(ts) => ts,
        Err(err) => err.to_compile_error(),
    };
    autumn_macros_support::crate_path::finalize(out).into()
}

/// Cache the return value of a function based on its arguments.
///
/// Wraps a function with an in-memory cache backed by a per-function
/// static `Cache` (from `autumn_web::cache::Cache`). Key arguments
/// must implement `Hash + Eq + Clone`; the return type must be `Clone`.
///
/// # Attributes
///
/// | Attribute | Example | Description |
/// |-----------|---------|-------------|
/// | `ttl` | `"5m"` | Time-to-live per entry (uses `parse_duration` syntax) |
/// | `max` | `1000` | Max entries; oldest evicted on overflow |
/// | `result` | (flag) | Only cache `Ok` values; pass `Err` through uncached |
/// | `key` | `key(tenant_id)` | Build the key from *these* parameters only |
/// | `reads` | `reads(Post, Comment)` | Declared cache-coherence dependency set |
/// | `acknowledge_stale` | `"5s TTL is tight enough"` | Opt out of the coherence gate |
/// | `scope` | `"Products"` | Enclosing type; keeps same-named associated functions apart |
///
/// # Associated functions
///
/// The cache key holds the module and function name. Two impls in one module
/// with a same-named `#[cached]` function would share keys. Put
/// [`cached_impl`] on each `impl` block, or set `scope` by hand.
///
/// # Cache coherence (issue #1716)
///
/// Every annotated function publishes which models its value is derived from,
/// and `autumn cache audit` fails the build when a `#[repository]` write can
/// leave that value stale with no invalidation covering the pair. `reads(...)`
/// declares the dependency set; without it the macro derives what it can from
/// the signature and body, and a function nothing could be recovered from is
/// recorded as `undetermined` — reported, never gated. See
/// `docs/guide/cache-coherence.md`.
///
/// # Examples
///
/// ```ignore
/// use autumn_web::cached;
///
/// // Cache with 5-minute TTL, max 100 entries, only cache Ok values
/// #[cached(ttl = "5m", max = 100, result)]
/// async fn get_user(id: i64) -> AutumnResult<User> {
///     db.find(id).await
/// }
///
/// // A repository-backed read: the handle is not part of the value's
/// // identity, so `key(...)` keeps it out of the cache key, and `reads(...)`
/// // tells the coherence gate what a write to `Project` would strand.
/// #[cached(ttl = "30s", key(tenant_id), reads(Project), result)]
/// async fn project_count(tenant_id: String, repo: &PgProjectRepository)
///     -> AutumnResult<i64>
/// {
///     repo.count().await
/// }
///
/// // Cache forever with no size limit
/// #[cached]
/// async fn get_config() -> Vec<String> {
///     load_config_from_disk()
/// }
/// ```
#[proc_macro_attribute]
pub fn cached(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        cached::cached_macro(attr, item)
    })
    .into()
}

/// Scope every `#[cached]` method of an `impl` block by its type.
///
/// Adds `scope = "<Type>"` to each `#[cached]` method, so `Products::get` and
/// `Reviews::get` in one module get different cache keys.
///
/// ```ignore
/// #[autumn_web::cached_impl]
/// impl Products {
///     #[cached]
///     async fn get(id: i64) -> String { /* .. */ }
/// }
/// ```
#[proc_macro_attribute]
pub fn cached_impl(attr: TokenStream, item: TokenStream) -> TokenStream {
    let (crate_override, attr) =
        match autumn_macros_support::crate_path::extract_crate_override(attr.into()) {
            Ok(pair) => pair,
            Err(err) => return err.into(),
        };
    let _guard = autumn_macros_support::crate_path::set_target(crate_override.as_deref());
    autumn_macros_support::crate_path::finalize(cached_impl::cached_impl_macro(
        attr,
        item.into(),
        crate_override.as_deref(),
    ))
    .into()
}

/// Enrich a route handler's auto-generated `OpenAPI` documentation.
///
/// Applied on top of a route macro (`#[get]`, `#[post]`, etc.), this
/// attribute lets you override or add documentation fields that cannot
/// be inferred from the handler signature (summaries, descriptions,
/// tags, custom success status codes).
///
/// The route macro consumes this attribute and folds the metadata into
/// the route's `ApiDoc`. When no route macro is applied, the attribute
/// is a no-op.
///
/// # Supported keys
///
/// | Key | Type | Effect |
/// |-----|------|--------|
/// | `summary` | string | Short one-line description |
/// | `description` | string | Longer multi-line description |
/// | `tag` | string | Single `OpenAPI` tag for grouping |
/// | `tags` | `[string, ...]` | Multiple `OpenAPI` tags |
/// | `operation_id` | string | Override the default operation id |
/// | `status` | integer | Success HTTP status code (defaults to `200`) |
/// | `hidden` | flag / bool | Exclude the route from the generated spec |
/// | `mcp` | flag / bool | Expose this endpoint as an MCP tool (`mcp = false` force-excludes it). Requires the `mcp` feature and a `mount_mcp` call. |
/// | `stream` | flag / bool | With `mcp`: the tool returns an `Sse` stream, sent as MCP progress. |
/// | `task` | flag / bool | With `mcp`: the tool can return a task handle (MCP Tasks extension). |
/// | `core` | flag / bool | With `mcp`: a core tool. A client that defers tools loads it first. |
/// | `webmcp` | flag / bool | Expose this endpoint as a `WebMCP` tool in the page (`webmcp = false` force-excludes it). `mcp` does not imply it. Requires the `webmcp` feature and a `mount_webmcp` call. |
///
/// # Examples
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[get("/users/{id}")]
/// #[api_doc(summary = "Fetch a user by id", tag = "users")]
/// async fn get_user(Path(id): Path<i32>) -> String {
///     format!("User {id}")
/// }
///
/// #[post("/users")]
/// #[api_doc(description = "Create a new user", status = 201)]
/// async fn create_user(Json(req): Json<serde_json::Value>) -> Json<serde_json::Value> {
///     Json(req)
/// }
///
/// #[get("/internal/metrics")]
/// #[api_doc(hidden)]
/// async fn metrics() -> &'static str { "" }
/// ```
#[proc_macro_attribute]
pub fn api_doc(attr: TokenStream, item: TokenStream) -> TokenStream {
    // Rust expands attribute macros top-down (outermost first), so if the
    // user writes
    //
    //   #[api_doc(summary = "...")]
    //   #[get("/x")]
    //   async fn handler() { ... }
    //
    // this macro fires BEFORE `#[get]` and would strip `#[api_doc]` from
    // the item — the route macro would then never see the overrides.
    //
    // To support both orderings, we detect any pending route attribute
    // (`get`, `post`, etc.) sitting below us and reorder: we remove the
    // route attribute and emit it as the NEW outermost attribute, and
    // we re-attach `#[api_doc(...)]` to the function body. Rust then
    // expands the route macro next, which finds and consumes the
    // preserved `#[api_doc]` via the usual attribute-list walk.
    //
    // `#[api_doc(...)]` never itself emits an `::autumn_web` path — it only
    // reorders attributes for the paired route macro to expand next, and
    // that route macro's own `crate = "..."` (see `get`, `post`, etc.) is
    // what actually governs the combined expansion. Still strip a `crate =
    // "..."` given here (rather than leaving it for the reordering below to
    // re-embed and only later fail with a confusing raw parse error out of
    // `api_doc::extract`), so every attribute macro accepts and validates
    // the argument uniformly even though this one has nothing to apply it
    // to.
    let (_crate_override, attr) =
        match autumn_macros_support::crate_path::extract_crate_override(attr.into()) {
            Ok(pair) => pair,
            Err(err) => return err.into(),
        };
    let out: proc_macro2::TokenStream = api_doc_standalone(attr.into(), item).into();
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(out).into()
}

const ROUTE_ATTR_NAMES: &[&str] = &["get", "post", "put", "delete", "patch", "static_get", "ws"];

/// Return `true` when an attribute names one of the Autumn route macros.
///
/// We match on the **last** path segment so qualified forms like
/// `#[autumn_web::get("/x")]`, `#[autumn_macros::post("/x")]`, or
/// even `#[crate::get("/x")]` are recognized alongside the bare
/// `#[get("/x")]`. Unqualified identifiers are covered by the same
/// logic because their path has a single segment.
fn is_route_attribute(attr: &syn::Attribute) -> bool {
    attr.path()
        .segments
        .last()
        .map(|segment| segment.ident.to_string())
        .is_some_and(|name| ROUTE_ATTR_NAMES.contains(&name.as_str()))
}

fn api_doc_standalone(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr_ts: proc_macro2::TokenStream = attr.into();
    let mut input_fn: syn::ItemFn = match syn::parse(item.clone()) {
        Ok(f) => f,
        // Not a function (e.g. applied to a struct) — leave it alone so
        // the user sees the usual "expected function" error from rustc.
        Err(_) => return item,
    };

    let route_idx = input_fn.attrs.iter().position(is_route_attribute);

    let Some(idx) = route_idx else {
        // Standalone `#[api_doc]` with no paired route macro is a no-op;
        // route metadata is only emitted through route macros.
        return quote::quote! { #input_fn }.into();
    };

    let route_attr = input_fn.attrs.remove(idx);
    let preserved: syn::Attribute = syn::parse_quote! {
        #[api_doc(#attr_ts)]
    };
    input_fn.attrs.insert(0, preserved);

    quote::quote! {
        #route_attr
        #input_fn
    }
    .into()
}

/// Annotate an async function as a WebSocket route handler.
///
/// The function follows the **two-function pattern**: it runs at HTTP
/// upgrade time (with access to Axum extractors) and returns a closure
/// implementing `WsHandler` (from `autumn_web::ws::WsHandler`) that handles the live WebSocket connection.
///
/// The macro generates a GET route that performs the WebSocket upgrade,
/// so it integrates seamlessly with `routes![]`.
///
/// # Examples
///
/// ```ignore
/// use autumn_web::prelude::*;
/// use autumn_web::ws::{WebSocket, Message, WsHandler};
///
/// // Minimal echo handler
/// #[ws("/echo")]
/// async fn echo() -> impl WsHandler {
///     |mut socket: WebSocket| async move {
///         while let Some(Ok(msg)) = socket.recv().await {
///             if let Message::Text(text) = msg {
///                 socket.send(Message::Text(text)).await.ok();
///             }
///         }
///     }
/// }
///
/// // With extractors (runs before upgrade)
/// #[ws("/chat")]
/// async fn chat(state: AppState) -> impl WsHandler {
///     let channels = state.channels().clone();
///     |mut socket: WebSocket| async move {
///         // use channels + socket
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn ws(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        ws::ws_macro(attr, item)
    })
    .into()
}

/// Translate an i18n key, with **compile-time validation** that the key
/// exists in the default locale's `.ftl` file.
///
/// Re-exported as `autumn_web::t!` (and `autumn_web::prelude::t!`) when the
/// `i18n` feature is enabled on `autumn-web`.
///
/// # Forms
///
/// ```ignore
/// // Without args:
/// t!(locale, "welcome.title")
/// // With named args (Project Fluent's `{ $name }` placeable syntax):
/// t!(locale, "welcome.greeting", name = "Ada")
/// ```
///
/// # Compile-time behaviour
///
/// At expansion time the macro reads `$CARGO_MANIFEST_DIR/i18n/<default>.ftl`
/// (where `<default>` is the value of the `AUTUMN_I18N_DEFAULT_LOCALE`
/// environment variable, defaulting to `"en"`). If the key is not present,
/// the macro emits a `compile_error!` pointing at the literal so the build
/// fails with a clear diagnostic — including a "did you mean" suggestion
/// for typos within Levenshtein distance 3.
///
/// If the file does not exist (e.g. an app that just enabled the feature
/// flag and has not yet authored translations), the macro degrades to a
/// pure runtime call so the build still succeeds. The runtime path will
/// produce the visible `{$key}` marker on miss.
#[proc_macro]
pub fn t(input: TokenStream) -> TokenStream {
    let _guard = autumn_macros_support::crate_path::set_target(None);
    autumn_macros_support::crate_path::finalize(i18n::t_macro(input.into())).into()
}

/// Turn a plain state enum into a statically-verified lifecycle.
///
/// Given a declared `initial` state, one or more `terminal` states, and a set
/// of `transitions`, `#[lifecycle]` preserves the original enum and appends:
///
/// 1. Metadata consts (`LIFECYCLE_INITIAL`, `LIFECYCLE_TERMINALS`,
///    `LIFECYCLE_STATES`, `LIFECYCLE_TRANSITIONS`) and a `can_transition_to`
///    runtime check on the enum. Because these reference the enum's own
///    variants, a declared state that is not a real variant is a compile error.
/// 2. A typestate transition module named after the enum in `snake_case`, whose
///    `Machine<S>` exposes a consuming `to_<target>` method *only* for declared
///    edges — firing an undeclared transition does not compile.
///
/// The declared graph is proven structurally sound at compile time: a state
/// unreachable from `initial`, or a reachable non-terminal state with no path
/// to a terminal, is a compile error naming the variant.
///
/// # Example
///
/// ```ignore
/// use autumn_web::lifecycle;
///
/// #[lifecycle(
///     initial = Draft,
///     terminal(Archived),
///     transitions(
///         Draft -> Published,
///         Published -> Archived,
///         Published -> Draft,
///     )
/// )]
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// pub enum ArticleState { Draft, Published, Archived }
///
/// let m = article_state::Machine::<article_state::Draft>::start();
/// let m = m.to_published();      // only declared edges exist as methods
/// assert_eq!(m.current(), ArticleState::Published);
/// assert!(ArticleState::Draft.can_transition_to(&ArticleState::Published));
/// ```
#[proc_macro_attribute]
pub fn lifecycle(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        lifecycle::lifecycle_macro(attr, item)
    })
    .into()
}

/// Declare a business-time obligation on a struct (issue #1826).
///
/// It adds `<name>_obligation(&self) -> autumn_web::sla::Obligation`.
///
/// # Arguments
///
/// - `name = ident` (required): the obligation name.
/// - `within = "..."` (required): the budget, such as `"2 business days"`.
///   A bad budget is a compile error.
/// - `starts = field` (required): a `DateTime<Utc>` field. The clock starts
///   there.
/// - `calendar = "..."`: the calendar name. The default is `"default"`.
/// - `met = field`: an `Option<DateTime<Utc>>` field. Your code sets it when
///   the subject meets the obligation.
/// - `zone = field`: a time zone field (`Tz`, an IANA name, or an `Option`).
/// - `subject = field`: the identity field. The default is `id`. The subject
///   is the `snake_case` type name, a colon, and the field value.
///
/// # Example
///
/// ```ignore
/// use autumn_web::obligation;
///
/// #[obligation(name = first_response, within = "2 business days", calendar = "support",
///              starts = opened_at, met = responded_at)]
/// pub struct Ticket {
///     pub id: i64,
///     pub opened_at: chrono::DateTime<chrono::Utc>,
///     pub responded_at: Option<chrono::DateTime<chrono::Utc>>,
/// }
/// ```
#[proc_macro_attribute]
pub fn obligation(attr: TokenStream, item: TokenStream) -> TokenStream {
    autumn_macros_support::crate_path::with_override(attr.into(), item.into(), |attr, item| {
        obligation::obligation_macro(attr, item)
    })
    .into()
}

#[cfg(test)]
mod rename_pipeline_tests {
    //! Cross-pipeline rename contract (#1828): every macro's expansion must
    //! rewrite `::autumn_web` token paths to the active crate target
    //! (`finalize`), and the idempotency replay-guard recognizer must accept
    //! the renamed target. These tests couple core pipelines (`#[get]`,
    //! `#[authorize]`/`#[secured]`) with the shared path rewriting, so they
    //! live with the core crate; the `#[model]`/`#[repository]` halves of
    //! this contract moved with those macros into their own crates.
    use autumn_macros_support::crate_path::{finalize, set_target};
    use quote::quote;

    fn ts_string(ts: &proc_macro2::TokenStream) -> String {
        ts.to_string()
    }

    /// No genuine `::autumn_web` *token* path (crate-root anchored) may
    /// survive `finalize`. `to_string()` renders a real `:: Ident ::` token
    /// sequence with spaces around the identifier; a doc comment or string
    /// literal's *contents* render with no such surrounding space, so this
    /// specifically will not (and must not) flag those.
    fn assert_no_leaked_autumn_web_token_path(s: &str) {
        assert!(
            !s.contains(":: autumn_web"),
            "leaked `::autumn_web` token path in: {s}"
        );
    }

    #[test]
    fn route_macro_pipeline_has_no_leaked_autumn_web_after_override() {
        let _guard = set_target(Some("renamed_autumn_web"));
        let generated = crate::route::route_macro(
            "GET",
            "get",
            quote! { "/users/{id}", seo(title = "User") },
            quote! {
                async fn show_user(Path(id): Path<i64>) -> AutumnResult<Json<User>> {
                    Ok(Json(repo.find_by_id(id).await?))
                }
            },
        );
        let rewritten = finalize(generated);
        let s = ts_string(&rewritten);
        assert_no_leaked_autumn_web_token_path(&s);
        assert!(s.contains("renamed_autumn_web"), "got: {s}");
    }

    /// Regression test for the exact scenario a Codex review on #2552 found:
    /// stacking `#[authorize]` above `#[secured]` under a rename must still
    /// let the route macro recognize the replay guard `#[authorize]`'s own
    /// (already-finalized, already-renamed) expansion injected, rather than
    /// missing it because the recognizer only knew the literal
    /// `"autumn_web"`.
    #[test]
    fn replay_guard_recognized_after_stacked_macro_rename() {
        let _guard = set_target(Some("renamed_autumn_web"));
        // Simulate what `#[authorize]` (or `#[secured]`/`#[step_up]`) leaves
        // behind once ITS OWN `finalize` has already run: a block whose
        // early-return replay check is rooted at the *renamed* crate, not
        // `autumn_web` literally.
        let block: syn::Block = syn::parse_quote! {{
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::renamed_autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        }};
        assert!(
            crate::idempotency_guard::block_has_replay_guard(&block),
            "recognizer must accept the actively-resolved crate name, not just the literal \
             \"autumn_web\""
        );
    }

    /// Regression test for a second Codex round on the same #2552 scenario:
    /// once the target is a keyword (`"type"`, from automatic resolution —
    /// see `ident_for_target`/`rewrite`), an earlier-expanded macro's own
    /// `finalize` pass emits the *raw* identifier `r#type`, not the bare
    /// `type`. A recognizer comparing against the bare `current_target()`
    /// (rather than `current_target_path_segment()`, which accounts for the
    /// raw prefix) misses the match — the same class of bug as
    /// `replay_guard_recognized_after_stacked_macro_rename` above, just
    /// triggered by a keyword target instead of a plain renamed one.
    #[test]
    fn replay_guard_recognized_after_stacked_macro_rename_with_keyword_target() {
        let _guard = set_target(Some("type"));
        let block: syn::Block = syn::parse_quote! {{
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::r#type::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        }};
        assert!(
            crate::idempotency_guard::block_has_replay_guard(&block),
            "recognizer must compare against the raw-escaped target, not the bare keyword"
        );
    }
}