rustf-macros 1.0.0

Procedural macros for RustF framework - auto-discovery of controllers and models
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
//! RustF Macros - Procedural macros for auto-discovery
//!
//! This crate provides build-time macros to automatically discover and include
//! controllers and models without requiring manual mod.rs files.

use proc_macro::TokenStream;
use quote::quote;
use std::path::PathBuf;
use syn::{parse_macro_input, parse_quote, ItemFn};
use walkdir::WalkDir;

/// Auto-discover and include all controllers from src/controllers/*.rs
///
/// This macro scans the controllers directory at build time and generates
/// the necessary module declarations and route aggregation code.
///
/// # Usage
/// ```rust,ignore
/// use rustf::prelude::*;
///
/// let routes = auto_controllers!();
/// let app = RustF::new().controllers(routes);
/// ```
#[proc_macro]
pub fn auto_controllers(_input: TokenStream) -> TokenStream {
    generate_auto_discovery("controllers", "install").into()
}

/// Auto-discover and include all models from src/models/*.rs
///
/// This macro scans the models directory at build time and generates
/// the necessary module declarations and model registration code.
///
/// # Usage
/// ```rust,ignore
/// use rustf::prelude::*;
///
/// let register_fn = auto_models!();
/// let app = RustF::new().models(register_fn);
/// ```
#[proc_macro]
pub fn auto_models(_input: TokenStream) -> TokenStream {
    generate_auto_discovery("models", "register").into()
}

/// Auto-discover and include all middleware from src/middleware/*.rs
///
/// This macro scans the middleware directory at build time and generates
/// the necessary module declarations and middleware registration code.
///
/// # Usage
/// ```rust,ignore
/// use rustf::prelude::*;
///
/// let register_fn = auto_middleware!();
/// let app = RustF::new().middleware_from(register_fn);
/// ```
#[proc_macro]
pub fn auto_middleware(_input: TokenStream) -> TokenStream {
    generate_auto_discovery("middleware", "install").into()
}

/// Auto-discover and include all definitions from src/definitions/*.rs
///
/// This macro scans the definitions directory at build time and generates
/// the necessary module declarations and registration code.
/// Each file should implement either Helpers or Validators trait.
///
/// # Usage
/// ```rust,ignore
/// let app = RustF::new()
///     .definitions_from(auto_definitions!());
/// ```
#[proc_macro]
pub fn auto_definitions(_input: TokenStream) -> TokenStream {
    generate_auto_discovery("definitions", "install").into()
}

/// Auto-discover and include all modules from src/modules/*.rs
///
/// This macro scans the modules directory at build time and generates
/// the necessary module declarations and module registration code.
/// Following Total.js inspiration, modules contain reusable business logic.
///
/// # Usage
/// ```rust,ignore
/// use rustf::prelude::*;
///
/// let register_fn = auto_modules!();
/// let app = RustF::new().modules_from(register_fn);
/// ```
#[proc_macro]
pub fn auto_modules(_input: TokenStream) -> TokenStream {
    generate_auto_discovery("modules", "install").into()
}

/// Auto-discover and include all event handlers from src/events/*.rs
///
/// This macro scans the events directory at build time and generates
/// the necessary module declarations and event handler registration code.
///
/// # Usage
/// ```rust,ignore
/// use rustf::prelude::*;
///
/// let register_fn = auto_events!();
/// let app = RustF::new().events_from(register_fn);
/// ```
#[proc_macro]
pub fn auto_events(_input: TokenStream) -> TokenStream {
    generate_auto_discovery("events", "install").into()
}

/// Auto-discover and include all workers from src/workers/*.rs
///
/// This macro scans the workers directory at build time and generates
/// the necessary module declarations and worker registration code.
/// Each file should have an async `install()` function that registers workers.
///
/// # Usage
/// ```rust,ignore
/// use rustf::prelude::*;
///
/// let app = RustF::new()
///     .with_workers()
///     .workers_from(auto_workers!());
/// ```
#[proc_macro]
pub fn auto_workers(_input: TokenStream) -> TokenStream {
    generate_worker_discovery().into()
}

