ic-asset-router 0.1.1

File-based HTTP routing with IC response certification for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;

/// Reserved filenames that are never registered as route handlers.
///
/// These files have special semantics in the file-based routing convention:
/// - `middleware` — middleware function for the directory and its children
/// - `not_found` — custom 404 handler for unmatched routes
///
/// Files not in this list (including `all`, `index`) are treated as regular
/// route handlers.
///
/// # Escape hatch for reserved name collisions
///
/// If you need a route at a path that collides with a reserved filename
/// (e.g. `/middleware` or `/not_found`), use a differently-named file with a
/// `#[route(path = "...")]` attribute override:
///
/// ```text
/// // File: src/routes/mw_page.rs
/// #[route(path = "middleware")]
/// pub fn get(...) -> HttpResponse { ... }
/// ```
///
/// This registers a route at `/middleware` without conflicting with the
/// reserved `middleware.rs` convention.
const RESERVED_FILES: &[&str] = &["middleware", "not_found"];

/// Recognized HTTP method function names and their corresponding `Method` enum variants.
const METHOD_NAMES: &[(&str, &str)] = &[
    ("get", "Method::GET"),
    ("post", "Method::POST"),
    ("put", "Method::PUT"),
    ("patch", "Method::PATCH"),
    ("delete", "Method::DELETE"),
    ("head", "Method::HEAD"),
    ("options", "Method::OPTIONS"),
];

/// A detected method export from a route file.
struct MethodExport {
    /// The route path (e.g. "/api/users")
    route_path: String,
    /// The Rust module path to the handler function (e.g. "routes::api::users::get")
    handler_path: String,
    /// The `Method` variant string (e.g. "Method::GET")
    method_variant: String,
    /// Accumulated dynamic parameters for this route, in order from outermost
    /// to innermost. Empty for static routes.
    params: Vec<ParamMapping>,
    /// The Rust module path to the `Params` struct for this route (e.g.
    /// "routes::posts::_postId::Params"). `None` for routes without dynamic segments.
    params_type_path: Option<String>,
    /// The Rust module path to the `SearchParams` struct for this route (e.g.
    /// "routes::posts::index::SearchParams"). `None` for routes without typed
    /// search params.
    search_params_type_path: Option<String>,
    /// The Rust module path to the route file (e.g. "routes::api::users").
    /// Used to reference the generated `__route_config()` function.
    module_path: String,
    /// Whether the route file has a `#[route(certification = ...)]` attribute.
    /// When true, the generated route tree calls `module_path::__route_config()`.
    /// When false, `RouteConfig::default()` is used.
    has_certification_attribute: bool,
}

/// Mapping from a route param name to its struct field name.
#[derive(Clone)]
struct ParamMapping {
    /// The route-level parameter name (e.g. "postId" from `:postId`).
    route_name: String,
    /// The snake_case field name on the Params struct (e.g. "post_id").
    field_name: String,
}

/// A detected middleware file in a route directory.
struct MiddlewareExport {
    /// The middleware prefix (e.g. "/" for root, "/api" for api directory)
    prefix: String,
    /// The Rust module path to the middleware function (e.g. "routes::middleware::middleware")
    handler_path: String,
}

/// A detected `not_found.rs` file in the routes root directory.
struct NotFoundExport {
    /// The Rust module path to the handler function (e.g. "routes::not_found::get")
    handler_path: String,
}

/// Generate the route tree from the default `src/routes` directory.
///
/// This is a convenience wrapper around [`generate_routes_from`] that uses
/// `"src/routes"` as the routes directory. Call this from your crate's
/// `build.rs`:
///
/// ```rust,ignore
/// // build.rs
/// fn main() {
///     ic_asset_router::build::generate_routes();
/// }
/// ```
pub fn generate_routes() {
    generate_routes_from("src/routes");
}

