reinhardt-macros 0.1.2

Procedural macros for Reinhardt 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
//! # Reinhardt Procedural Macros
//!
//! Provides Django-style decorators as Rust procedural macros.
//!
//! ## Macros
//!
//! - `#[routes]` - Register URL pattern function for automatic discovery
//! - `#[api_view]` - Convert function to API view
//! - `#[action]` - Define custom ViewSet action
//! - `#[get]`, `#[post]`, etc. - HTTP method decorators
//! - `#[permission_required]` - Permission decorator
//!

use proc_macro::TokenStream;
use syn::{ItemFn, ItemStruct, parse_macro_input};

mod action;
mod admin;
mod api_view;
// client_routes module removed: superseded by #[url_patterns(InstalledApp::<variant>, mode = client)]
mod app_config_attribute;
mod app_config_derive;
mod apply_update_attribute;
mod apply_update_derive;
mod collect_migrations;
mod crate_paths;
mod dto;
mod flatten_imports;
mod hook;
mod injectable_common;
mod injectable_fn;
mod injectable_struct;
mod installed_apps;
mod macro_state;
mod model_attribute;
mod model_derive;
mod orm_reflectable_derive;
mod pascal_case;
mod path_macro;
mod permission_macro;
mod permissions;
mod pk_shape;
mod query_fields;
mod receiver;
mod rel;
mod routes;
mod routes_registration;
mod schema;
mod settings_compose;
mod settings_fragment;
pub(crate) mod settings_parser;
mod streaming;
mod streaming_patterns;
mod use_inject;
mod user_attribute;
mod user_field_mapping;
mod validate_derive;

use action::action_impl;
use admin::admin_impl;
use api_view::api_view_impl;
use app_config_attribute::app_config_attribute_impl;
use apply_update_attribute::apply_update_attribute_impl;
use apply_update_derive::apply_update_derive_impl;
use injectable_fn::injectable_fn_impl;
use injectable_struct::injectable_struct_impl;
use installed_apps::installed_apps_impl;
use model_attribute::model_attribute_impl;
use model_derive::model_derive_impl;
use orm_reflectable_derive::orm_reflectable_derive_impl;
use path_macro::path_impl;
use permissions::permission_required_impl;
use query_fields::derive_query_fields_impl;
use receiver::receiver_impl;
use routes::{delete_impl, get_impl, patch_impl, post_impl, put_impl};
use routes_registration::routes_impl;
mod url_patterns;
mod viewset_macro;
mod websocket;
use schema::derive_schema_impl;
use url_patterns::url_patterns_impl;
use use_inject::use_inject_impl;
use user_attribute::user_attribute_impl;