/// Generate auto-discovery code for a given directory and function name
fn generate_auto_discovery(dir_name: &str, fn_name: &str) -> proc_macro2::TokenStream {
    let manifest_dir =
        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR should be set during build");

    let src_dir = PathBuf::from(&manifest_dir).join("src").join(dir_name);

    // Check if we're in the rustf framework itself by looking for Cargo.toml [package] name
    let cargo_toml_path = PathBuf::from(&manifest_dir).join("Cargo.toml");
    let is_rustf_framework = if cargo_toml_path.exists() {
        if let Ok(contents) = std::fs::read_to_string(&cargo_toml_path) {
            contents.contains("name = \"rustf\"") && !contents.contains("name = \"rustf-")
        } else {
            false
        }
    } else {
        false
    };

    // If we're in the rustf framework itself, don't try to auto-discover framework internal modules
    // Only auto-discover in user projects
    let should_skip = is_rustf_framework
        && matches!(
            dir_name,
            "models" | "workers" | "definitions" | "middleware" | "events"
        );

    if should_skip || !src_dir.exists() {
        // If directory doesn't exist or we should skip it, return empty implementation
        // Use correct path prefix based on whether we're in rustf framework or user project
        let path_prefix = if is_rustf_framework {
            quote! { crate }
        } else {
            quote! { rustf }
        };

        return match dir_name {
            "controllers" => quote! {
                {
                    Vec::new()
                }
            },
            "models" => quote! {
                {
                    |_registry: &mut #path_prefix::models::ModelRegistry| {
                        // No models to register
                    }
                }
            },
            "middleware" => quote! {
                {
                    |_registry: &mut #path_prefix::middleware::MiddlewareRegistry| {
                        // No middleware to register
                    }
                }
            },
            "events" => quote! {
                {
                    |_emitter: &mut #path_prefix::events::EventEmitter| {
                        // No event handlers to register
                    }
                }
            },
            "definitions" => quote! {
                {
                    |_defs: &mut #path_prefix::definitions::Definitions| {
                        // No definitions to register
                    }
                }
            },
            _ => quote! { compile_error!("Unknown directory type"); },
        };
    }

    let mut modules = Vec::new();
    let mut function_calls = Vec::new();

    // Walk through all .rs files in the directory with max depth of 3
    for entry in WalkDir::new(&src_dir)
        .min_depth(1)
        .max_depth(3) // Support up to 3 levels of nesting
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();

        // Skip directories (we only want files)
        if path.is_dir() {
            continue;
        }

        // Skip if not a .rs file
        if path.extension().and_then(|s| s.to_str()) != Some("rs") {
            continue;
        }

        // Skip mod.rs files if they exist
        if path.file_name().and_then(|s| s.to_str()) == Some("mod.rs") {
            continue;
        }

        // Skip .inc.rs files (included code fragments)
        if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
            if file_name.ends_with(".inc.rs") {
                continue;
            }
            // Skip files starting with underscore
            if file_name.starts_with("_") {
                continue;
            }
        }

        // Create the module path relative to the target directory
        let relative_to_target = path
            .strip_prefix(&src_dir)
            .expect("Path should be under target directory");

        // Build nested module path (e.g., api::v1::users for api/v1/users.rs)
        let mut path_components = Vec::new();
        for component in relative_to_target.components() {
            if let std::path::Component::Normal(name) = component {
                if let Some(name_str) = name.to_str() {
                    // Remove .rs extension from the last component
                    if name_str.ends_with(".rs") {
                        path_components.push(name_str.trim_end_matches(".rs"));
                    } else {
                        path_components.push(name_str);
                    }
                }
            }
        }

        // Create the full module path (e.g., "api::v1::users")
        let _module_path = path_components.join("::");

        // Generate unique module identifier for nested paths
        let module_ident_str = path_components.join("_");
        let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());

        // Create relative path from the src directory (where main.rs is located)
        let src_dir_base = PathBuf::from(&manifest_dir).join("src");
        let relative_path = path
            .strip_prefix(&src_dir_base)
            .expect("Path should be under src directory")
            .to_string_lossy()
            .replace('\\', "/"); // Normalize path separators

        // Generate module declaration with nested structure
        if path_components.len() == 1 {
            // Top-level module (e.g., controllers/home.rs)
            let module_name = path_components[0];
            let module_ident = syn::Ident::new(module_name, proc_macro2::Span::call_site());
            modules.push(quote! {
                #[path = #relative_path]
                pub mod #module_ident;
            });

            // Generate function call using the simple identifier
            match dir_name {
                "controllers" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        routes.extend(#module_ident::#fn_ident());
                    });
                }
                "models" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident(registry);
                    });
                }
                "middleware" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident(registry);
                    });
                }
                "modules" => {
                    // Modules are now discovered but NOT automatically registered
                    // Developers must explicitly call MODULE::register() with a unique name
                    // This allows multiple instances of the same type
                    // (no code generation needed - just module declarations)
                }
                "events" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident(emitter);
                    });
                }
                "definitions" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident(defs);
                    });
                }
                "workers" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident().await?;
                    });
                }
                _ => {}
            }
        } else {
            // Nested module (e.g., controllers/api/users.rs)
            // We need to create nested module structure
            modules.push(quote! {
                #[path = #relative_path]
                pub mod #module_ident;
            });

            // Generate function call with full module path
            match dir_name {
                "controllers" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        routes.extend(#module_ident::#fn_ident());
                    });
                }
                "models" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident(registry);
                    });
                }
                "middleware" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident(registry);
                    });
                }
                "modules" => {
                    // Modules are now discovered but NOT automatically registered
                    // Developers must explicitly call MODULE::register() with a unique name
                    // This allows multiple instances of the same type
                    // (no code generation needed - just module declarations)
                }
                "events" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident(emitter);
                    });
                }
                "definitions" => {
                    let fn_ident = syn::Ident::new(fn_name, proc_macro2::Span::call_site());
                    function_calls.push(quote! {
                        #module_ident::#fn_ident(defs);
                    });
                }
                _ => {}
            }
        }
    }

    // Generate the final code based on directory type
    // Use correct path prefix based on whether we're in rustf framework or user project
    let path_prefix = if is_rustf_framework {
        quote! { crate }
    } else {
        quote! { rustf }
    };

    match dir_name {
        "controllers" => {
            let controller_count = function_calls.len();
            quote! {
                {
                    // Module declarations
                    #(#modules)*

                    log::info!("Auto-discovery: Loading {} controller(s)", #controller_count);

                    // Function to collect all routes
                    let mut routes = Vec::new();
                    #(#function_calls)*
                    routes
                }
            }
        }
        "models" => {
            let model_count = function_calls.len();
            quote! {
                {
                    // Module declarations
                    #(#modules)*

                    // Function to register all models
                    |registry: &mut #path_prefix::models::ModelRegistry| {
                        log::info!("Auto-discovery: Registering {} model(s)", #model_count);
                        #(#function_calls)*
                    }
                }
            }
        }
        "middleware" => {
            let middleware_count = function_calls.len();
            quote! {
                {
                    // Module declarations
                    #(#modules)*

                    // Function to register all middleware
                    |registry: &mut #path_prefix::middleware::MiddlewareRegistry| {
                        log::info!("Auto-discovery: Registering {} middleware", #middleware_count);
                        #(#function_calls)*
                    }
                }
            }
        }
        "modules" => {
            quote! {
                {
                    // Module declarations (auto-discovery only)
                    #(#modules)*

                    log::info!("Auto-discovery: Found module(s) - explicit MODULE::register() required for registration");
                    // Modules are no longer auto-registered. Developers must explicitly call
                    // MODULE::register("unique-name", module_instance) with a unique name.
                    // This enables multiple instances of the same type with different configs.
                }
            }
        }
        "events" => {
            let event_count = function_calls.len();
            quote! {
                {
                    // Module declarations
                    #(#modules)*

                    // Function to register all event handlers
                    |emitter: &mut #path_prefix::events::EventEmitter| {
                        log::info!("Auto-discovery: Registering {} event handler(s)", #event_count);
                        #(#function_calls)*
                    }
                }
            }
        }
        "definitions" => {
            let definitions_count = function_calls.len();
            quote! {
                {
                    // Module declarations
                    #(#modules)*

                    // Function to register all definitions
                    |defs: &mut #path_prefix::definitions::Definitions| {
                        log::info!("Auto-discovery: Registering {} definition(s)", #definitions_count);
                        #(#function_calls)*
                    }
                }
            }
        }
        _ => quote! { compile_error!("Unknown directory type"); },
    }
}