/// Generate the route tree from a custom routes directory.
///
/// Scans `dir` recursively for `.rs` route files, generates handler wiring
/// code into `OUT_DIR/__route_tree.rs`, creates `mod.rs` files for IDE
/// visibility, and emits a `route_manifest.json` for debugging.
///
/// The `dir` parameter is the path to the routes directory relative to the
/// crate root (e.g. `"src/routes"` or `"src/api/routes"`).
///
/// # Routing conventions
///
/// | Filesystem pattern | URL route | Notes |
/// |--------------------|-----------|-------|
/// | `index.rs` | `/` (parent dir) | Index handler |
/// | `about.rs` | `/about` | Named route |
/// | `og.png.rs` | `/og.png` | Dotted filename — dots are preserved in the URL |
/// | `_postId/index.rs` | `/:postId` | Dynamic segment with typed `Params` struct |
/// | `all.rs` | `/*` | Catch-all wildcard |
/// | `middleware.rs` | — | Scoped middleware |
/// | `not_found.rs` | — | Custom 404 handler |
///
/// ## Dotted filenames
///
/// Files with dots before the `.rs` extension (e.g. `og.png.rs`, `feed.xml.rs`)
/// are served at the literal path including the dot (`/og.png`, `/feed.xml`).
/// The Rust module name replaces dots with underscores (`og_png`), and a
/// `#[path = "og.png.rs"]` attribute is emitted in the generated `mod.rs` so
/// the compiler can locate the source file.
pub fn generate_routes_from(dir: &str) {
    let routes_dir = Path::new(dir);
    let out_dir = std::env::var("OUT_DIR")
        .expect("OUT_DIR not set — this function must be called from a build script");
    let generated_file = Path::new(&out_dir).join("__route_tree.rs");

    // Tell Cargo to re-run the build script when any file in the routes
    // directory changes. We emit rerun-if-changed for the root and every
    // subdirectory so that adding/removing files anywhere in the tree
    // triggers a rebuild.
    println!("cargo:rerun-if-changed={dir}");
    fn emit_rerun_if_changed(dir: &Path) {
        for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
            let path = entry.path();
            println!("cargo:rerun-if-changed={}", path.display());
            if path.is_dir() {
                emit_rerun_if_changed(&path);
            }
        }
    }
    emit_rerun_if_changed(routes_dir);

    let mut exports: Vec<MethodExport> = Vec::new();
    let mut middleware_exports: Vec<MiddlewareExport> = Vec::new();
    let mut not_found_exports: Vec<NotFoundExport> = Vec::new();
    process_directory(
        routes_dir,
        String::new(),
        &mut exports,
        &mut middleware_exports,
        &mut not_found_exports,
        &[],
    );

    // Sort by route path for deterministic output
    exports.sort_by(|a, b| {
        a.route_path
            .cmp(&b.route_path)
            .then(a.method_variant.cmp(&b.method_variant))
    });

    // Sort middleware by prefix for deterministic output
    middleware_exports.sort_by(|a, b| a.prefix.cmp(&b.prefix));

    let mut output = String::new();
    output.push_str("#[allow(unused_imports)]\n");
    output.push_str("use crate::routes;\n");
    output.push_str("#[allow(unused_imports)]\n");
    output.push_str("use ic_asset_router::Method;\n");
    output.push_str("#[allow(unused_imports)]\n");
    output.push_str("use ic_asset_router::router::{NodeType, RouteNode, RouteParams};\n");
    output.push_str("#[allow(unused_imports)]\n");
    output
        .push_str("use ic_asset_router::{HttpRequest, HttpResponse, RouteConfig, RouteContext, parse_query, deserialize_search_params};\n");
    output.push('\n');

    // Generate wrapper functions for each route handler.
    // Each wrapper bridges the router's internal (HttpRequest, RouteParams) signature
    // to the user-facing RouteContext<Params, SearchParams> signature.
    for (i, export) in exports.iter().enumerate() {
        let wrapper_name = format!("__route_handler_{i}");
        output.push_str("#[allow(unused_variables)]\n");
        output.push_str(&format!(
            "fn {wrapper_name}(req: HttpRequest, raw_params: RouteParams) -> HttpResponse<'static> {{\n"
        ));

        // Extract query string for both untyped (query) and typed (search) access.
        // Strips the fragment (#...) if present so serde_urlencoded sees clean input.
        output.push_str(
            "    let __query_str = req.url().split_once('?').map(|(_, q)| q.split_once('#').map_or(q, |(qs, _)| qs)).unwrap_or(\"\");\n",
        );

        // Deserialize typed search params if the route defines SearchParams.
        if let Some(ref search_path) = export.search_params_type_path {
            output.push_str(&format!(
                "    let __search: {search_path} = deserialize_search_params(__query_str);\n"
            ));
        }

        if let Some(ref params_path) = export.params_type_path {
            // Route has dynamic params — construct the typed Params struct.
            output.push_str("    let ctx = RouteContext {\n");
            output.push_str(&format!("        params: {params_path} {{\n"));
            for pm in &export.params {
                output.push_str(&format!(
                    "            {}: ic_asset_router::url_decode(&raw_params.get(\"{}\").cloned().unwrap_or_default()).into_owned(),\n",
                    pm.field_name, pm.route_name,
                ));
            }
            output.push_str("        },\n");
        } else {
            // Static route — use () as the params type.
            output.push_str("    let ctx = RouteContext {\n");
            output.push_str("        params: (),\n");
        }

        // Set the search field: typed SearchParams or () default.
        if export.search_params_type_path.is_some() {
            output.push_str("        search: __search,\n");
        } else {
            output.push_str("        search: (),\n");
        }

        output.push_str("        query: parse_query(req.url()),\n");
        output.push_str("        method: req.method().clone(),\n");
        output.push_str("        headers: req.headers().to_vec(),\n");
        output.push_str("        body: req.body().to_vec(),\n");
        output.push_str("        url: req.url().to_string(),\n");
        output.push_str("        wildcard: raw_params.get(\"*\").map(|w| ic_asset_router::url_decode(w).into_owned()),\n");
        output.push_str("    };\n");
        output.push_str(&format!("    {}(ctx)\n", export.handler_path));
        output.push_str("}\n\n");
    }

    // Generate wrapper function for the not_found handler if present.
    if let Some(nf) = not_found_exports.first() {
        output.push_str("#[allow(unused_variables)]\n");
        output.push_str(
            "fn __not_found_handler(req: HttpRequest, raw_params: RouteParams) -> HttpResponse<'static> {\n",
        );
        output.push_str("    let ctx = RouteContext {\n");
        output.push_str("        params: (),\n");
        output.push_str("        search: (),\n");
        output.push_str("        query: parse_query(req.url()),\n");
        output.push_str("        method: req.method().clone(),\n");
        output.push_str("        headers: req.headers().to_vec(),\n");
        output.push_str("        body: req.body().to_vec(),\n");
        output.push_str("        url: req.url().to_string(),\n");
        output.push_str("        wildcard: None,\n");
        output.push_str("    };\n");
        output.push_str(&format!("    {}(ctx)\n", nf.handler_path));
        output.push_str("}\n\n");
    }

    output.push_str("thread_local! {\n");
    output.push_str("    pub static ROUTES: RouteNode = {\n");
    output.push_str("        let mut root = RouteNode::new(NodeType::Static(\"\".into()));\n");

    for (i, export) in exports.iter().enumerate() {
        output.push_str(&format!(
            "        root.insert(\"{}\", {}, __route_handler_{i});\n",
            export.route_path, export.method_variant,
        ));
    }

    // Generate set_route_config calls. Multiple methods on the same path share
    // the same config, so we deduplicate by route_path.
    {
        let mut seen_paths = std::collections::HashSet::new();
        for export in exports.iter() {
            if seen_paths.insert(export.route_path.clone()) {
                if export.has_certification_attribute {
                    output.push_str(&format!(
                        "        root.set_route_config(\"{}\", {}::__route_config());\n",
                        export.route_path, export.module_path,
                    ));
                } else {
                    output.push_str(&format!(
                        "        root.set_route_config(\"{}\", RouteConfig::default());\n",
                        export.route_path,
                    ));
                }
            }
        }
    }

    for mw in &middleware_exports {
        output.push_str(&format!(
            "        root.set_middleware(\"{}\", {});\n",
            mw.prefix, mw.handler_path,
        ));
    }

    // At most one not_found handler should be registered (from the root not_found.rs).
    if !not_found_exports.is_empty() {
        output.push_str("        root.set_not_found(__not_found_handler);\n");
    }

    output.push_str("        root\n    };\n}\n");

    let mut file = File::create(&generated_file)
        .unwrap_or_else(|e| panic!("failed to create {}: {e}", generated_file.display()));
    file.write_all(output.as_bytes())
        .unwrap_or_else(|e| panic!("failed to write {}: {e}", generated_file.display()));

    // Generate route_manifest.json into OUT_DIR for debugging and inspection.
    let manifest_file = Path::new(&out_dir).join("route_manifest.json");
    let manifest = generate_manifest(&exports, &middleware_exports, &not_found_exports);
    fs::write(&manifest_file, manifest)
        .unwrap_or_else(|e| panic!("failed to write {}: {e}", manifest_file.display()));
}

/// Generate a JSON route manifest listing all registered routes, middleware,
/// and the not-found handler. The manifest is intended for debugging and
/// tooling — it is not consumed by the Rust build.
fn generate_manifest(
    exports: &[MethodExport],
    middleware_exports: &[MiddlewareExport],
    not_found_exports: &[NotFoundExport],
) -> String {
    let mut json = String::from("{\n  \"routes\": [\n");

    for (i, export) in exports.iter().enumerate() {
        // Extract parameter names from the route path (segments starting with ':')
        let params: Vec<&str> = export
            .route_path
            .split('/')
            .filter(|s| s.starts_with(':'))
            .map(|s| &s[1..])
            .collect();

        // Extract the method name from the variant string (e.g. "Method::GET" → "GET")
        let method = export
            .method_variant
            .strip_prefix("Method::")
            .unwrap_or(&export.method_variant);

        json.push_str("    {\n");
        json.push_str(&format!(
            "      \"path\": \"{}\",\n",
            escape_json(&export.route_path)
        ));
        json.push_str(&format!(
            "      \"handler\": \"{}\",\n",
            escape_json(&export.handler_path)
        ));
        json.push_str(&format!("      \"method\": \"{method}\",\n"));

        json.push_str("      \"params\": [");
        for (j, param) in params.iter().enumerate() {
            json.push_str(&format!("\"{}\"", escape_json(param)));
            if j + 1 < params.len() {
                json.push_str(", ");
            }
        }
        json.push(']');

        json.push_str("\n    }");
        if i + 1 < exports.len() {
            json.push(',');
        }
        json.push('\n');
    }

    json.push_str("  ],\n  \"middleware\": [\n");

    for (i, mw) in middleware_exports.iter().enumerate() {
        json.push_str("    {\n");
        json.push_str(&format!(
            "      \"prefix\": \"{}\",\n",
            escape_json(&mw.prefix)
        ));
        json.push_str(&format!(
            "      \"handler\": \"{}\"\n",
            escape_json(&mw.handler_path)
        ));
        json.push_str("    }");
        if i + 1 < middleware_exports.len() {
            json.push(',');
        }
        json.push('\n');
    }

    json.push_str("  ],\n  \"not_found\": ");
    if let Some(nf) = not_found_exports.first() {
        json.push_str(&format!("\"{}\"", escape_json(&nf.handler_path)));
    } else {
        json.push_str("null");
    }
    json.push_str("\n}\n");

    json
}