/// Decorator for function-based API views
#[proc_macro_attribute]
pub fn api_view(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	api_view_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Decorator for ViewSet custom actions
#[proc_macro_attribute]
pub fn action(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	action_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// GET method decorator
#[proc_macro_attribute]
pub fn get(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	get_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// POST method decorator
#[proc_macro_attribute]
pub fn post(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	post_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// PUT method decorator
#[proc_macro_attribute]
pub fn put(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	put_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// PATCH method decorator
#[proc_macro_attribute]
pub fn patch(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	patch_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// DELETE method decorator
#[proc_macro_attribute]
pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	delete_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Producer handler decorator — auto-publishes return value to a Kafka topic.
///
/// # Arguments
///
/// - `topic` — Kafka topic to publish to
/// - `name` — identifier used in `ResolvedUrls::streaming().<app>().<name>()`
///
/// # Example
///
/// ```rust,ignore
/// #[producer(topic = "orders", name = "create_order")]
/// pub async fn create_order(cmd: CreateOrderCommand) -> Result<Order, StreamingError> {
///     Ok(Order::from(cmd))
/// }
/// ```
#[proc_macro_attribute]
pub fn producer(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);
	streaming::producer_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Consumer handler decorator — receives messages from a Kafka topic.
///
/// # Arguments
///
/// - `topic` — Kafka topic to consume from
/// - `group` — Consumer group id
/// - `name` — identifier used in `ResolvedUrls::streaming().<app>().<name>()`
///
/// # Example
///
/// ```rust,ignore
/// #[consumer(topic = "orders", group = "order-processor", name = "handle_order")]
/// pub async fn handle_order(msg: Message<Order>) -> Result<(), StreamingError> {
///     Ok(())
/// }
/// ```
#[proc_macro_attribute]
pub fn consumer(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);
	streaming::consumer_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Streaming patterns attribute — generates typed per-app streaming URL accessors.
///
/// Apply to the function that builds and returns the app's `StreamingRouter`.
/// The function body must contain `streaming_routes![handler1, handler2, ...]`.
///
/// # Arguments
///
/// - First positional arg: `InstalledApp::<Variant>` — the app's label (or any path/ident)
///
/// # Example
///
/// ```rust,ignore
/// #[streaming_patterns(InstalledApp::Orders)]
/// pub fn streaming_routes() -> reinhardt_streaming::StreamingRouter {
///     streaming_routes![create_order, handle_order]
/// }
/// ```
///
/// After this macro expands:
/// - `OrdersStreamingUrls` struct is generated with `.create_order()` and `.handle_order()` methods
/// - `urls.streaming().orders()` returns `OrdersStreamingUrls<'_>` (requires `#[routes]` in same crate)
/// - Each method returns the Kafka topic name as `&'static str`
#[proc_macro_attribute]
pub fn streaming_patterns(args: TokenStream, input: TokenStream) -> TokenStream {
	streaming_patterns::streaming_patterns_impl(args.into(), input.into())
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Permission required decorator
#[proc_macro_attribute]
pub fn permission_required(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	permission_required_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Defines installed applications with compile-time validation.
///
/// Generates an `InstalledApp` enum with variants for each application,
/// along with `Display`, `FromStr` traits and helper methods.
///
/// **Important**: This macro is for **user applications only**. Built-in framework features
/// (auth, sessions, admin, etc.) are enabled via Cargo feature flags, not through `installed_apps!`.
///
/// # Generated Code
///
/// The macro generates:
///
/// - `enum InstalledApp { ... }` - Type-safe app references with variants for each app
/// - `impl Display` - Convert enum variants to path strings
/// - `impl FromStr` - Parse path strings to enum variants
/// - `fn all_apps() -> Vec<String>` - List all app paths as strings
/// - `fn path(&self) -> &'static str` - Get app path without allocation
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt::installed_apps;
///
/// installed_apps! {
///     users: "users",
///     posts: "posts",
/// }
///
/// // Use generated enum
/// let app = InstalledApp::users;
/// println!("{}", app);  // Output: "users"
///
/// // Get all apps
/// let all = InstalledApp::all_apps();
/// assert_eq!(all, vec!["users".to_string(), "posts".to_string()]);
///
/// // Parse from string
/// use std::str::FromStr;
/// let app = InstalledApp::from_str("users")?;
/// assert_eq!(app, InstalledApp::users);
///
/// // Get path without allocation
/// assert_eq!(app.path(), "users");
/// ```
///
/// # Compile-time Validation
///
/// Framework modules (starting with `reinhardt.`) are validated at compile time.
/// Non-existent modules will cause compilation errors:
///
/// ```rust,ignore
/// installed_apps! {
///     nonexistent: "reinhardt.contrib.nonexistent",
/// }
/// // Compile error: cannot find module `nonexistent` in `contrib`
/// ```
///
/// User apps (not starting with `reinhardt.`) skip compile-time validation,
/// allowing flexible user-defined application names.
///
/// # Framework Features
///
/// **Do NOT use this macro for built-in framework features.** Instead, enable them
/// via Cargo feature flags:
///
/// ```toml
/// [dependencies]
/// reinhardt = { version = "0.1.0-alpha.1", features = ["auth", "sessions", "admin"] }
/// ```
///
/// Then import them directly:
///
/// ```rust,ignore
/// use reinhardt::auth::*;
/// use reinhardt::auth::sessions::*;
/// use reinhardt::admin::*;
/// ```
///
/// # See Also
///
/// - Module documentation in `installed_apps.rs` for detailed information about
///   generated code structure, trait implementations, and advanced usage
/// - `crates/reinhardt-apps/README.md` for comprehensive usage guide
/// - Tutorial: `docs/tutorials/en/basis/1-project-setup.md`
///
#[proc_macro]
pub fn installed_apps(input: TokenStream) -> TokenStream {
	installed_apps_impl(input.into())
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Register URL patterns for automatic discovery by the framework
///
/// This attribute macro automatically registers a function as the URL pattern
/// provider for the framework. The function will be discovered and used when
/// running management commands like `runserver`.
///
/// # Important: Single Usage Only
///
/// **Only one function per project can be annotated with `#[routes]`.**
/// If multiple `#[routes]` attributes are used, the linker will fail with a
/// "duplicate symbol" error for `__reinhardt_routes_registration_marker`.
///
/// To organize routes across multiple files, use the `.mount()` method:
///
/// ```rust,ignore
/// // In src/config/urls.rs - Only ONE #[routes] in the entire project
/// #[routes]
/// pub fn routes() -> UnifiedRouter {
///     UnifiedRouter::new()
///         .mount("/api/", api::routes())   // api::routes() returns UnifiedRouter
///         .mount("/admin/", admin::routes())  // WITHOUT #[routes] attribute
/// }
///
/// // In src/apps/api/urls.rs - NO #[routes] attribute
/// pub fn routes() -> UnifiedRouter {
///     UnifiedRouter::new()
///         .endpoint(views::list)
///         .endpoint(views::create)
/// }
/// ```
///
/// # Supported Function Signatures
///
/// ## 1. Sync function (standard)
///
/// ```rust,ignore
/// #[routes]
/// pub fn routes() -> UnifiedRouter {
///     UnifiedRouter::new()
///         .endpoint(views::index)
///         .mount("/api/", api::routes())
/// }
/// ```
///
/// ## 2. Async function (no DI)
///
/// ```rust,ignore
/// #[routes]
/// pub async fn routes() -> UnifiedRouter {
///     UnifiedRouter::new()
///         .mount("/api/", api::routes())
/// }
/// ```
///
/// ## 3. Async function with `#[inject]` (DI-aware)
///
/// ```rust,ignore
/// #[routes]
/// pub async fn routes(#[inject] router: UnifiedRouter) -> UnifiedRouter {
///     router
/// }
/// ```
///
/// When `#[inject]` parameters are present, the macro automatically creates
/// a DI context (`SingletonScope` + `InjectionContext`) and resolves each
/// injected dependency before calling the function.
///
/// # Arguments
///
/// - `#[routes]` — Default mode. Generates `ResolvedUrls` and `url_prelude`
///   module with URL resolver traits from all installed apps. Requires
///   `installed_apps!` to be present in the crate.
/// - `#[routes(standalone)]` — Standalone mode. Generates `ResolvedUrls` only,
///   without `url_prelude` module. Use this for projects that don't use
///   `installed_apps!`.
/// - `#[routes(client_inventory)]` — Opt into the WASM cross-target
///   `ClientRouter` `inventory::submit!` registration (see Issue #4453).
///
/// ## Per-mode resolver suppression (Issue #4509)
///
/// Plain `#[routes]` unconditionally emits per-app resolver lookups for
/// three modes (server, client, ws). REST-only apps that do not use
/// `#[url_patterns(InstalledApp::<app>, mode = client)]` or
/// `#[url_patterns(InstalledApp::<app>, mode = ws)]` would need to stub
/// the missing modules. These flags let the macro skip the unused lookups:
///
/// - `#[routes(server_only)]` — Shorthand for
///   `no_client_resolvers, no_ws_resolvers`. The `urls.client()` /
///   `urls.ws()` gateways are not emitted; only `urls.server().<app>()`
///   remains. The `ResolvedUrls::<app>()` server-side accessor is
///   preserved (unlike `standalone`, which suppresses it).
/// - `#[routes(no_client_resolvers)]` — Skip per-app client resolver
///   lookups and the `ClientUrls` / `<app>ClientUrls` types.
/// - `#[routes(no_ws_resolvers)]` — Skip per-app WebSocket resolver
///   lookups, the `WsUrls` / `<app>WsUrls` types, and the stub
///   `WebSocketUrlResolver` impl on `ResolvedUrls`.
///
/// `client_inventory` is mutually exclusive with the `no_*` flags
/// (and therefore with `server_only`) — `client_inventory` registers
/// the very WASM client surface those flags suppress.
///
/// ```rust,ignore
/// // REST-only project with #[url_patterns(InstalledApp::api, mode = server)]
/// // — no stub client_router.rs / ws_urls.rs needed. `server_only` only
/// // gates per-app client/ws emission, so the return type stays
/// // `UnifiedRouter` for consistency with every other `#[routes]` example.
/// #[routes(server_only)]
/// pub fn routes() -> UnifiedRouter {
///     UnifiedRouter::new().mount("/api/", api::urls::url_patterns())
/// }
///
/// // HTTP + WebSocket but no WASM admin: skip client resolvers only.
/// #[routes(no_client_resolvers)]
/// pub fn routes() -> UnifiedRouter { ... }
/// ```
///
/// # Notes
///
/// - The function can have any name (e.g., `routes`, `app_routes`, `url_patterns`)
/// - The return type must be `UnifiedRouter` (not `Arc<UnifiedRouter>`)
/// - The framework automatically wraps the router in `Arc`
/// - Sync functions cannot use `#[inject]` (DI resolution is inherently async)
#[proc_macro_attribute]
pub fn routes(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	routes_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Register an app-scoped URL pattern function with the framework and
/// generate per-mode helper modules from its body.
///
/// # Syntax
///
/// ```text
/// #[url_patterns(<InstalledApp::variant>, mode = server|client|unified|ws)]
/// pub fn url_patterns() -> Router { ... }
/// ```
///
/// The first argument is a path to a variant of an enum implementing
/// `reinhardt_apps::apps::AppLabel` — normally the `InstalledApp`
/// enum generated by `installed_apps!`. The macro wraps the original
/// function so the returned router carries the variant's
/// `AppLabel::path(&variant)` value as its runtime namespace.
///
/// # Modes
///
/// | mode      | Router          | Scanned calls                                                            | Modules emitted                                    |
/// |-----------|-----------------|--------------------------------------------------------------------------|----------------------------------------------------|
/// | `server`  | `ServerRouter`  | `.endpoint()`, `.viewset()`, `.mount()`                                  | `url_resolvers`                                    |
/// | `client`  | `ClientRouter`  | `.named_route()` / `.named_route_path*()` family                         | `client_url_resolvers` + `urls` (typed helpers)    |
/// | `unified` | `UnifiedRouter` | both sides (inside `.server(\|s\| ...)` / `.client(\|c\| ...)` closures) | `url_resolvers` + `client_url_resolvers` + `urls`  |
/// | `ws`      | `WsRouter`      | `.consumer(...)`                                                         | `ws_url_resolvers`                                 |
///
/// # The `urls` module (Issue #4644)
///
/// For `mode = client` and the client side of `mode = unified`, the macro
/// emits a sibling `pub mod urls` whose contents mirror the named routes
/// declared in the function body. Each named route appears as a free
/// function whose signature carries the path parameters lifted from the
/// closure binding:
///
/// ```text
/// // Input
/// #[url_patterns(InstalledApp::polls, mode = client)]
/// pub fn client_url_patterns() -> ClientRouter {
///     ClientRouter::new()
///         .named_route("index", "/", index_page)
///         .named_route_path(
///             "detail",
///             "/polls/{question_id}/",
///             |ClientPath(question_id): ClientPath<i64>| polls_detail_page(question_id),
///         )
/// }
///
/// // Generated (sketch)
/// pub mod urls {
///     pub fn index() -> String { /* "polls:index" via global reverser */ }
///     pub fn detail(question_id: i64) -> String { /* "polls:detail" */ }
/// }
/// ```
///
/// Each helper resolves through the global `ClientUrlReverser`
/// (`reinhardt::get_client_reverser()`), so a route-pattern change in the
/// `#[url_patterns]` body propagates without any call-site edits.
///
/// **Extraction rules.** A typed helper is generated when the path
/// parameter count in the pattern matches the binding count in the
/// closure, and every binding is shaped `ClientPath(name): ClientPath<T>`:
///
/// - `.named_route(name, pattern, component)` — always emits a zero-arg
///   helper.
/// - `.named_route_path(name, pattern, |ClientPath(id): ClientPath<T>| ...)`
///   — emits `fn name(id: T) -> String`.
/// - `.named_route_path2(...)` / `.named_route_path3(...)` — emit helpers
///   with two / three positional parameters, in binding order.
/// - `.named_route_params(...)` / `.named_route_result(...)` — the macro
///   does not project these into typed helpers today; the route is still
///   reachable through the stringly-typed
///   `ResolvedUrls::resolve_client_url(...)` API.
/// - Routes whose handler is a function reference (not an inline closure)
///   are silently skipped in the `urls` module for the same reason.
///
/// The `urls` module is emitted unconditionally so call sites can write
/// `use ...::urls;` regardless of which routes happen to be typed; an
/// empty module is harmless.
#[doc = include_str!("upstream_workaround_note.md")]
#[proc_macro_attribute]
pub fn url_patterns(args: TokenStream, input: TokenStream) -> TokenStream {
	url_patterns_impl(args.into(), input.into())
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Generate URL resolver traits for a ViewSet function.
///
/// When applied to a function returning a ViewSet (e.g., `ModelViewSet`), extracts
/// the basename from the function body and generates `__url_resolver_{basename}_list`
/// and `__url_resolver_{basename}_detail` modules.
///
/// # Example
///
/// ```rust,ignore
/// #[viewset]
/// pub fn viewset() -> ModelViewSet<Snippet, SnippetSerializer> {
///     ModelViewSet::new("snippet")
/// }
/// // Generates: __url_resolver_snippet_list, __url_resolver_snippet_detail
/// ```
///
#[doc = include_str!("upstream_workaround_note.md")]
#[proc_macro_attribute]
pub fn viewset(args: TokenStream, input: TokenStream) -> TokenStream {
	viewset_macro::viewset_macro_impl(args.into(), input.into())
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Validate URL patterns at compile time
///
/// This macro validates URL pattern syntax at compile time, catching common errors
/// before they reach runtime. It supports both simple parameters and Django-style
/// typed parameters.
///
/// # Compile-time Validation
///
/// The macro will fail to compile if:
/// - Braces are not properly matched (e.g., `{id` or `id}`)
/// - Parameter names are empty (e.g., `{}`)
/// - Parameter names contain invalid characters
/// - Type specifiers are invalid (valid: `int`, `str`, `uuid`, `slug`, `path`)
/// - Django-style parameters are used outside braces (e.g., `<int:id>` instead of `{<int:id>}`)
///
/// # Supported Type Specifiers
///
/// - `int` - Integer values
/// - `str` - String values
/// - `uuid` - UUID values
/// - `slug` - Slug strings (alphanumeric, hyphens, underscores)
/// - `path` - Path segments (can include slashes)
///
#[proc_macro]
pub fn path(input: TokenStream) -> TokenStream {
	path_impl(input.into())
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Connect a receiver function to a signal automatically
///
/// This macro provides Django-style `@receiver` decorator functionality for Rust.
/// It automatically registers the function as a signal receiver at startup.
///
#[proc_macro_attribute]
pub fn receiver(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	receiver_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Attribute macro for registering lifecycle hooks.
///
/// Currently supports `runserver` hooks for extending server startup behavior.
///
/// # Usage
///
/// ```rust,ignore
/// use reinhardt::commands::{RunserverHook, RunserverContext};
///
/// #[reinhardt::hook(on = runserver)]
/// struct MyValidationHook;
///
/// #[async_trait]
/// impl RunserverHook for MyValidationHook {
///     async fn validate(&self) -> Result<(), Box<dyn Error + Send + Sync>> {
///         // Fail-fast validation before server starts
///         Ok(())
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn hook(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemStruct);
	hook::hook_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Automatic dependency injection macro
///
/// This macro enables FastAPI-style dependency injection using parameter attributes.
/// Parameters marked with `#[inject]` will be automatically resolved from the
/// `InjectionContext`. Can be used with any function, not just endpoints.
///
/// # Generated Code
///
/// The macro transforms the function by:
/// 1. Removing `#[inject]` parameters from the signature
/// 2. Adding an `InjectionContext` parameter
/// 3. Injecting dependencies at the start of the function
///
#[proc_macro_attribute]
pub fn use_inject(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);

	use_inject_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Derive macro for type-safe field lookups
///
/// Automatically generates field accessor methods for models, enabling
/// compile-time validated field lookups.
///
/// # Generated Methods
///
/// For each field in the struct, the macro generates a static method that
/// returns a `Field<Model, FieldType>`. The field type determines which
/// lookup methods are available:
///
/// - String fields: `lower()`, `upper()`, `trim()`, `contains()`, etc.
/// - Numeric fields: `abs()`, `ceil()`, `floor()`, `round()`
/// - DateTime fields: `year()`, `month()`, `day()`, `hour()`, etc.
/// - All fields: `eq()`, `ne()`, `gt()`, `gte()`, `lt()`, `lte()`
///
#[proc_macro_derive(QueryFields)]
pub fn derive_query_fields(input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as syn::DeriveInput);

	derive_query_fields_impl(input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Derive macro for automatic OpenAPI schema generation
///
/// Automatically implements the `ToSchema` trait for structs and enums,
/// generating OpenAPI 3.0 schemas from Rust type definitions.
///
/// # Supported Types
///
/// - Primitives: `String`, `i32`, `i64`, `f32`, `f64`, `bool`
/// - `Option<T>`: Makes fields optional in the schema
/// - `Vec<T>`: Generates array schemas
/// - Custom types implementing `ToSchema`
///
/// # Features
///
/// - Automatic field metadata extraction
/// - Documentation comments become field descriptions
/// - Required/optional field detection
/// - Nested schema support
/// - Enum variant handling
///
#[proc_macro_derive(Schema)]
pub fn derive_schema(input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as syn::DeriveInput);

	derive_schema_impl(input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Attribute macro for injectable factory/provider functions and structs
///
/// This macro can be applied to both functions and structs to enable dependency injection.
///
/// # Field Attributes (Struct Only)
///
/// All struct fields must have either `#[inject]` or `#[no_inject]` attribute:
///
/// - **`#[inject]`**: Inject this field from the DI container
/// - **`#[inject(cache = false)]`**: Inject without caching
/// - **`#[inject(scope = Singleton)]`**: Use singleton scope
/// - **`#[no_inject(default = Default)]`**: Initialize with `Default::default()`
/// - **`#[no_inject(default = value)]`**: Initialize with specific value
/// - **`#[no_inject]`**: Initialize with `None` (field must be `Option<T>`)
///
/// # Restrictions
///
/// **For functions:**
/// - Function must have an explicit return type
/// - All parameters must be marked with `#[inject]`
///
/// **For structs:**
/// - Struct must have named fields
/// - All fields must have either `#[inject]` or `#[no_inject]` attribute
/// - `#[no_inject]` without default value requires field type to be `Option<T>`
/// - `Clone` is auto-derived if not already present (used by `into_inner()` and `injectable_factory` patterns)
/// - All `#[inject]` field types must implement `Injectable`
///
/// # Attribute Ordering
///
/// **`#[injectable]` must be placed above `#[derive(...)]` attributes.**
///
/// In Rust 2024 edition, attribute macros can only see attributes listed
/// below them. If `#[derive(Clone)]` appears above `#[injectable]`, the
/// macro cannot detect it and will add a duplicate `#[derive(Clone)]`,
/// causing a compilation error.
///
/// ```ignore
/// // Correct
/// #[injectable]
/// #[derive(Default, Debug)]
/// struct MyService { /* ... */ }
///
/// // Incorrect — may cause duplicate Clone derive
/// #[derive(Default, Debug)]
/// #[injectable]
/// struct MyService { /* ... */ }
/// ```
///
#[proc_macro_attribute]
pub fn injectable(args: TokenStream, input: TokenStream) -> TokenStream {
	// Try to parse as ItemFn first
	if let Ok(item_fn) = syn::parse::<ItemFn>(input.clone()) {
		return injectable_fn_impl(proc_macro2::TokenStream::new(), item_fn)
			.unwrap_or_else(|e| e.to_compile_error())
			.into();
	}

	// Try to parse as ItemStruct
	if let Ok(item_struct) = syn::parse::<ItemStruct>(input.clone()) {
		// Convert ItemStruct to DeriveInput for compatibility
		let derive_input = syn::DeriveInput {
			attrs: item_struct.attrs,
			vis: item_struct.vis,
			ident: item_struct.ident,
			generics: item_struct.generics,
			data: syn::Data::Struct(syn::DataStruct {
				struct_token: item_struct.struct_token,
				fields: item_struct.fields,
				semi_token: item_struct.semi_token,
			}),
		};

		return injectable_struct_impl(args.into(), derive_input)
			.unwrap_or_else(|e| e.to_compile_error())
			.into();
	}

	// Neither ItemFn nor ItemStruct
	syn::Error::new(
		proc_macro2::Span::call_site(),
		"#[injectable] can only be applied to functions or structs",
	)
	.to_compile_error()
	.into()
}

/// Attribute macro for Django-style model definition with automatic derive
///
/// Automatically adds `#[derive(Model)]` and keeps the `#[model(...)]` attribute.
/// This provides a cleaner syntax by eliminating the need to explicitly write
/// `#[derive(Model)]` on every model struct.
///
/// # Model Attributes
///
/// Same as `#[derive(Model)]`. See [`derive_model`] for details.
///
#[proc_macro_attribute]
pub fn model(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemStruct);

	model_attribute_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Attribute macro for generating auth trait implementations.
///
/// Generates `BaseUser`, `FullUser` (when `full = true`), `PermissionsMixin`
/// (when `user_permissions` and `groups` fields exist), and `AuthIdentity`
/// trait implementations based on struct fields.
///
/// # Arguments
///
/// - `hasher`: Type implementing `PasswordHasher + Default` (required)
/// - `username_field`: Name of the field used as username (required)
/// - `full`: Generate `FullUser` impl (default: `false`)
///
/// # Examples
///
/// ```rust,ignore
/// #[user(hasher = Argon2Hasher, username_field = "email", full = true)]
/// #[derive(Serialize, Deserialize)]
/// pub struct MyUser {
///     pub id: Uuid,
///     pub email: String,
///     pub password_hash: Option<String>,
///     pub last_login: Option<DateTime<Utc>>,
///     pub is_active: bool,
///     pub is_superuser: bool,
/// }
/// ```
#[proc_macro_attribute]
pub fn user(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemStruct);

	user_attribute_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Derive macro for automatic Model implementation and migration registration
///
/// Automatically implements the `Model` trait and registers the model with the global
/// ModelRegistry for automatic migration generation.
///
/// # Model Attributes
///
/// - `app_label`: Application label (default: "default")
/// - `table_name`: Database table name (default: struct name in snake_case)
/// - `constraints`: List of unique constraints (e.g., `unique(fields = ["field1", "field2"], name = "name")`)
///
/// # Field Attributes
///
/// - `primary_key`: Mark field as primary key (required for exactly one field)
/// - `max_length`: Maximum length for String fields (required for String)
/// - `null`: Allow NULL values (default: inferred from `Option<T>`)
/// - `blank`: Allow blank values in forms
/// - `unique`: Enforce uniqueness constraint
/// - `default`: Default value
/// - `db_column`: Custom database column name
/// - `editable`: Whether field is editable (default: true)
///
/// # Supported Types
///
/// - `i32` → IntegerField
/// - `i64` → BigIntegerField
/// - `String` → CharField (requires max_length)
/// - `bool` → BooleanField
/// - `DateTime<Utc>` → DateTimeField
/// - `Date` → DateField
/// - `Time` → TimeField
/// - `f32`, `f64` → FloatField
/// - `Option<T>` → Sets null=true automatically
///
/// # Requirements
///
/// - Struct must have named fields
/// - Struct must implement `Serialize` and `Deserialize`
/// - Exactly one field must be marked with `primary_key = true`
/// - String fields must specify `max_length`
///
#[proc_macro_derive(Model, attributes(model, model_config, field, rel, fk_id_field))]
pub fn derive_model(input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as syn::DeriveInput);

	model_derive_impl(input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Derive macro for automatic OrmReflectable implementation
///
/// Automatically implements the `OrmReflectable` trait for structs,
/// enabling reflection-based field and relationship access for association proxies.
///
/// ## Type Inference
///
/// Fields are automatically classified based on their types:
/// - `Vec<T>` → Collection relationship
/// - `Option<T>` (where T is non-primitive) → Scalar relationship
/// - Primitive types (i32, String, etc.) → Regular fields
///
/// ## Attributes
///
/// Override automatic inference with explicit attributes:
///
/// - `#[orm_field(type = "Integer")]` - Mark as regular field with specific type
/// - `#[orm_relationship(type = "collection")]` - Mark as collection relationship
/// - `#[orm_relationship(type = "scalar")]` - Mark as scalar relationship
/// - `#[orm_ignore]` - Exclude field from reflection
///
/// ## Supported Field Types
///
/// - **Integer**: i8, i16, i32, i64, i128, u8, u16, u32, u64, u128
/// - **Float**: f32, f64
/// - **Boolean**: bool
/// - **String**: String, str
///
#[proc_macro_derive(OrmReflectable, attributes(orm_field, orm_relationship, orm_ignore))]
pub fn derive_orm_reflectable(input: TokenStream) -> TokenStream {
	orm_reflectable_derive_impl(input)
}

/// Attribute macro for Django-style AppConfig definition with automatic derive
///
/// Automatically adds `#[derive(AppConfig)]` and keeps the `#[app_config(...)]` attribute.
/// This provides a cleaner syntax by eliminating the need to explicitly write
/// `#[derive(AppConfig)]` on every app config struct.
///
/// # Example
///
/// ```rust,ignore
/// #[app_config(name = "hello", label = "hello")]
/// pub struct HelloConfig;
///
/// // Generates a config() method:
/// let config = HelloConfig::config();
/// assert_eq!(config.name, "hello");
/// assert_eq!(config.label, "hello");
/// ```
///
/// # Attributes
///
/// - `name`: Application name (required, string literal)
/// - `label`: Application label (required, string literal)
/// - `verbose_name`: Verbose name (optional, string literal)
///
/// # Note
///
/// Direct use of `#[derive(AppConfig)]` is not allowed. Always use
/// `#[app_config(...)]` attribute macro instead.
///
#[proc_macro_attribute]
pub fn app_config(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemStruct);

	app_config_attribute_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Derive macro for automatic AppConfig factory method generation
///
/// **Note**: Do not use this derive macro directly. Use `#[app_config(...)]`
/// attribute macro instead.
///
/// This derive macro is invoked automatically by the `#[app_config(...)]` attribute.
/// Direct use will result in a compile error.
///
#[proc_macro_derive(AppConfig, attributes(app_config, app_config_internal))]
pub fn derive_app_config(input: TokenStream) -> TokenStream {
	app_config_derive::derive(input)
}

/// Collect migrations and register them with the global registry
///
/// # Deprecated since 0.2.0
///
/// **This macro is deprecated.** Use `FilesystemSource` instead for loading migrations.
/// `FilesystemSource` scans directories for `.rs` migration files and does not require
/// compile-time registration. It is consistent with `manage migrate` behavior and
/// works reliably in Cargo workspaces when using `env!("CARGO_MANIFEST_DIR")`.
///
/// This macro generates a `MigrationProvider` implementation and automatically
/// registers it with the global migration registry using `linkme::distributed_slice`.
///
/// # Requirements
///
/// - Each migration module must export a `migration()` function returning `Migration`
/// - The crate must have `reinhardt-migrations` and `linkme` as dependencies
///
#[proc_macro]
pub fn collect_migrations(input: TokenStream) -> TokenStream {
	collect_migrations::collect_migrations_impl(input.into())
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Attribute macro for ModelAdmin configuration
///
/// Automatically implements the `ModelAdmin` trait for a struct with compile-time
/// field validation against the specified model type.
///
/// # Attributes
///
/// ## Required
///
/// - `for = ModelType` - The model type to validate fields against
/// - `name = "ModelName"` - The display name for the model
///
/// ## Optional
///
/// - `list_display = [field1, field2, ...]` - Fields to display in list view (default: `[id]`)
/// - `list_filter = [field1, field2, ...]` - Fields for filtering (default: `[]`)
/// - `search_fields = [field1, field2, ...]` - Fields for search (default: `[]`)
/// - `fields = [field1, field2, ...]` - Fields to display in forms (default: all)
/// - `readonly_fields = [field1, field2, ...]` - Read-only fields (default: `[]`)
/// - `ordering = [(field1, asc/desc), ...]` - Default ordering (default: `[(id, desc)]`)
/// - `list_per_page = N` - Items per page (default: site default)
///
/// # Compile-time Field Validation
///
/// All field names are validated at compile time against the model's `field_xxx()` methods.
/// If a field doesn't exist, compilation will fail with an error.
///
/// # Generated Code
///
/// The macro generates:
/// 1. The struct definition
/// 2. Compile-time field validation code
/// 3. `ModelAdmin` trait implementation with `#[async_trait]`
///
#[proc_macro_attribute]
pub fn admin(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemStruct);

	admin_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Attribute macro for applying partial updates to target structs
///
/// Automatically adds `#[derive(ApplyUpdate)]` and creates a helper config attribute.
/// This provides a cleaner syntax for defining update request structs.
///
/// # Attributes
///
/// - `target(Type1, Type2, ...)`: Target types to generate `ApplyUpdate` implementations for
///
/// # Field Attributes
///
/// - `#[apply_update(skip)]`: Skip this field during update application
/// - `#[apply_update(rename = "field_name")]`: Use a different field name on the target
///
#[proc_macro_attribute]
pub fn apply_update(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemStruct);

	apply_update_attribute_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Derive macro for automatic `ApplyUpdate` trait implementation
///
/// **Note**: Do not use this derive macro directly. Use `#[apply_update(...)]`
/// attribute macro instead.
///
#[proc_macro_derive(ApplyUpdate, attributes(apply_update, apply_update_config))]
pub fn derive_apply_update(input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as syn::DeriveInput);

	apply_update_derive_impl(input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Derive macro for struct-level validation
///
/// Implements the `Validate` trait using `#[validate(...)]` field attributes
/// to call Reinhardt's built-in validators.
///
/// # Supported Attributes
///
/// - `#[validate(email)]` - Validate email format
/// - `#[validate(url)]` - Validate URL format
/// - `#[validate(length(min = N, max = M))]` - Validate string length
/// - `#[validate(range(min = N, max = M))]` - Validate numeric range
/// - `message = "..."` - Custom error message (inside rule parentheses)
///
/// `Option<T>` fields are skipped when `None`.
///
#[proc_macro_derive(Validate, attributes(validate))]
pub fn derive_validate(input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as syn::DeriveInput);

	validate_derive::validate_derive_impl(input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Attribute macro that absorbs the `cfg_attr(native, ...)` boilerplate for
/// DTOs shared between the server (`native` cfg) and client (`wasm`) builds.
///
/// The macro:
///
/// 1. Emits `#[cfg_attr(native, derive(::reinhardt::Validate, ::reinhardt::rest::openapi::Schema))]`
///    on the struct so the server build gets validation and OpenAPI schema
///    generation, while the wasm build sees a plain serializable type.
/// 2. Wraps every `#[validate(...)]` field attribute in `#[cfg_attr(native, ...)]`
///    so the same source compiles unchanged for `wasm32-unknown-unknown`.
/// 3. Is idempotent: if the user already wrote
///    `#[cfg_attr(native, derive(Validate))]` or
///    `#[cfg_attr(native, derive(Schema))]` on the struct, that derive is not
///    duplicated.
///
/// # `#[dto]` vs [`macro@model`]
///
/// Both are struct attributes, but they describe different things and live in
/// different files:
///
/// | | `#[model]` (ORM) | `#[dto]` (this macro) |
/// |---|---|---|
/// | What | A persistent record | A wire-level data shape |
/// | Where it lives | `apps/<app>/models/*.rs` | `apps/<app>/shared/types.rs` |
/// | Where it runs | Server only (`native`) | Both server (`native`) and client (`wasm`) |
/// | What it adds | Table mapping, primary key, FK fields, migrations | Validate + OpenAPI `Schema` derives (native-only), wraps `#[validate(...)]` |
/// | Boundary it crosses | Rust ↔ database | Server ↔ client (via `#[server_fn]`, REST handlers, WebSocket payloads) |
///
/// "DTO" is the industry-standard term for the second row — a data-transfer
/// object that is serialized on one side, sent over the wire, and
/// deserialized on the other side.
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt::dto;
/// use serde::{Deserialize, Serialize};
///
/// #[dto]
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// pub struct LoginRequest {
///     #[validate(email(message = "Invalid email address"))]
///     pub email: String,
///
///     #[validate(length(min = 1, message = "Password is required"))]
///     pub password: String,
/// }
/// ```
///
/// Expands (conceptually) to:
///
/// ```rust,ignore
/// #[cfg_attr(native, derive(::reinhardt::Validate, ::reinhardt::rest::openapi::Schema))]
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// pub struct LoginRequest {
///     #[cfg_attr(native, validate(email(message = "Invalid email address")))]
///     pub email: String,
///
///     #[cfg_attr(native, validate(length(min = 1, message = "Password is required")))]
///     pub password: String,
/// }
/// ```
///
/// # Requirements
///
/// - The consumer crate's **native** build of `reinhardt` MUST enable the
///   `rest` feature — the macro expansion references
///   `::reinhardt::rest::openapi::Schema`.
/// - Applies only to `struct` items (named, tuple, or unit). Enums and unions
///   produce a compile error.
/// - Does not accept arguments in this version. Passing any tokens (e.g.
///   `#[dto(no_schema)]`) is a compile error.
/// - Unconditional `#[derive(Validate)]` or `#[derive(Schema)]` on the same
///   struct is a compile error. Both traits live behind the `native` cfg, so
///   an unconditional derive cannot resolve on wasm and would duplicate the
///   macro's emission on native. Either delete the derive (and let `#[dto]`
///   emit it) or wrap it in `#[cfg_attr(native, derive(...))]` yourself.
/// - Any pre-existing `#[cfg_attr(native, derive(Validate))]` or
///   `#[cfg_attr(native, derive(Schema))]` MUST be written *below* `#[dto]`,
///   not above it. Attribute proc macros only observe attributes that appear
///   under them in source order, so a `cfg_attr` placed above `#[dto]` is
///   invisible to the macro and would cause `#[dto]` to emit a duplicate
///   `cfg_attr(native, derive(...))` on native. Example of the supported
///   ordering:
///
/// ```rust,ignore
/// #[dto]
/// #[cfg_attr(native, derive(Schema))]
/// pub struct LoginRequest { /* ... */ }
/// ```
#[proc_macro_attribute]
pub fn dto(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as syn::DeriveInput);

	dto::dto_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Settings attribute macro for composable configuration.
///
/// # Fragment mode
///
/// Marks a struct as a settings fragment:
///
/// ```rust,ignore
/// #[settings(fragment = true, section = "cache")]
/// pub struct CacheSettings {
///     pub backend: String,
/// }
/// ```
///
/// # Composition mode
///
/// Composes fragments into a project settings struct.
///
/// Supports two syntax forms:
/// - **Explicit**: `key: Type` — specify field name explicitly
/// - **Implicit**: `Type` — infer field name from type (requires `Settings` suffix)
///
/// Both forms can be mixed freely:
///
/// ```rust,ignore
/// // All implicit (XxxSettings → xxx)
/// #[settings(CoreSettings | CacheSettings | SessionSettings)]
/// pub struct ProjectSettings;
///
/// // Mixed implicit + explicit
/// #[settings(CoreSettings | CacheSettings | static_files: StaticSettings)]
/// pub struct ProjectSettings;
///
/// // Explicit only (original syntax, still fully supported)
/// #[settings(core: CoreSettings | cache: CacheSettings)]
/// pub struct ProjectSettings;
/// ```
///
/// Types without `Settings` suffix require explicit `key: Type` syntax. Note that
/// even for `*Settings` types, if the inferred field name would be a Rust keyword
/// (e.g. `StaticSettings` → `static`), you must use explicit `key: Type` syntax,
/// as in `static_files: StaticSettings` above.
#[proc_macro_attribute]
pub fn settings(args: TokenStream, input: TokenStream) -> TokenStream {
	let input_struct = parse_macro_input!(input as ItemStruct);

	// Detect mode: if args contain "fragment", use fragment handler
	let args_str = args.to_string();
	if args_str.contains("fragment") {
		settings_fragment::settings_fragment_impl(args.into(), input_struct)
			.unwrap_or_else(|e| e.to_compile_error())
			.into()
	} else {
		settings_compose::settings_compose_impl(args.into(), input_struct)
			.unwrap_or_else(|e| e.to_compile_error())
			.into()
	}
}

/// WebSocket consumer macro. Parallel to `#[get]` / `#[post]`.
///
/// Annotates an `async fn` that handles WebSocket messages (`on_message`).
/// Generates a `{FnName}Consumer` struct implementing `WebSocketConsumer`,
/// a factory function, inventory metadata, and URL resolver extension traits.
///
/// # Example
///
/// ```ignore
/// use reinhardt::websocket;
/// use reinhardt_websockets::consumers::{ConsumerContext, WebSocketResult};
/// use reinhardt_websockets::connection::Message;
///
/// #[websocket("/ws/chat/{room_id}/", name = "chat_ws")]
/// pub async fn chat_ws(
///     context: &mut ConsumerContext,
///     message: Message,
/// ) -> WebSocketResult<()> {
///     context.send_text("pong".to_string()).await
/// }
/// ```
#[proc_macro_attribute]
pub fn websocket(args: TokenStream, input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as ItemFn);
	websocket::websocket_impl(args.into(), input)
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}

/// Function-like proc macro for multi-file view modules.
///
/// When a view module uses per-file endpoint organization (one file per view in
/// `views/`), the URL resolver modules generated by `#[get]`/`#[post]`/etc.
/// live inside the submodules. This macro generates `pub use submod::*;`
/// for each `pub mod` declaration, bringing endpoint functions and their
/// resolver modules into the parent module scope.
///
/// This enables `#[url_patterns]` to discover resolvers using the standard
/// parent-module path convention (e.g., `.endpoint(views::login)`).
///
/// # Usage
///
/// ```rust,ignore
/// // views.rs (multi-file pattern)
/// use reinhardt::flatten_imports;
///
/// flatten_imports! {
///     pub mod login;
///     pub mod register;
/// }
///
/// // Generates:
/// //   pub mod login;
/// //   pub mod register;
/// //   pub use login::*;
/// //   pub use register::*;
/// ```
///
/// For single-file views where all functions are defined directly in
/// `views.rs`, this macro is not needed.
#[proc_macro]
pub fn flatten_imports(input: TokenStream) -> TokenStream {
	flatten_imports::flatten_imports_impl(input.into())
		.unwrap_or_else(|e| e.to_compile_error())
		.into()
}