/// Auto-discover and generate module declarations for the entire application
///
/// This attribute macro scans the filesystem at compile time and generates
/// standard Rust module declarations for modules, controllers, and models.
///
/// # Usage
/// ```rust,ignore
/// use rustf::prelude::*;
///
/// #[rustf::auto_discover]
/// #[tokio::main]
/// async fn main() -> rustf::Result<()> {
///     // Modules are now available via standard Rust module system
///     let user_svc = modules::user_service::UserService::new();
///
///     let app = RustF::new()
///         .controllers(auto_controllers!())
///         .start().await
/// }
/// ```
#[proc_macro_attribute]
pub fn auto_discover(_args: TokenStream, input: TokenStream) -> TokenStream {
    let mut input_fn = parse_macro_input!(input as ItemFn);

    let manifest_dir =
        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR should be set during build");
    let src_dir = PathBuf::from(&manifest_dir).join("src");

    // Generate module declarations for each directory
    let modules_mod = generate_mod_declarations(&src_dir, "modules");
    let controllers_mod = generate_mod_declarations(&src_dir, "controllers");
    let models_mod = generate_mod_declarations(&src_dir, "models");
    let middleware_mod = generate_mod_declarations(&src_dir, "middleware");
    let events_mod = generate_mod_declarations(&src_dir, "events");
    let definitions_mod = generate_mod_declarations(&src_dir, "definitions");

    // Conditionally generate embedded provider structs + registrations
    // Only when the embedded-views feature is active AND we're in a user project
    #[cfg(feature = "embedded-views")]
    let is_rustf_framework = {
        let cargo_toml_path = PathBuf::from(&manifest_dir).join("Cargo.toml");
        if cargo_toml_path.exists() {
            if let Ok(contents) = std::fs::read_to_string(&cargo_toml_path) {
                contents.contains("name = \"rustf\"") && !contents.contains("name = \"rustf-")
            } else {
                false
            }
        } else {
            false
        }
    };

    #[cfg(feature = "embedded-views")]
    let embedded_structs = if !is_rustf_framework {
        let views_folder = format!("{}/views/", manifest_dir);
        let assets_folder = format!("{}/public/", manifest_dir);
        quote! {
            // Auto-generated by #[auto_discover] — DO NOT EDIT
            // Embeds views/ and public/ from this crate at compile time.
            #[derive(rustf::rust_embed::RustEmbed)]
            #[folder = #views_folder]
            #[allow(dead_code)]
            struct __RustfAppViews;

            #[derive(rustf::rust_embed::RustEmbed)]
            #[folder = #assets_folder]
            #[allow(dead_code)]
            struct __RustfAppAssets;

            impl rustf::EmbeddedFileProvider for __RustfAppViews {
                fn get(&self, path: &str) -> Option<Vec<u8>> {
                    <__RustfAppViews as rustf::rust_embed::RustEmbed>::get(path)
                        .map(|f| f.data.into_owned())
                }
                fn files(&self) -> Vec<String> {
                    <__RustfAppViews as rustf::rust_embed::RustEmbed>::iter()
                        .map(|p| p.to_string())
                        .collect()
                }
            }

            impl rustf::EmbeddedFileProvider for __RustfAppAssets {
                fn get(&self, path: &str) -> Option<Vec<u8>> {
                    <__RustfAppAssets as rustf::rust_embed::RustEmbed>::get(path)
                        .map(|f| f.data.into_owned())
                }
                fn files(&self) -> Vec<String> {
                    <__RustfAppAssets as rustf::rust_embed::RustEmbed>::iter()
                        .map(|p| p.to_string())
                        .collect()
                }
            }
        }
    } else {
        quote! {}
    };

    #[cfg(not(feature = "embedded-views"))]
    let embedded_structs = quote! {};

    // Registration statements injected at the start of main()
    #[cfg(feature = "embedded-views")]
    let embed_register_stmt: syn::Stmt = if !is_rustf_framework {
        parse_quote! {
            {
                rustf::register_views_provider(Box::new(__RustfAppViews));
                rustf::register_assets_provider(Box::new(__RustfAppAssets));
            }
        }
    } else {
        parse_quote! { {} }
    };

    #[cfg(not(feature = "embedded-views"))]
    let embed_register_stmt: syn::Stmt = parse_quote! { {} };

    // Inject auto-discovery hook registration at the start of the function body.
    // Note: Modules are no longer auto-registered via hooks. They're discovered via
    // auto_modules!() for IDE support, but developers must call MODULE::register() explicitly.
    let register_stmt = parse_quote! {
        rustf::auto::register_hooks(rustf::auto::AutoDiscoveryHooks {
            controllers: Some(|| controllers::collect_routes()),
            models: Some(|registry: &mut rustf::models::ModelRegistry| {
                models::register_all(registry);
            }),
            shared: None,  // Modules are no longer auto-registered. Explicit registration only.
            middleware: Some(|registry: &mut rustf::middleware::MiddlewareRegistry| {
                middleware::register_all(registry);
            }),
            events: Some(|emitter: &mut rustf::events::EventEmitter| {
                events::register_all(emitter);
            }),
            definitions: Some(|defs: &mut rustf::definitions::Definitions| {
                definitions::register_all(defs);
            }),
            workers: Some(auto_workers!()),
        });
    };

    let mut fn_block = (*input_fn.block).clone();
    // Insert in reverse order so index 0 ends up first
    fn_block.stmts.insert(0, embed_register_stmt);
    fn_block.stmts.insert(0, register_stmt);
    input_fn.block = Box::new(fn_block);

    let expanded = quote! {
        // Auto-generated module declarations
        #modules_mod
        #controllers_mod
        #models_mod
        #middleware_mod
        #events_mod
        #definitions_mod

        // Embedded file provider structs (only when embedded-views feature is active)
        #embedded_structs

        // Original function
        #input_fn
    };

    expanded.into()
}