/// Escape a string for JSON output (handles backslash and double-quote).
fn escape_json(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// A dynamic parameter accumulated from parent directories.
///
/// Tracks both the original camelCase name (for route path matching) and the
/// snake_case field name (for the generated `Params` struct).
struct AccumulatedParam {
    /// The original parameter name as it appears in the route path (e.g. "postId").
    route_name: String,
    /// The snake_case field name for the Params struct (e.g. "post_id").
    field_name: String,
}

fn process_directory(
    dir: &Path,
    prefix: String,
    exports: &mut Vec<MethodExport>,
    middleware_exports: &mut Vec<MiddlewareExport>,
    not_found_exports: &mut Vec<NotFoundExport>,
    accumulated_params: &[AccumulatedParam],
) {
    // Detect ambiguous routes, conflicting param segments, and unreachable
    // post-wildcard routes.
    {
        let mut file_stems: Vec<String> = Vec::new();
        let mut dir_names: Vec<String> = Vec::new();
        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                let name = path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or_default()
                    .to_string();
                if path.is_dir() {
                    dir_names.push(name);
                } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                        if stem != "mod" && stem != "index" {
                            file_stems.push(stem.to_string());
                        }
                    }
                }
            }
        }
        for stem in &file_stems {
            if dir_names.contains(stem) {
                panic!(
                    "Ambiguous route: both '{stem}.rs' and '{stem}/index.rs' exist in '{}'. \
                     Use one form or the other, not both.",
                    dir.display()
                );
            }
        }

        // Warn on conflicting param directories at the same level.
        // Two `_`-prefixed directories as siblings produce ambiguous routing
        // because only one param child is allowed per trie node.
        let param_dirs: Vec<&String> = dir_names.iter().filter(|n| n.starts_with('_')).collect();
        if param_dirs.len() > 1 {
            println!(
                "cargo:warning=Conflicting param directories in '{}': {} \
                 — only one dynamic parameter directory is allowed per level. \
                 The first one encountered will win at runtime.",
                dir.display(),
                param_dirs
                    .iter()
                    .map(|d| format!("'{d}/'"))
                    .collect::<Vec<_>>()
                    .join(", "),
            );
        }

        // Warn on unreachable post-wildcard routes.
        // `all.rs` maps to a wildcard `/*` which consumes all remaining
        // segments, making sibling route files and subdirectories unreachable.
        let has_wildcard = file_stems.iter().any(|s| s == "all");
        if has_wildcard {
            let other_routes: Vec<&String> = file_stems
                .iter()
                .filter(|s| *s != "all" && !RESERVED_FILES.contains(&s.as_str()))
                .collect();
            if !other_routes.is_empty() || !dir_names.is_empty() {
                println!(
                    "cargo:warning=Unreachable routes in '{}': \
                     'all.rs' (wildcard /*) will consume all remaining segments, \
                     making sibling routes and subdirectories unreachable.",
                    dir.display(),
                );
            }
        }
    }

    let mut children = vec![];

    for entry in fs::read_dir(dir)
        .unwrap_or_else(|e| panic!("failed to read directory {}: {e}", dir.display()))
    {
        let entry =
            entry.unwrap_or_else(|e| panic!("failed to read entry in {}: {e}", dir.display()));
        let path = entry.path();

        if path.is_dir() {
            let name = path
                .file_name()
                .unwrap_or_else(|| panic!("directory has no file name: {}", path.display()))
                .to_str()
                .unwrap_or_else(|| panic!("non-UTF-8 directory name: {}", path.display()));
            let next_prefix = if prefix.is_empty() {
                format!("/{name}")
            } else {
                format!("{prefix}/{name}")
            };
            fs::create_dir_all(&path)
                .unwrap_or_else(|e| panic!("failed to create directory {}: {e}", path.display()));
            // If this directory is a dynamic param (starts with `_`), accumulate
            // it for Params struct generation in child directories.
            let mut child_params: Vec<AccumulatedParam> = accumulated_params
                .iter()
                .map(|p| AccumulatedParam {
                    route_name: p.route_name.clone(),
                    field_name: p.field_name.clone(),
                })
                .collect();
            if let Some(param_name) = name.strip_prefix('_') {
                child_params.push(AccumulatedParam {
                    route_name: param_name.to_string(),
                    field_name: camel_to_snake(param_name),
                });
            }
            process_directory(
                &path,
                next_prefix,
                exports,
                middleware_exports,
                not_found_exports,
                &child_params,
            );
            let mod_name = sanitize_mod(name);
            if mod_name.starts_with('_') {
                children.push(format!("#[allow(non_snake_case)]\npub mod {mod_name};\n"));
            } else {
                children.push(format!("pub mod {mod_name};\n"));
            }
        } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
            let stem = path
                .file_stem()
                .unwrap_or_else(|| panic!("file has no stem: {}", path.display()))
                .to_str()
                .unwrap_or_else(|| panic!("non-UTF-8 file name: {}", path.display()));
            if stem == "mod" {
                continue;
            }

            // Reserved files are never registered as route handlers.
            // The RESERVED_FILES constant is the single source of truth.
            if RESERVED_FILES.contains(&stem) {
                match stem {
                    "middleware" => {
                        children.push("pub mod middleware;\n".to_string());
                        // Best-effort signature validation: warn if middleware.rs
                        // doesn't appear to export `pub fn middleware`.
                        if !has_pub_fn(&path, "middleware") {
                            println!(
                                "cargo:warning=middleware.rs in '{}' should export \
                                 `pub fn middleware(...)`. The generated wiring expects \
                                 this export and will fail to compile without it.",
                                dir.display()
                            );
                        }
                        let mw_prefix = if prefix.is_empty() {
                            "/".to_string()
                        } else {
                            prefix_to_route_path(&prefix)
                        };
                        let mw_handler_path = if prefix.is_empty() {
                            "routes::middleware::middleware".to_string()
                        } else {
                            let parts: Vec<String> = prefix
                                .split('/')
                                .filter(|s| !s.is_empty())
                                .map(sanitize_mod)
                                .collect();
                            format!("routes::{}::middleware::middleware", parts.join("::"))
                        };
                        middleware_exports.push(MiddlewareExport {
                            prefix: mw_prefix,
                            handler_path: mw_handler_path,
                        });
                    }
                    "not_found" => {
                        children.push("pub mod not_found;\n".to_string());
                        let methods = detect_method_exports(&path);
                        if methods.is_empty() {
                            panic!(
                                "not_found.rs does not export any recognized HTTP method functions (get, post, put, etc.). \
                                 It must export at least one."
                            );
                        }
                        // Use the `get` export if available, otherwise the first detected method.
                        let (fn_name, _) = methods
                            .iter()
                            .find(|(name, _)| *name == "get")
                            .unwrap_or(&methods[0]);
                        let handler_path = if prefix.is_empty() {
                            format!("routes::not_found::{fn_name}")
                        } else {
                            let parts: Vec<String> = prefix
                                .split('/')
                                .filter(|s| !s.is_empty())
                                .map(sanitize_mod)
                                .collect();
                            format!("routes::{}::not_found::{fn_name}", parts.join("::"))
                        };
                        not_found_exports.push(NotFoundExport { handler_path });
                    }
                    _ => {
                        // Future reserved filenames: skip route registration,
                        // emit a module declaration, and warn.
                        children.push(format!("pub mod {stem};\n"));
                        println!(
                            "cargo:warning=Reserved file '{stem}.rs' in '{}' was skipped — \
                             no handler registered for it.",
                            dir.display()
                        );
                    }
                }
                continue;
            }

            let mod_name = sanitize_mod(stem);
            // Check for a #[route(path = "...")] attribute override.
            // If present, use the attribute value as the route segment instead
            // of the filename-derived segment.
            let route_path = match scan_route_attribute(&path) {
                Some(override_segment) => {
                    // Build route path using the prefix + the override segment
                    let mut parts: Vec<String> = prefix
                        .split('/')
                        .filter(|s| !s.is_empty())
                        .map(name_to_route_segment)
                        .collect();
                    parts.push(override_segment);
                    format!("/{}", parts.join("/"))
                }
                None => file_to_route_path(&prefix, stem),
            };
            let module_path = file_to_handler_path(&prefix, stem);

            // Emit module declaration. When the sanitized module name differs from the
            // filename stem (e.g. `og.png.rs` → mod `og_png`), add a `#[path]` attribute
            // so the compiler can find the source file.
            let path_attr = if mod_name != stem {
                format!("#[path = \"{stem}.rs\"]\n")
            } else {
                String::new()
            };
            if mod_name.starts_with('_') {
                children.push(format!(
                    "{path_attr}#[allow(non_snake_case)]\npub mod {mod_name};\n"
                ));
            } else {
                children.push(format!("{path_attr}pub mod {mod_name};\n"));
            }

            // Scan the file for recognized method exports
            let methods = detect_method_exports(&path);
            if methods.is_empty() {
                panic!(
                    "Route file '{}' does not export any recognized HTTP method functions (get, post, put, patch, delete, head, options). \
                     Each route file must export at least one.",
                    path.display()
                );
            }

            // Build params info for RouteContext wiring.
            let param_mappings: Vec<ParamMapping> = accumulated_params
                .iter()
                .map(|p| ParamMapping {
                    route_name: p.route_name.clone(),
                    field_name: p.field_name.clone(),
                })
                .collect();
            let params_type_path = if param_mappings.is_empty() {
                None
            } else {
                // The Params struct lives in the mod.rs of the directory that
                // contains this file. Build the module path from the prefix.
                let parts: Vec<String> = prefix
                    .split('/')
                    .filter(|s| !s.is_empty())
                    .map(sanitize_mod)
                    .collect();
                if parts.is_empty() {
                    Some("routes::Params".to_string())
                } else {
                    Some(format!("routes::{}::Params", parts.join("::")))
                }
            };

            // Detect typed search params: if the route file defines
            // `pub struct SearchParams`, the generated wiring will
            // deserialize the query string into it via serde_urlencoded.
            let search_params_type_path = if has_search_params(&path) {
                Some(format!("{}::SearchParams", module_path))
            } else {
                None
            };

            // Detect #[route(certification = ...)] attribute for per-route
            // certification configuration.
            let has_cert_attr = scan_certification_attribute(&path);

            for (fn_name, variant) in &methods {
                exports.push(MethodExport {
                    route_path: route_path.clone(),
                    handler_path: format!("{}::{}", module_path, fn_name),
                    method_variant: variant.to_string(),
                    params: param_mappings.clone(),
                    params_type_path: params_type_path.clone(),
                    search_params_type_path: search_params_type_path.clone(),
                    module_path: module_path.clone(),
                    has_certification_attribute: has_cert_attr,
                });
            }
        }
    }

    if !children.is_empty() || !accumulated_params.is_empty() {
        let mut contents = String::new();

        // Generate the Params struct for IDE visibility if this directory has
        // accumulated dynamic parameters. Routes without dynamic segments use `()`.
        if !accumulated_params.is_empty() {
            contents.push_str("/// Typed route parameters for this route segment.\n");
            contents.push_str("///\n");
            contents.push_str("/// Auto-generated by the build script. Do not edit.\n");
            contents.push_str("#[derive(Debug, Clone)]\n");
            contents.push_str("pub struct Params {\n");
            for param in accumulated_params {
                contents.push_str(&format!("    pub {}: String,\n", param.field_name));
            }
            contents.push_str("}\n\n");
        }

        contents.push_str(&children.concat());

        let mod_path = dir.join("mod.rs");
        fs::write(&mod_path, contents)
            .unwrap_or_else(|e| panic!("failed to write {}: {e}", mod_path.display()));
    }
}