/// Generate module declarations for a specific directory
fn generate_mod_declarations(src_dir: &PathBuf, dir_name: &str) -> proc_macro2::TokenStream {
    let target_dir = src_dir.join(dir_name);

    if !target_dir.exists() {
        return fallback_module(dir_name);
    }

    let mut generated_module_declarations = Vec::new();
    let mut generated_mod_content = String::new();
    generated_mod_content
        .push_str("// Auto-generated by RustF #[auto_discover] macro - DO NOT EDIT\n");
    generated_mod_content.push_str("// This file is framework-owned and may be overwritten.\n");
    generated_mod_content.push_str(&format!(
        "// Generated module declarations for src/{}/\n\n",
        dir_name
    ));
    let mut aggregator_calls = String::new();

    // Scan for .rs files in the directory with max depth of 3
    for entry in WalkDir::new(&target_dir)
        .min_depth(1)
        .max_depth(3) // Support up to 3 levels of nesting
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();

        // Skip directories
        if path.is_dir() {
            continue;
        }

        // Skip if not a .rs file
        if path.extension().and_then(|s| s.to_str()) != Some("rs") {
            continue;
        }

        // Skip IDE files, mod.rs files, and .inc.rs files
        if let Some(filename) = path.file_name().and_then(|s| s.to_str()) {
            if filename == "mod.rs" || filename.starts_with("_") || filename.ends_with(".inc.rs") {
                continue;
            }
        }

        // Get the relative path from target directory
        let relative_to_target = path
            .strip_prefix(&target_dir)
            .expect("Path should be under target directory");

        // Build nested module path components
        let mut path_components = Vec::new();
        for component in relative_to_target.components() {
            if let std::path::Component::Normal(name) = component {
                if let Some(name_str) = name.to_str() {
                    // Remove .rs extension from the last component
                    if name_str.ends_with(".rs") {
                        path_components.push(name_str.trim_end_matches(".rs"));
                    } else {
                        path_components.push(name_str);
                    }
                }
            }
        }

        if path_components.is_empty() {
            continue;
        }

        // Skip special files for models
        if dir_name == "models" {
            let module_name = path_components.last().unwrap();
            if module_name == &"MODELS_README" || module_name.contains("_generated") {
                continue;
            }
        }

        // Create unique module identifier (e.g., "api_users" for "api/users.rs")
        let module_ident_str = path_components.join("_");
        let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());

        // Generate module declaration with proper path handling
        if path_components.len() == 1 {
            // Simple top-level module - no path attribute needed
            generated_module_declarations.push(quote! {
                pub mod #module_ident;
            });
        } else {
            // Nested module - use path attribute relative to the module we're in
            let relative_path = relative_to_target.to_string_lossy().replace('\\', "/");
            generated_module_declarations.push(quote! {
                #[path = #relative_path]
                pub mod #module_ident;
            });
        }

        let relative_path = relative_to_target.to_string_lossy().replace('\\', "/");
        generated_mod_content.push_str(&format!(
            "#[path = \"../{}/{}\"]\n",
            dir_name, relative_path
        ));
        generated_mod_content.push_str(&format!("pub mod {};\n", module_ident_str));

        match dir_name {
            "controllers" => aggregator_calls.push_str(&format!(
                "    routes.extend({}::install());\n",
                module_ident_str
            )),
            "models" => aggregator_calls.push_str(&format!(
                "    {}::register(registry);\n",
                module_ident_str
            )),
            "middleware" => aggregator_calls.push_str(&format!(
                "    {}::install(registry);\n",
                module_ident_str
            )),
            "events" => aggregator_calls.push_str(&format!(
                "    {}::install(emitter);\n",
                module_ident_str
            )),
            "definitions" => aggregator_calls.push_str(&format!(
                "    {}::install(defs);\n",
                module_ident_str
            )),
            _ => {}
        }
    }

    // Handle special case for models with base subdirectory
    if dir_name == "models" {
        let base_dir = target_dir.join("base");
        if base_dir.exists() {
            let mut base_declarations = Vec::new();
            let mut base_content = String::new();

            for entry in WalkDir::new(&base_dir)
                .min_depth(1)
                .max_depth(1)
                .into_iter()
                .filter_map(|e| e.ok())
            {
                let path = entry.path();

                if path.extension().and_then(|s| s.to_str()) == Some("rs") {
                    // Skip .inc.rs files (included code fragments)
                    if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
                        if file_name.ends_with(".inc.rs") {
                            continue;
                        }
                    }

                    if let Some(module_name) = path.file_stem().and_then(|s| s.to_str()) {
                        let module_ident =
                            syn::Ident::new(module_name, proc_macro2::Span::call_site());
                        base_declarations.push(quote! {
                            pub mod #module_ident;
                        });
                        base_content
                            .push_str(&format!("    #[path = \"base/{}.rs\"]\n", module_name));
                        base_content.push_str(&format!("    pub mod {};\n", module_name));
                    }
                }
            }

            if !base_declarations.is_empty() {
                generated_module_declarations.push(quote! {
                    pub mod base {
                        #(#base_declarations)*
                    }
                });

                generated_mod_content.push_str("\npub mod base {\n");
                generated_mod_content.push_str(&base_content);
                generated_mod_content.push_str("}\n");
            }
        }
    }

    match dir_name {
        "controllers" => generated_mod_content.push_str(
            "\npub fn collect_routes() -> Vec<rustf::routing::Route> {\n    let mut routes = Vec::new();\n",
        ),
        "models" => generated_mod_content.push_str(
            "\npub fn register_all(registry: &mut rustf::models::ModelRegistry) {\n",
        ),
        "middleware" => generated_mod_content.push_str(
            "\npub fn register_all(registry: &mut rustf::middleware::MiddlewareRegistry) {\n",
        ),
        "events" => generated_mod_content
            .push_str("\npub fn register_all(emitter: &mut rustf::events::EventEmitter) {\n"),
        "definitions" => generated_mod_content.push_str(
            "\npub fn register_all(defs: &mut rustf::definitions::Definitions) {\n",
        ),
        _ => {}
    }

    if !aggregator_calls.is_empty() {
        generated_mod_content.push_str(&aggregator_calls);
    }

    match dir_name {
        "controllers" => generated_mod_content.push_str("    routes\n}\n"),
        "models" | "middleware" | "events" | "definitions" => {
            generated_mod_content.push_str("}\n");
        }
        _ => {}
    }

    // Write generated support files
    if !generated_module_declarations.is_empty() {
        let legacy_ide_file_path = src_dir.join(format!("_{}.rs", dir_name));
        if legacy_ide_file_path.exists() {
            if let Err(e) = std::fs::remove_file(&legacy_ide_file_path) {
                let message = format!(
                    "RustF auto-discovery failed to remove legacy IDE file '{}': {}",
                    legacy_ide_file_path.display(),
                    e
                );
                return quote! { compile_error!(#message); };
            }
        }

        let generated_dir = src_dir.join(".rustf");
        if let Err(e) = std::fs::create_dir_all(&generated_dir) {
            let message = format!(
                "RustF auto-discovery failed to create '{}': {}",
                generated_dir.display(),
                e
            );
            return quote! { compile_error!(#message); };
        }

        let generated_file_path = generated_dir.join(format!("{}_gen.rs", dir_name));
        if let Err(e) = std::fs::write(&generated_file_path, &generated_mod_content) {
            let message = format!(
                "RustF auto-discovery failed to write '{}': {}",
                generated_file_path.display(),
                e
            );
            return quote! { compile_error!(#message); };
        }

        if let Err(message) = ensure_wrapper_module(src_dir, dir_name) {
            return quote! { compile_error!(#message); };
        }
    }

    if generated_module_declarations.is_empty() {
        return fallback_module(dir_name);
    }

    // Return wrapper module import for compilation
    let dir_ident = syn::Ident::new(dir_name, proc_macro2::Span::call_site());
    let wrapper_relative_path = format!("{}/mod.rs", dir_name);
    quote! {
        #[path = #wrapper_relative_path]
        mod #dir_ident;
    }
}

fn fallback_module(dir_name: &str) -> proc_macro2::TokenStream {
    let dir_ident = syn::Ident::new(dir_name, proc_macro2::Span::call_site());
    match dir_name {
        "controllers" => quote! {
            mod #dir_ident {
                pub fn collect_routes() -> Vec<rustf::routing::Route> {
                    Vec::new()
                }
            }
        },
        "models" => quote! {
            mod #dir_ident {
                pub fn register_all(_registry: &mut rustf::models::ModelRegistry) {}
            }
        },
        "middleware" => quote! {
            mod #dir_ident {
                pub fn register_all(_registry: &mut rustf::middleware::MiddlewareRegistry) {}
            }
        },
        "events" => quote! {
            mod #dir_ident {
                pub fn register_all(_emitter: &mut rustf::events::EventEmitter) {}
            }
        },
        "definitions" => quote! {
            mod #dir_ident {
                pub fn register_all(_defs: &mut rustf::definitions::Definitions) {}
            }
        },
        _ => quote! {
            mod #dir_ident {}
        },
    }
}

fn ensure_wrapper_module(src_dir: &PathBuf, dir_name: &str) -> Result<(), String> {
    let wrapper_path = src_dir.join(dir_name).join("mod.rs");
    if !wrapper_path.exists() {
        if let Some(parent) = wrapper_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                format!(
                    "RustF auto-discovery failed to create '{}': {}",
                    parent.display(),
                    e
                )
            })?;
        }

        std::fs::write(&wrapper_path, wrapper_template(dir_name)).map_err(|e| {
            format!(
                "RustF auto-discovery failed to write '{}': {}",
                wrapper_path.display(),
                e
            )
        })?;
        return Ok(());
    }

    validate_wrapper_module(&wrapper_path, dir_name)
}