/// Scan a Rust source file for all `pub fn` declarations and return their names.
///
/// Uses `syn::parse_file` to walk the AST, so it correctly handles multi-line
/// signatures, generics, and only detects truly `pub` functions. Used as the
/// shared implementation for [`has_pub_fn`] and [`detect_method_exports`].
fn scan_pub_fns(path: &Path) -> Vec<String> {
    let source = fs::read_to_string(path)
        .unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display()));
    let file = match syn::parse_file(&source) {
        Ok(f) => f,
        Err(_) => return vec![], // unparseable file — skip gracefully
    };
    file.items
        .iter()
        .filter_map(|item| {
            if let syn::Item::Fn(func) = item {
                if matches!(func.vis, syn::Visibility::Public(_)) {
                    return Some(func.sig.ident.to_string());
                }
            }
            None
        })
        .collect()
}

/// Best-effort check: does the file contain `pub fn <name>(`?
///
/// Used for signature validation of reserved files (e.g. checking that
/// `middleware.rs` exports `pub fn middleware`). Delegates to [`scan_pub_fns`]
/// and checks if `name` is in the result.
fn has_pub_fn(path: &Path, name: &str) -> bool {
    scan_pub_fns(path).iter().any(|n| n == name)
}

/// Scan a Rust source file for `pub fn <method_name>` declarations matching
/// recognized HTTP methods. Returns a list of `(fn_name, Method_variant)` pairs.
///
/// Delegates to [`scan_pub_fns`] and filters against [`METHOD_NAMES`].
fn detect_method_exports(path: &Path) -> Vec<(&'static str, &'static str)> {
    let pub_fns = scan_pub_fns(path);
    METHOD_NAMES
        .iter()
        .filter(|(fn_name, _)| pub_fns.iter().any(|n| n == fn_name))
        .copied()
        .collect()
}

/// Scan a Rust source file for a `#[route(path = "...")]` attribute and return
/// the override path segment if present.
///
/// Parses the file with `syn` and walks top-level function items looking
/// for `#[route(...)]` attributes containing `path = "..."`. Handles
/// multi-line attributes correctly.
///
/// Returns `Some("ogimage.png")` if found, `None` otherwise.
/// Check if a `syn::Attribute` path matches `route` or `ic_asset_router::route`.
fn is_route_attribute(attr: &syn::Attribute) -> bool {
    attr.path().is_ident("route") || {
        let segments: Vec<_> = attr.path().segments.iter().collect();
        segments.len() == 2
            && segments[0].ident == "ic_asset_router"
            && segments[1].ident == "route"
    }
}