fn wrapper_template(dir_name: &str) -> String {
    format!(
        "// Auto-generated scaffold for RustF auto-discovery.\n\
// You may add custom code here, but keep the generated import and re-export intact.\n\
#[path = \"../.rustf/{dir_name}_gen.rs\"]\n\
mod generated;\n\n\
pub use generated::*;\n"
    )
}

fn validate_wrapper_module(wrapper_path: &std::path::Path, dir_name: &str) -> Result<(), String> {
    let expected_path = format!("../.rustf/{}_gen.rs", dir_name);
    let contents = std::fs::read_to_string(wrapper_path).map_err(|e| {
        format!(
            "RustF auto-discovery failed to read '{}': {}",
            wrapper_path.display(),
            e
        )
    })?;

    let parsed = syn::parse_file(&contents).map_err(|e| {
        format!(
            "RustF auto-discovery found invalid Rust in '{}': {}",
            wrapper_path.display(),
            e
        )
    })?;

    let mut has_generated_mod = false;
    let mut has_generated_reexport = false;

    for item in parsed.items {
        match item {
            syn::Item::Mod(item_mod) if item_mod.ident == "generated" => {
                if item_mod.content.is_some() {
                    return Err(format!(
                        "RustF auto-discovery rejected '{}': `mod generated` must stay external and point to '{}'",
                        wrapper_path.display(),
                        expected_path
                    ));
                }

                let mut matches_expected_path = false;
                for attr in item_mod.attrs {
                    if attr.path().is_ident("path") {
                        if let syn::Meta::NameValue(name_value) = &attr.meta {
                            if let syn::Expr::Lit(expr_lit) = &name_value.value {
                                if let syn::Lit::Str(lit) = &expr_lit.lit {
                                    matches_expected_path = lit.value() == expected_path;
                                }
                            }
                        }
                    }
                }

                if !matches_expected_path {
                    return Err(format!(
                        "RustF auto-discovery rejected '{}': `mod generated` must use #[path = \"{}\"]",
                        wrapper_path.display(),
                        expected_path
                    ));
                }

                has_generated_mod = true;
            }
            syn::Item::Use(item_use) if is_generated_glob_reexport(&item_use) => {
                has_generated_reexport = true;
            }
            _ => {}
        }
    }

    if !has_generated_mod {
        return Err(format!(
            "RustF auto-discovery rejected '{}': missing required generated module import `#[path = \"{}\"] mod generated;`",
            wrapper_path.display(),
            expected_path
        ));
    }

    if !has_generated_reexport {
        return Err(format!(
            "RustF auto-discovery rejected '{}': missing required `pub use generated::*;` re-export",
            wrapper_path.display()
        ));
    }

    Ok(())
}