fn scan_route_attribute(path: &Path) -> Option<String> {
    let source = fs::read_to_string(path).ok()?;
    let file = syn::parse_file(&source).ok()?;
    for item in &file.items {
        if let syn::Item::Fn(func) = item {
            for attr in &func.attrs {
                if is_route_attribute(attr) {
                    let list = attr.meta.require_list().ok()?;
                    // Parse attribute arguments as comma-separated Meta items.
                    let nested: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> = list
                        .parse_args_with(syn::punctuated::Punctuated::parse_terminated)
                        .ok()?;
                    for meta in &nested {
                        if let syn::Meta::NameValue(nv) = meta {
                            if nv.path.is_ident("path") {
                                if let syn::Expr::Lit(syn::ExprLit {
                                    lit: syn::Lit::Str(lit_str),
                                    ..
                                }) = &nv.value
                                {
                                    return Some(lit_str.value());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Scan a Rust source file for a `#[route(...)]` attribute that contains a
/// `certification` key.
///
/// Parses the file with `syn` and walks top-level function items looking
/// for `#[route(...)]` attributes. Returns `true` if any such attribute
/// contains a `certification` key. Handles multi-line attributes correctly.
fn scan_certification_attribute(path: &Path) -> bool {
    let source = fs::read_to_string(path).unwrap_or_default();
    let file = match syn::parse_file(&source) {
        Ok(f) => f,
        Err(_) => return false,
    };
    for item in &file.items {
        if let syn::Item::Fn(func) = item {
            for attr in &func.attrs {
                if is_route_attribute(attr) {
                    let list = match attr.meta.require_list() {
                        Ok(l) => l,
                        Err(_) => continue,
                    };
                    let nested: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> =
                        match list.parse_args_with(syn::punctuated::Punctuated::parse_terminated) {
                            Ok(n) => n,
                            Err(_) => continue,
                        };
                    for meta in &nested {
                        if let syn::Meta::NameValue(nv) = meta {
                            if nv.path.is_ident("certification") {
                                return true;
                            }
                        }
                    }
                }
            }
        }
    }
    false
}

/// Scan a Rust source file for a `pub struct SearchParams` declaration.
///
/// Parses the file with `syn` and walks top-level items looking for a
/// `pub struct SearchParams` declaration. Handles any formatting and
/// ignores private structs or structs in comments/string literals.
fn has_search_params(path: &Path) -> bool {
    let source = fs::read_to_string(path).unwrap_or_default();
    let file = match syn::parse_file(&source) {
        Ok(f) => f,
        Err(_) => return false,
    };
    for item in &file.items {
        if let syn::Item::Struct(s) = item {
            if s.ident == "SearchParams" && matches!(s.vis, syn::Visibility::Public(_)) {
                return true;
            }
        }
    }
    false
}

/// Convert a camelCase identifier to snake_case.
///
/// Examples:
/// - `"postId"` → `"post_id"`
/// - `"userId"` → `"user_id"`
/// - `"id"` → `"id"`
/// - `"HTMLParser"` → `"html_parser"`
fn camel_to_snake(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 4);
    let chars: Vec<char> = s.chars().collect();
    for (i, &c) in chars.iter().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                let prev_upper = chars[i - 1].is_uppercase();
                let next_lower = chars.get(i + 1).is_some_and(|nc| nc.is_lowercase());
                // Insert underscore before this uppercase letter if:
                // - previous char was lowercase (camelCase boundary), OR
                // - previous char was uppercase AND next char is lowercase
                //   (end of acronym like "HTMLParser" → insert before 'P')
                if !prev_upper || next_lower {
                    result.push('_');
                }
            }
            result.push(c.to_lowercase().next().unwrap());
        } else {
            result.push(c);
        }
    }
    result
}

/// Sanitize a filesystem name into a valid Rust module identifier.
///
/// Dots are replaced with underscores so that dotted filenames like `og.png.rs`
/// produce valid module names (`og_png`). When the sanitized name differs from
/// the original, the caller emits a `#[path = "..."]` attribute.
fn sanitize_mod(name: &str) -> String {
    name.replace('.', "_")
}

/// Convert a raw filesystem prefix (e.g. `/_postId/edit`) to a route prefix
/// (e.g. `/:postId/edit`). Each segment is mapped through `name_to_route_segment`.
fn prefix_to_route_path(prefix: &str) -> String {
    let parts: Vec<String> = prefix
        .split('/')
        .filter(|s| !s.is_empty())
        .map(name_to_route_segment)
        .collect();
    if parts.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", parts.join("/"))
    }
}

/// Convert a filesystem name (file stem or directory name) to its route segment.
///
/// - `index` → `""` (maps to the parent directory path)
/// - `all` → `*` (catch-all wildcard)
/// - `_param` → `:param` (dynamic segment)
/// - anything else → literal segment
fn name_to_route_segment(name: &str) -> String {
    if name == "index" {
        String::new()
    } else if name == "all" {
        "*".to_string()
    } else if let Some(param) = name.strip_prefix('_') {
        format!(":{param}")
    } else {
        name.to_string()
    }
}

fn file_to_route_path(prefix: &str, name: &str) -> String {
    let mut parts: Vec<String> = prefix
        .split('/')
        .filter(|s| !s.is_empty())
        .map(name_to_route_segment)
        .collect();

    let segment = name_to_route_segment(name);
    if !segment.is_empty() {
        parts.push(segment);
    }

    if parts.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", parts.join("/"))
    }
}

fn file_to_handler_path(prefix: &str, name: &str) -> String {
    let mut parts: Vec<String> = prefix
        .split('/')
        .filter(|s| !s.is_empty())
        .map(sanitize_mod)
        .collect();
    parts.push(sanitize_mod(name));
    format!("routes::{}", parts.join("::"))
}

// Test coverage audit (Session 7, Spec 5.5):
//
// Previously covered:
//   - camel_to_snake: simple, single word, user_id, multi-word, already snake, acronym, leading upper
//   - name_to_route_segment: index→"", all→"*", _param→":param", static→literal
//   - file_to_route_path: index at root, param directory, nested param directory
//   - has_search_params: detects pub struct, absent, ignores private struct
//
// Gaps filled in this session:
//   - scan_route_attribute: valid attribute, missing attribute, whitespace variations
//   - detect_method_exports: single method, multiple methods, no methods, near-miss names
//   - has_pub_fn: present, absent, near-miss names
//   - sanitize_mod: plain name, dotted name, underscore-prefixed
//   - prefix_to_route_path: root, single segment, param segment, nested
//   - file_to_handler_path: root, nested, param directory
//   - escape_json: plain, backslash, double-quote
//   - file_to_route_path: all→wildcard, static name
//   - RESERVED_FILES recognition
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn camel_to_snake_simple() {
        assert_eq!(camel_to_snake("postId"), "post_id");
    }

    #[test]
    fn camel_to_snake_single_word() {
        assert_eq!(camel_to_snake("id"), "id");
    }

    #[test]
    fn camel_to_snake_user_id() {
        assert_eq!(camel_to_snake("userId"), "user_id");
    }

    #[test]
    fn camel_to_snake_multi_word() {
        assert_eq!(camel_to_snake("myLongParamName"), "my_long_param_name");
    }

    #[test]
    fn camel_to_snake_already_snake() {
        assert_eq!(camel_to_snake("post_id"), "post_id");
    }

    #[test]
    fn camel_to_snake_acronym() {
        assert_eq!(camel_to_snake("HTMLParser"), "html_parser");
    }

    #[test]
    fn camel_to_snake_leading_upper() {
        assert_eq!(camel_to_snake("PostId"), "post_id");
    }

    #[test]
    fn name_to_route_segment_index() {
        assert_eq!(name_to_route_segment("index"), "");
    }

    #[test]
    fn name_to_route_segment_all() {
        assert_eq!(name_to_route_segment("all"), "*");
    }

    #[test]
    fn name_to_route_segment_param() {
        assert_eq!(name_to_route_segment("_postId"), ":postId");
    }

    #[test]
    fn name_to_route_segment_static() {
        assert_eq!(name_to_route_segment("about"), "about");
    }

    #[test]
    fn file_to_route_path_index() {
        assert_eq!(file_to_route_path("", "index"), "/");
    }

    #[test]
    fn file_to_route_path_param_dir() {
        assert_eq!(file_to_route_path("/_postId", "edit"), "/:postId/edit");
    }

    #[test]
    fn file_to_route_path_nested() {
        assert_eq!(
            file_to_route_path("/posts/_postId", "index"),
            "/posts/:postId"
        );
    }

    // --- has_search_params tests ---

    fn write_temp_file(name: &str, content: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join("ic_asset_router_test");
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join(name);
        fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn has_search_params_detects_struct() {
        let path = write_temp_file(
            "sp_detect.rs",
            r#"
use serde::Deserialize;

#[derive(Deserialize, Default)]
pub struct SearchParams {
    pub page: Option<u32>,
}
"#,
        );
        assert!(has_search_params(&path));
    }

    #[test]
    fn has_search_params_returns_false_when_absent() {
        let path = write_temp_file(
            "sp_absent.rs",
            r#"
pub fn get() -> String {
    "hello".to_string()
}
"#,
        );
        assert!(!has_search_params(&path));
    }

    #[test]
    fn has_search_params_ignores_private_struct() {
        let path = write_temp_file(
            "sp_private.rs",
            r#"
struct SearchParams {
    page: Option<u32>,
}
"#,
        );
        assert!(!has_search_params(&path));
    }

    // --- scan_route_attribute tests ---

    #[test]
    fn scan_route_attribute_basic() {
        let path = write_temp_file(
            "scan_basic.rs",
            r#"
#[route(path = "ogimage.png")]
pub fn get() -> String { todo!() }
"#,
        );
        assert_eq!(scan_route_attribute(&path), Some("ogimage.png".to_string()));
    }

    #[test]
    fn scan_route_attribute_with_spaces() {
        let path = write_temp_file(
            "scan_spaces.rs",
            r#"
#[route( path = "custom-name" )]
pub fn get() -> String { todo!() }
"#,
        );
        assert_eq!(scan_route_attribute(&path), Some("custom-name".to_string()));
    }

    #[test]
    fn scan_route_attribute_missing() {
        let path = write_temp_file(
            "scan_missing.rs",
            r#"
pub fn get() -> String { todo!() }
"#,
        );
        assert_eq!(scan_route_attribute(&path), None);
    }

    #[test]
    fn scan_route_attribute_non_route_attribute() {
        let path = write_temp_file(
            "scan_non_route.rs",
            r#"
#[derive(Debug)]
pub fn get() -> String { todo!() }
"#,
        );
        assert_eq!(scan_route_attribute(&path), None);
    }

    #[test]
    fn scan_route_attribute_no_false_match_on_xpath() {
        // `xpath` and `mypath` should NOT be matched as `path`
        let path = write_temp_file(
            "scan_xpath.rs",
            r#"
#[route(xpath = "ogimage.png")]
pub fn get() -> String { todo!() }
"#,
        );
        assert_eq!(scan_route_attribute(&path), None);
    }

    #[test]
    fn scan_route_attribute_no_false_match_on_mypath() {
        let path = write_temp_file(
            "scan_mypath.rs",
            r#"
#[route(mypath = "ogimage.png")]
pub fn get() -> String { todo!() }
"#,
        );
        assert_eq!(scan_route_attribute(&path), None);
    }

    // --- detect_method_exports tests ---

    #[test]
    fn detect_method_exports_single_get() {
        let path = write_temp_file(
            "detect_get.rs",
            r#"
pub fn get(ctx: RouteContext<()>) -> HttpResponse<'static> { todo!() }
"#,
        );
        let methods = detect_method_exports(&path);
        assert_eq!(methods.len(), 1);
        assert_eq!(methods[0].0, "get");
        assert_eq!(methods[0].1, "Method::GET");
    }

    #[test]
    fn detect_method_exports_multiple() {
        let path = write_temp_file(
            "detect_multi.rs",
            r#"
pub fn get(ctx: RouteContext<()>) -> HttpResponse<'static> { todo!() }
pub fn post(ctx: RouteContext<()>) -> HttpResponse<'static> { todo!() }
pub fn delete(ctx: RouteContext<()>) -> HttpResponse<'static> { todo!() }
"#,
        );
        let methods = detect_method_exports(&path);
        assert_eq!(methods.len(), 3);
        let names: Vec<&str> = methods.iter().map(|(n, _)| *n).collect();
        assert!(names.contains(&"get"));
        assert!(names.contains(&"post"));
        assert!(names.contains(&"delete"));
    }

    #[test]
    fn detect_method_exports_none() {
        let path = write_temp_file(
            "detect_none.rs",
            r#"
pub fn helper() -> String { todo!() }
"#,
        );
        let methods = detect_method_exports(&path);
        assert!(methods.is_empty());
    }

    #[test]
    fn detect_method_exports_no_false_match() {
        // `get_user` should not match `get`
        let path = write_temp_file(
            "detect_near_miss.rs",
            r#"
pub fn get_user(id: u64) -> String { todo!() }
"#,
        );
        let methods = detect_method_exports(&path);
        assert!(methods.is_empty());
    }

    #[test]
    fn detect_method_exports_private_fn_ignored() {
        // `fn get` without `pub` should not match
        let path = write_temp_file(
            "detect_private.rs",
            r#"
fn get(ctx: RouteContext<()>) -> HttpResponse<'static> { todo!() }
"#,
        );
        let methods = detect_method_exports(&path);
        assert!(methods.is_empty());
    }

    // --- has_pub_fn tests ---

    #[test]
    fn has_pub_fn_present() {
        let path = write_temp_file(
            "hpf_present.rs",
            r#"
pub fn middleware(req: HttpRequest, params: &RouteParams, next: &dyn Fn()) -> HttpResponse<'static> {
    todo!()
}
"#,
        );
        assert!(has_pub_fn(&path, "middleware"));
    }

    #[test]
    fn has_pub_fn_absent() {
        let path = write_temp_file(
            "hpf_absent.rs",
            r#"
pub fn handler() -> String { todo!() }
"#,
        );
        assert!(!has_pub_fn(&path, "middleware"));
    }

    #[test]
    fn has_pub_fn_near_miss() {
        // `pub fn middleware_v2` should not match `middleware`
        let path = write_temp_file(
            "hpf_near_miss.rs",
            r#"
pub fn middleware_v2(req: HttpRequest) -> HttpResponse<'static> { todo!() }
"#,
        );
        assert!(!has_pub_fn(&path, "middleware"));
    }

    // --- scan_pub_fns tests ---

    #[test]
    fn scan_pub_fns_ignores_private_functions() {
        let path = write_temp_file(
            "spf_private.rs",
            r#"
fn get() -> () { todo!() }
pub fn post() -> () { todo!() }
"#,
        );
        let fns = scan_pub_fns(&path);
        assert_eq!(fns, vec!["post"]);
    }

    #[test]
    fn scan_pub_fns_handles_multiline_signature() {
        let path = write_temp_file(
            "spf_multiline.rs",
            r#"
pub fn get(
    ctx: RouteContext<()>,
) -> HttpResponse<'static> {
    todo!()
}
"#,
        );
        let fns = scan_pub_fns(&path);
        assert_eq!(fns, vec!["get"]);
    }

    #[test]
    fn scan_pub_fns_handles_generics() {
        let path = write_temp_file(
            "spf_generics.rs",
            r#"
pub fn get<T: Default>(x: T) -> T { x }
"#,
        );
        let fns = scan_pub_fns(&path);
        assert_eq!(fns, vec!["get"]);
    }

    // --- sanitize_mod tests ---

    #[test]
    fn sanitize_mod_plain() {
        assert_eq!(sanitize_mod("about"), "about");
    }

    #[test]
    fn sanitize_mod_dot_replacement() {
        assert_eq!(sanitize_mod("file.name"), "file_name");
    }

    #[test]
    fn sanitize_mod_underscore_prefixed() {
        assert_eq!(sanitize_mod("_postId"), "_postId");
    }

    // --- prefix_to_route_path tests ---

    #[test]
    fn prefix_to_route_path_empty() {
        assert_eq!(prefix_to_route_path(""), "/");
    }

    #[test]
    fn prefix_to_route_path_single() {
        assert_eq!(prefix_to_route_path("/api"), "/api");
    }

    #[test]
    fn prefix_to_route_path_param() {
        assert_eq!(prefix_to_route_path("/_postId"), "/:postId");
    }

    #[test]
    fn prefix_to_route_path_nested() {
        assert_eq!(
            prefix_to_route_path("/api/_userId/posts"),
            "/api/:userId/posts"
        );
    }

    // --- file_to_handler_path tests ---

    #[test]
    fn file_to_handler_path_root() {
        assert_eq!(file_to_handler_path("", "index"), "routes::index");
    }

    #[test]
    fn file_to_handler_path_nested() {
        assert_eq!(
            file_to_handler_path("/api/users", "index"),
            "routes::api::users::index"
        );
    }

    #[test]
    fn file_to_handler_path_param_dir() {
        assert_eq!(
            file_to_handler_path("/_postId", "edit"),
            "routes::_postId::edit"
        );
    }

    // --- file_to_route_path additional tests ---

    #[test]
    fn file_to_route_path_all_wildcard() {
        assert_eq!(file_to_route_path("/files", "all"), "/files/*");
    }

    #[test]
    fn file_to_route_path_static_name() {
        assert_eq!(file_to_route_path("", "about"), "/about");
    }

    #[test]
    fn file_to_route_path_deeply_nested() {
        assert_eq!(
            file_to_route_path("/api/v2/_userId/posts", "index"),
            "/api/v2/:userId/posts"
        );
    }

    // --- escape_json tests ---

    #[test]
    fn escape_json_plain() {
        assert_eq!(escape_json("hello world"), "hello world");
    }

    #[test]
    fn escape_json_backslash() {
        assert_eq!(escape_json("a\\b"), "a\\\\b");
    }

    #[test]
    fn escape_json_quote() {
        assert_eq!(escape_json(r#"say "hi""#), r#"say \"hi\""#);
    }

    // --- RESERVED_FILES tests ---

    #[test]
    fn reserved_files_contains_middleware() {
        assert!(RESERVED_FILES.contains(&"middleware"));
    }

    #[test]
    fn reserved_files_contains_not_found() {
        assert!(RESERVED_FILES.contains(&"not_found"));
    }

    #[test]
    fn reserved_files_does_not_contain_index() {
        assert!(!RESERVED_FILES.contains(&"index"));
    }

    #[test]
    fn reserved_files_does_not_contain_all() {
        assert!(!RESERVED_FILES.contains(&"all"));
    }

    // --- process_directory integration tests (using temp dirs) ---

    /// RAII guard for a temporary route directory. Cleans up the directory
    /// tree on drop so tests do not leak temp files.
    struct TempRouteDir {
        path: std::path::PathBuf,
    }

    impl TempRouteDir {
        fn path(&self) -> &Path {
            &self.path
        }
    }

    impl Drop for TempRouteDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.path);
        }
    }

    /// Helper: create a temp directory tree and return a guard that cleans up on drop.
    fn setup_temp_routes(structure: &[(&str, &str)]) -> TempRouteDir {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let id = COUNTER.fetch_add(1, Ordering::Relaxed);
        let base = std::env::temp_dir()
            .join("ic_asset_router_test")
            .join(format!("routes_{id}"));
        if base.exists() {
            fs::remove_dir_all(&base).unwrap();
        }
        fs::create_dir_all(&base).unwrap();
        for (path, content) in structure {
            let full = base.join(path);
            if let Some(parent) = full.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(&full, content).unwrap();
        }
        TempRouteDir { path: base }
    }

    #[test]
    fn process_directory_basic_index() {
        let dir = setup_temp_routes(&[("index.rs", "pub fn get() -> () { todo!() }")]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert_eq!(exports.len(), 1);
        assert_eq!(exports[0].route_path, "/");
        assert_eq!(exports[0].method_variant, "Method::GET");
    }

    #[test]
    fn process_directory_static_route() {
        let dir = setup_temp_routes(&[("about.rs", "pub fn get() -> () { todo!() }")]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert_eq!(exports.len(), 1);
        assert_eq!(exports[0].route_path, "/about");
    }

    #[test]
    fn process_directory_param_directory() {
        let dir = setup_temp_routes(&[("_postId/index.rs", "pub fn get() -> () { todo!() }")]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert_eq!(exports.len(), 1);
        assert_eq!(exports[0].route_path, "/:postId");
        assert!(exports[0].params_type_path.is_some());
    }

    #[test]
    fn process_directory_wildcard_all() {
        let dir = setup_temp_routes(&[("all.rs", "pub fn get() -> () { todo!() }")]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert_eq!(exports.len(), 1);
        assert_eq!(exports[0].route_path, "/*");
    }

    #[test]
    fn process_directory_middleware_detected() {
        let dir = setup_temp_routes(&[(
            "middleware.rs",
            "pub fn middleware(req: R, params: &P, next: &dyn Fn()) -> R { todo!() }",
        )]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        // middleware.rs should NOT be registered as a route
        assert!(exports.is_empty());
        // But it should be registered as middleware
        assert_eq!(mw.len(), 1);
        assert_eq!(mw[0].prefix, "/");
    }

    #[test]
    fn process_directory_not_found_detected() {
        let dir = setup_temp_routes(&[("not_found.rs", "pub fn get() -> () { todo!() }")]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        // not_found.rs should NOT be registered as a route
        assert!(exports.is_empty());
        // But it should be registered as not-found handler
        assert_eq!(nf.len(), 1);
    }

    #[test]
    fn process_directory_nested_structure() {
        let dir = setup_temp_routes(&[
            ("index.rs", "pub fn get() -> () { todo!() }"),
            ("about.rs", "pub fn get() -> () { todo!() }"),
            ("posts/_postId/index.rs", "pub fn get() -> () { todo!() }"),
            (
                "posts/_postId/edit.rs",
                "pub fn get() -> () { todo!() }\npub fn post() -> () { todo!() }",
            ),
        ]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );

        let paths: Vec<&str> = exports.iter().map(|e| e.route_path.as_str()).collect();
        assert!(paths.contains(&"/"));
        assert!(paths.contains(&"/about"));
        assert!(paths.contains(&"/posts/:postId"));
        assert!(paths.contains(&"/posts/:postId/edit"));

        // edit.rs should produce both GET and POST
        let edit_methods: Vec<&str> = exports
            .iter()
            .filter(|e| e.route_path == "/posts/:postId/edit")
            .map(|e| e.method_variant.as_str())
            .collect();
        assert!(edit_methods.contains(&"Method::GET"));
        assert!(edit_methods.contains(&"Method::POST"));
    }

    #[test]
    fn process_directory_route_attribute_override() {
        let dir = setup_temp_routes(&[(
            "og_image.rs",
            "#[route(path = \"ogimage.png\")]\npub fn get() -> () { todo!() }",
        )]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert_eq!(exports.len(), 1);
        assert_eq!(exports[0].route_path, "/ogimage.png");
    }

    #[test]
    #[should_panic(expected = "Ambiguous route")]
    fn process_directory_ambiguous_route_panics() {
        let dir = setup_temp_routes(&[
            ("_param.rs", "pub fn get() -> () { todo!() }"),
            ("_param/index.rs", "pub fn get() -> () { todo!() }"),
        ]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
    }

    #[test]
    #[should_panic(expected = "does not export any recognized HTTP method")]
    fn process_directory_route_without_methods_panics() {
        let dir = setup_temp_routes(&[("broken.rs", "pub fn helper() -> String { todo!() }")]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
    }

    #[test]
    fn process_directory_empty_dir() {
        let dir = setup_temp_routes(&[]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert!(exports.is_empty());
        assert!(mw.is_empty());
        assert!(nf.is_empty());
    }

    #[test]
    fn process_directory_search_params_detected() {
        let dir = setup_temp_routes(&[(
            "search.rs",
            r#"
use serde::Deserialize;
#[derive(Deserialize, Default)]
pub struct SearchParams {
    pub q: Option<String>,
}
pub fn get() -> () { todo!() }
"#,
        )]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert_eq!(exports.len(), 1);
        assert!(exports[0].search_params_type_path.is_some());
    }

    // --- scan_certification_attribute tests ---

    #[test]
    fn scan_certification_attribute_skip() {
        let path = write_temp_file(
            "cert_skip.rs",
            r#"
#[route(certification = "skip")]
pub fn get() -> () { todo!() }
"#,
        );
        assert!(scan_certification_attribute(&path));
    }

    #[test]
    fn scan_certification_attribute_response_only() {
        let path = write_temp_file(
            "cert_ro.rs",
            r#"
#[route(certification = "response_only")]
pub fn get() -> () { todo!() }
"#,
        );
        assert!(scan_certification_attribute(&path));
    }

    #[test]
    fn scan_certification_attribute_authenticated() {
        let path = write_temp_file(
            "cert_auth.rs",
            r#"
#[route(certification = "authenticated")]
pub fn get() -> () { todo!() }
"#,
        );
        assert!(scan_certification_attribute(&path));
    }

    #[test]
    fn scan_certification_attribute_custom() {
        let path = write_temp_file(
            "cert_custom.rs",
            r#"
#[route(certification = custom(request_headers = ["authorization"]))]
pub fn get() -> () { todo!() }
"#,
        );
        assert!(scan_certification_attribute(&path));
    }

    #[test]
    fn scan_certification_attribute_absent() {
        let path = write_temp_file(
            "cert_absent.rs",
            r#"
pub fn get() -> () { todo!() }
"#,
        );
        assert!(!scan_certification_attribute(&path));
    }

    #[test]
    fn scan_certification_attribute_path_only() {
        let path = write_temp_file(
            "cert_path_only.rs",
            r#"
#[route(path = "ogimage.png")]
pub fn get() -> () { todo!() }
"#,
        );
        // Has #[route(...)] but no certification key
        assert!(!scan_certification_attribute(&path));
    }

    #[test]
    fn scan_certification_attribute_multiline() {
        let path = write_temp_file(
            "cert_multiline.rs",
            r#"
#[route(
    certification = custom(
        request_headers = ["authorization"],
        query_params = ["page", "limit"]
    )
)]
pub fn get() -> () { todo!() }
"#,
        );
        assert!(scan_certification_attribute(&path));
    }

    #[test]
    fn scan_certification_attribute_fully_qualified_path() {
        let path = write_temp_file(
            "cert_fq.rs",
            r#"
#[ic_asset_router::route(certification = "skip")]
pub fn get() -> () { todo!() }
"#,
        );
        assert!(scan_certification_attribute(&path));
    }

    #[test]
    fn scan_certification_in_comment_ignored() {
        let path = write_temp_file(
            "cert_comment.rs",
            r#"
// #[route(certification = "skip")]
pub fn get() -> () { todo!() }
"#,
        );
        assert!(!scan_certification_attribute(&path));
    }

    #[test]
    fn has_search_params_multiline_struct() {
        let path = write_temp_file(
            "sp_multiline.rs",
            r#"
use serde::Deserialize;

#[derive(Deserialize, Default)]
pub struct SearchParams
{
    pub page: Option<u32>,
    pub limit: Option<u32>,
}
"#,
        );
        assert!(has_search_params(&path));
    }

    #[test]
    fn scan_route_attribute_multiline() {
        let path = write_temp_file(
            "scan_multiline.rs",
            r#"
#[route(
    path = "ogimage.png",
    certification = "skip"
)]
pub fn get() -> () { todo!() }
"#,
        );
        assert_eq!(scan_route_attribute(&path), Some("ogimage.png".to_string()));
    }

    // --- process_directory certification detection tests ---

    #[test]
    fn process_directory_detects_certification_attribute() {
        let dir = setup_temp_routes(&[(
            "api.rs",
            "#[route(certification = \"skip\")]\npub fn get() -> () { todo!() }",
        )]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert_eq!(exports.len(), 1);
        assert!(exports[0].has_certification_attribute);
    }

    #[test]
    fn process_directory_no_certification_attribute() {
        let dir = setup_temp_routes(&[("about.rs", "pub fn get() -> () { todo!() }")]);
        let mut exports = Vec::new();
        let mut mw = Vec::new();
        let mut nf = Vec::new();
        process_directory(
            dir.path(),
            String::new(),
            &mut exports,
            &mut mw,
            &mut nf,
            &[],
        );
        assert_eq!(exports.len(), 1);
        assert!(!exports[0].has_certification_attribute);
    }

    // --- 8.5.6: Generated code includes url_decode for params and wildcard ---

    /// Verify that the generated wrapper code for param routes includes
    /// `url_decode` calls for each param field. This test exercises the
    /// code generation format string by simulating the output for a
    /// param route.
    #[test]
    fn generated_param_code_includes_url_decode() {
        let pm = ParamMapping {
            route_name: "postId".to_string(),
            field_name: "post_id".to_string(),
        };
        // This is the exact format string used in generate_routes_from.
        let line = format!(
            "            {}: ic_asset_router::url_decode(&raw_params.get(\"{}\").cloned().unwrap_or_default()).into_owned(),\n",
            pm.field_name, pm.route_name,
        );
        assert!(
            line.contains("ic_asset_router::url_decode"),
            "generated param field line must include url_decode: {line}"
        );
        assert!(
            line.contains("into_owned()"),
            "generated param field line must convert Cow to owned String: {line}"
        );
    }

    /// Verify that the generated wildcard field includes `url_decode`.
    #[test]
    fn generated_wildcard_code_includes_url_decode() {
        // This is the exact string pushed for the wildcard field.
        let line = "        wildcard: raw_params.get(\"*\").map(|w| ic_asset_router::url_decode(w).into_owned()),\n";
        assert!(
            line.contains("ic_asset_router::url_decode"),
            "generated wildcard line must include url_decode: {line}"
        );
    }
}