fn is_generated_glob_reexport(item_use: &syn::ItemUse) -> bool {
    if !matches!(item_use.vis, syn::Visibility::Public(_)) {
        return false;
    }

    match &item_use.tree {
        syn::UseTree::Path(path) if path.ident == "generated" => {
            matches!(&*path.tree, syn::UseTree::Glob(_))
        }
        _ => false,
    }
}

/// Utility macro to include a directory of Rust files as modules
///
/// This is a more generic version that can be used for custom directory structures.
/// Note: This is a placeholder for future extensibility.
#[proc_macro]
pub fn include_dir_as_modules(_input: TokenStream) -> TokenStream {
    // For now, this is a placeholder - could be implemented later if needed
    quote! {
        compile_error!("include_dir_as_modules! is not yet implemented. Use auto_controllers! or auto_models! instead.");
    }.into()
}

/// Generate worker auto-discovery code
/// Returns an async closure compatible with workers_from()
fn generate_worker_discovery() -> proc_macro2::TokenStream {
    let manifest_dir =
        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR should be set during build");

    let src_dir = PathBuf::from(&manifest_dir).join("src").join("workers");

    // Check if we're in the rustf framework itself by looking for Cargo.toml [package] name
    let cargo_toml_path = PathBuf::from(&manifest_dir).join("Cargo.toml");
    let is_rustf_framework = if cargo_toml_path.exists() {
        if let Ok(contents) = std::fs::read_to_string(&cargo_toml_path) {
            contents.contains("name = \"rustf\"") && !contents.contains("name = \"rustf-")
        } else {
            false
        }
    } else {
        false
    };

    // If we're in the rustf framework itself, don't try to auto-discover workers
    // (workers/ is an internal module, not user-defined workers)
    let path_prefix = if is_rustf_framework {
        quote! { crate }
    } else {
        quote! { rustf }
    };

    if is_rustf_framework || !src_dir.exists() {
        // Return empty implementation
        return quote! {
            {
                |_manager: std::sync::Arc<#path_prefix::workers::WorkerManager>| {
                    Box::pin(async move {
                        // No workers to register
                        Ok(())
                    })
                }
            }
        };
    }

    let mut modules = Vec::new();
    let mut function_calls = Vec::new();

    // Walk through all .rs files in the workers directory
    for entry in WalkDir::new(&src_dir)
        .min_depth(1)
        .max_depth(3)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();

        // Skip directories
        if path.is_dir() {
            continue;
        }

        // Skip if not a .rs file
        if path.extension().and_then(|s| s.to_str()) != Some("rs") {
            continue;
        }

        // Skip mod.rs files
        if path.file_name().and_then(|s| s.to_str()) == Some("mod.rs") {
            continue;
        }

        // Skip .inc.rs files and files starting with underscore
        if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
            if file_name.ends_with(".inc.rs") || file_name.starts_with("_") {
                continue;
            }
        }

        // Create the module path relative to the workers directory
        let relative_to_workers = path
            .strip_prefix(&src_dir)
            .expect("Path should be under workers directory");

        // Build nested module path
        let mut path_components = Vec::new();
        for component in relative_to_workers.components() {
            if let std::path::Component::Normal(name) = component {
                if let Some(name_str) = name.to_str() {
                    if name_str.ends_with(".rs") {
                        path_components.push(name_str.trim_end_matches(".rs"));
                    } else {
                        path_components.push(name_str);
                    }
                }
            }
        }

        if path_components.is_empty() {
            continue;
        }

        // Generate unique module identifier
        let module_ident_str = path_components.join("_");
        let module_ident = syn::Ident::new(&module_ident_str, proc_macro2::Span::call_site());

        // Create relative path from src directory
        let src_dir_base = PathBuf::from(&manifest_dir).join("src");
        let relative_path = path
            .strip_prefix(&src_dir_base)
            .expect("Path should be under src directory")
            .to_string_lossy()
            .replace('\\', "/");

        // Generate module declaration
        modules.push(quote! {
            #[path = #relative_path]
            pub mod #module_ident;
        });

        // Generate async install call
        function_calls.push(quote! {
            #module_ident::install().await?;
        });
    }

    let worker_count = function_calls.len();

    quote! {
        {
            // Module declarations
            #(#modules)*

            // Return async closure for workers_from()
            |_manager: std::sync::Arc<#path_prefix::workers::WorkerManager>| {
                Box::pin(async move {
                    log::info!("Auto-discovery: Loading {} worker(s)", #worker_count);
                    #(#function_calls)*
                    Ok(())
                })
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::Path;
    use std::sync::{Mutex, MutexGuard};
    use tempfile::TempDir;

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    struct ManifestGuard {
        _lock: MutexGuard<'static, ()>,
        previous: Option<String>,
    }

    impl ManifestGuard {
        fn enter(manifest_dir: &Path) -> Self {
            let lock = ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());
            let previous = std::env::var("CARGO_MANIFEST_DIR").ok();
            std::env::set_var("CARGO_MANIFEST_DIR", manifest_dir);
            Self {
                _lock: lock,
                previous,
            }
        }
    }

    impl Drop for ManifestGuard {
        fn drop(&mut self) {
            if let Some(previous) = &self.previous {
                std::env::set_var("CARGO_MANIFEST_DIR", previous);
            } else {
                std::env::remove_var("CARGO_MANIFEST_DIR");
            }
        }
    }

    fn create_manifest(name: &str) -> TempDir {
        let temp_dir = TempDir::new().expect("temp dir");
        fs::create_dir_all(temp_dir.path().join("src")).expect("src dir");
        fs::write(
            temp_dir.path().join("Cargo.toml"),
            format!("[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", name),
        )
        .expect("cargo toml");
        temp_dir
    }

    fn write_rs(path: &Path, body: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("parent dir");
        }
        fs::write(path, body).expect("rust file");
    }

    #[test]
    fn auto_discovery_discovers_nested_controllers_and_skips_special_files() {
        let temp_dir = create_manifest("fixture-app");
        write_rs(
            &temp_dir.path().join("src/controllers/home.rs"),
            "pub fn install() -> Vec<()> { vec![] }",
        );
        write_rs(
            &temp_dir.path().join("src/controllers/api/users.rs"),
            "pub fn install() -> Vec<()> { vec![] }",
        );
        write_rs(
            &temp_dir.path().join("src/controllers/_private.rs"),
            "pub fn install() -> Vec<()> { vec![] }",
        );
        write_rs(
            &temp_dir.path().join("src/controllers/shared.inc.rs"),
            "pub fn install() -> Vec<()> { vec![] }",
        );
        write_rs(
            &temp_dir.path().join("src/controllers/mod.rs"),
            "pub fn ignored() {}",
        );

        let _guard = ManifestGuard::enter(temp_dir.path());
        let tokens = generate_auto_discovery("controllers", "install").to_string();

        assert!(tokens.contains("home"));
        assert!(tokens.contains("api_users"));
        assert!(tokens.contains("routes . extend (home :: install ())"));
        assert!(tokens.contains("routes . extend (api_users :: install ())"));
        assert!(tokens.contains("Loading {} controller(s)"));
        assert!(!tokens.contains("_private"));
        assert!(!tokens.contains("shared.inc"));
    }

    #[test]
    fn auto_discovery_skips_framework_internal_models() {
        let temp_dir = create_manifest("rustf");
        write_rs(
            &temp_dir.path().join("src/models/user.rs"),
            "pub fn register(_: &mut ()) {}",
        );

        let _guard = ManifestGuard::enter(temp_dir.path());
        let tokens = generate_auto_discovery("models", "register").to_string();

        assert!(tokens.contains("| _registry : & mut crate :: models :: ModelRegistry |"));
        assert!(!tokens.contains("user"));
    }

    #[test]
    fn worker_discovery_generates_async_install_calls() {
        let temp_dir = create_manifest("fixture-app");
        write_rs(
            &temp_dir.path().join("src/workers/email.rs"),
            "pub async fn install() -> Result<(), ()> { Ok(()) }",
        );
        write_rs(
            &temp_dir.path().join("src/workers/jobs/cleanup.rs"),
            "pub async fn install() -> Result<(), ()> { Ok(()) }",
        );

        let _guard = ManifestGuard::enter(temp_dir.path());
        let tokens = generate_worker_discovery().to_string();

        assert!(tokens.contains("email :: install () . await ?"));
        assert!(tokens.contains("jobs_cleanup :: install () . await ?"));
        assert!(tokens.contains("Loading {} worker(s)"));
    }

    #[test]
    fn generate_mod_declarations_creates_wrapper_and_generated_files() {
        let temp_dir = create_manifest("fixture-app");
        write_rs(
            &temp_dir.path().join("src/controllers/home.rs"),
            "pub fn install() -> Vec<()> { vec![] }",
        );

        let _guard = ManifestGuard::enter(temp_dir.path());
        let tokens = generate_mod_declarations(&temp_dir.path().join("src"), "controllers")
            .to_string();

        assert!(tokens.contains("# [path = \"controllers/mod.rs\"] mod controllers ;"));

        let wrapper_path = temp_dir.path().join("src/controllers/mod.rs");
        let generated_path = temp_dir.path().join("src/.rustf/controllers_gen.rs");

        let wrapper = fs::read_to_string(wrapper_path).expect("wrapper content");
        let generated = fs::read_to_string(generated_path).expect("generated content");

        assert!(wrapper.contains("#[path = \"../.rustf/controllers_gen.rs\"]"));
        assert!(wrapper.contains("mod generated;"));
        assert!(wrapper.contains("pub use generated::*;"));

        assert!(generated.contains("#[path = \"../controllers/home.rs\"]"));
        assert!(generated.contains("pub mod home;"));
        assert!(!temp_dir.path().join("src/_controllers.rs").exists());
    }

    #[test]
    fn generate_mod_declarations_removes_legacy_underscore_file() {
        let temp_dir = create_manifest("fixture-app");
        write_rs(
            &temp_dir.path().join("src/models/users.rs"),
            "pub fn register(_: &mut ()) {}",
        );
        write_rs(
            &temp_dir.path().join("src/_models.rs"),
            "// legacy auto-generated IDE file",
        );

        let _guard = ManifestGuard::enter(temp_dir.path());
        let tokens = generate_mod_declarations(&temp_dir.path().join("src"), "models").to_string();

        assert!(tokens.contains("# [path = \"models/mod.rs\"] mod models ;"));
        assert!(!temp_dir.path().join("src/_models.rs").exists());
    }

    #[test]
    fn generate_mod_declarations_rejects_invalid_wrapper_shape() {
        let temp_dir = create_manifest("fixture-app");
        write_rs(
            &temp_dir.path().join("src/controllers/home.rs"),
            "pub fn install() -> Vec<()> { vec![] }",
        );
        write_rs(
            &temp_dir.path().join("src/controllers/mod.rs"),
            "mod generated;\n",
        );

        let _guard = ManifestGuard::enter(temp_dir.path());
        let tokens = generate_mod_declarations(&temp_dir.path().join("src"), "controllers")
            .to_string();

        assert!(tokens.contains("compile_error !"));
        assert!(tokens.contains("mod generated"));
        assert!(tokens.contains("controllers_gen.rs"));
    }

    #[test]
    fn generate_mod_declarations_accepts_valid_existing_wrapper() {
        let temp_dir = create_manifest("fixture-app");
        write_rs(
            &temp_dir.path().join("src/models/users.rs"),
            "pub fn register(_: &mut ()) {}",
        );
        write_rs(
            &temp_dir.path().join("src/models/mod.rs"),
            "// custom comment is allowed\n#[path = \"../.rustf/models_gen.rs\"]\nmod generated;\n\npub use generated::*;\n",
        );

        let _guard = ManifestGuard::enter(temp_dir.path());
        let tokens = generate_mod_declarations(&temp_dir.path().join("src"), "models").to_string();

        assert!(tokens.contains("# [path = \"models/mod.rs\"] mod models ;"));
    }
}