rustapi-macros 0.1.450

Procedural macros for RustAPI. Includes #[get], #[post], #[derive(Schema)], and #[derive(Validate)] for compile-time magic.
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
//!
//! This crate provides the attribute macros used in RustAPI:
//!
//! - `#[rustapi::main]` - Main entry point macro
//! - `#[rustapi::get("/path")]` - GET route handler
//! - `#[rustapi::post("/path")]` - POST route handler
//! - `#[rustapi::put("/path")]` - PUT route handler
//! - `#[rustapi::patch("/path")]` - PATCH route handler
//! - `#[rustapi::delete("/path")]` - DELETE route handler
//! - `#[derive(Validate)]` - Validation derive macro
//!
//! ## Debugging
//!
//! Set `RUSTAPI_DEBUG=1` environment variable during compilation to see
//! expanded macro output for debugging purposes.

use proc_macro::TokenStream;
use proc_macro_crate::{crate_name, FoundCrate};
use quote::quote;
use std::collections::HashSet;
use syn::{
    parse_macro_input, Attribute, Data, DeriveInput, Expr, Fields, FnArg, GenericArgument, ItemFn,
    Lit, LitStr, Meta, PathArguments, ReturnType, Type,
};

mod api_error;
mod derive_schema;

/// Determine the path to the RustAPI facade crate (`rustapi-rs`).
///
/// This supports dependency renaming, for example:
/// `api = { package = "rustapi-rs", version = "..." }`.
fn get_rustapi_path() -> proc_macro2::TokenStream {
    let rustapi_rs_found = crate_name("rustapi-rs").or_else(|_| crate_name("rustapi_rs"));

    if let Ok(found) = rustapi_rs_found {
        match found {
            // `FoundCrate::Itself` can occur for examples/benches inside the rustapi-rs package.
            // Use an absolute crate path so generated code also works in those targets.
            FoundCrate::Itself => quote! { ::rustapi_rs },
            FoundCrate::Name(name) => {
                let normalized = name.replace('-', "_");
                let ident = syn::Ident::new(&normalized, proc_macro2::Span::call_site());
                quote! { ::#ident }
            }
        }
    } else {
        quote! { ::rustapi_rs }
    }
}

/// Derive macro for OpenAPI Schema trait
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Schema)]
/// struct User {
///     id: i64,
///     name: String,
/// }
/// ```
#[proc_macro_derive(Schema, attributes(schema))]
pub fn derive_schema(input: TokenStream) -> TokenStream {
    derive_schema::expand_derive_schema(parse_macro_input!(input as DeriveInput)).into()
}

/// Auto-register a schema type for zero-config OpenAPI.
///
/// Attach this to a `struct` or `enum` that also derives `Schema`.
/// This ensures the type is registered into RustAPI's OpenAPI components even if it is
/// only referenced indirectly (e.g. as a nested field type).
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// #[rustapi_rs::schema]
/// #[derive(Serialize, Schema)]
/// struct UserInfo { /* ... */ }
/// ```
#[proc_macro_attribute]
pub fn schema(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as syn::Item);
    let rustapi_path = get_rustapi_path();

    let (ident, generics) = match &input {
        syn::Item::Struct(s) => (&s.ident, &s.generics),
        syn::Item::Enum(e) => (&e.ident, &e.generics),
        _ => {
            return syn::Error::new_spanned(
                &input,
                "#[rustapi_rs::schema] can only be used on structs or enums",
            )
            .to_compile_error()
            .into();
        }
    };

    if !generics.params.is_empty() {
        return syn::Error::new_spanned(
            generics,
            "#[rustapi_rs::schema] does not support generic types",
        )
        .to_compile_error()
        .into();
    }

    let registrar_ident = syn::Ident::new(
        &format!("__RUSTAPI_AUTO_SCHEMA_{}", ident),
        proc_macro2::Span::call_site(),
    );

    let expanded = quote! {
        #input

        #[allow(non_upper_case_globals)]
        #[#rustapi_path::__private::linkme::distributed_slice(#rustapi_path::__private::AUTO_SCHEMAS)]
        #[linkme(crate = #rustapi_path::__private::linkme)]
        static #registrar_ident: fn(&mut #rustapi_path::__private::openapi::OpenApiSpec) =
            |spec: &mut #rustapi_path::__private::openapi::OpenApiSpec| {
                spec.register_in_place::<#ident>();
            };
    };

    debug_output("schema", &expanded);
    expanded.into()
}

fn extract_schema_types(ty: &Type, out: &mut Vec<Type>, allow_leaf: bool) {
    match ty {
        Type::Reference(r) => extract_schema_types(&r.elem, out, allow_leaf),
        Type::Path(tp) => {
            let Some(seg) = tp.path.segments.last() else {
                return;
            };

            let ident = seg.ident.to_string();

            let unwrap_first_generic = |out: &mut Vec<Type>| {
                if let PathArguments::AngleBracketed(args) = &seg.arguments {
                    if let Some(GenericArgument::Type(inner)) = args.args.first() {
                        extract_schema_types(inner, out, true);
                    }
                }
            };

            match ident.as_str() {
                // Request/response wrappers
                "Json" | "ValidatedJson" | "Created" => {
                    unwrap_first_generic(out);
                }
                // WithStatus<T, CODE>
                "WithStatus" => {
                    if let PathArguments::AngleBracketed(args) = &seg.arguments {
                        if let Some(GenericArgument::Type(inner)) = args.args.first() {
                            extract_schema_types(inner, out, true);
                        }
                    }
                }
                // Common combinators
                "Option" | "Result" => {
                    if let PathArguments::AngleBracketed(args) = &seg.arguments {
                        if let Some(GenericArgument::Type(inner)) = args.args.first() {
                            extract_schema_types(inner, out, allow_leaf);
                        }
                    }
                }
                _ => {
                    if allow_leaf {
                        out.push(ty.clone());
                    }
                }
            }
        }
        _ => {}
    }
}

fn collect_handler_schema_types(input: &ItemFn) -> Vec<Type> {
    let mut found: Vec<Type> = Vec::new();

    for arg in &input.sig.inputs {
        if let FnArg::Typed(pat_ty) = arg {
            extract_schema_types(&pat_ty.ty, &mut found, false);
        }
    }

    if let ReturnType::Type(_, ty) = &input.sig.output {
        extract_schema_types(ty, &mut found, false);
    }

    // Dedup by token string.
    let mut seen = HashSet::<String>::new();
    found
        .into_iter()
        .filter(|t| seen.insert(quote!(#t).to_string()))
        .collect()
}

/// Collect path parameters and their inferred types from function arguments
///
/// Returns a list of (name, schema_type) tuples.
fn collect_path_params(input: &ItemFn) -> Vec<(String, String)> {
    let mut params = Vec::new();

    for arg in &input.sig.inputs {
        if let FnArg::Typed(pat_ty) = arg {
            // Check if the argument is a Path extractor
            if let Type::Path(tp) = &*pat_ty.ty {
                if let Some(seg) = tp.path.segments.last() {
                    if seg.ident == "Path" {
                        // Extract the inner type T from Path<T>
                        if let PathArguments::AngleBracketed(args) = &seg.arguments {
                            if let Some(GenericArgument::Type(inner_ty)) = args.args.first() {
                                // Map inner type to schema string
                                if let Some(schema_type) = map_type_to_schema(inner_ty) {
                                    // Extract the parameter name
                                    // We handle the pattern `Path(name)` or `name: Path<T>`
                                    // For `Path(id): Path<Uuid>`, the variable binding is inside the tuple struct pattern?
                                    // No, wait. `Path(id): Path<Uuid>` is NOT valid Rust syntax for function arguments!
                                    // Extractor destructuring uses `Path(id)` as the PATTERN.
                                    // e.g. `fn handler(Path(id): Path<Uuid>)`

                                    if let Some(name) = extract_param_name(&pat_ty.pat) {
                                        params.push((name, schema_type));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    params
}

/// Extract parameter name from pattern
///
/// Handles `Path(id)` -> "id"
/// Handles `id` -> "id" (if simple binding)
fn extract_param_name(pat: &syn::Pat) -> Option<String> {
    match pat {
        syn::Pat::Ident(ident) => Some(ident.ident.to_string()),
        syn::Pat::TupleStruct(ts) => {
            // Handle Path(id) destructuring
            // We assume the first field is the parameter we want if it's a simple identifier
            if let Some(first) = ts.elems.first() {
                extract_param_name(first)
            } else {
                None
            }
        }
        _ => None, // Complex patterns not supported for auto-detection yet
    }
}

/// Map Rust type to OpenAPI schema type string
fn map_type_to_schema(ty: &Type) -> Option<String> {
    match ty {
        Type::Path(tp) => {
            if let Some(seg) = tp.path.segments.last() {
                let ident = seg.ident.to_string();
                match ident.as_str() {
                    "Uuid" => Some("uuid".to_string()),
                    "String" | "str" => Some("string".to_string()),
                    "bool" => Some("boolean".to_string()),
                    "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64"
                    | "usize" => Some("integer".to_string()),
                    "f32" | "f64" => Some("number".to_string()),
                    _ => None,
                }
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Check if RUSTAPI_DEBUG is enabled at compile time
fn is_debug_enabled() -> bool {
    std::env::var("RUSTAPI_DEBUG")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false)
}

/// Print debug output if RUSTAPI_DEBUG=1 is set
fn debug_output(name: &str, tokens: &proc_macro2::TokenStream) {
    if is_debug_enabled() {
        eprintln!("\n=== RUSTAPI_DEBUG: {} ===", name);
        eprintln!("{}", tokens);
        eprintln!("=== END {} ===\n", name);
    }
}

/// Validate route path syntax at compile time
///
/// Returns Ok(()) if the path is valid, or Err with a descriptive error message.
fn validate_path_syntax(path: &str, span: proc_macro2::Span) -> Result<(), syn::Error> {
    // Path must start with /
    if !path.starts_with('/') {
        return Err(syn::Error::new(
            span,
            format!("route path must start with '/', got: \"{}\"", path),
        ));
    }

    // Check for empty path segments (double slashes)
    if path.contains("//") {
        return Err(syn::Error::new(
            span,
            format!(
                "route path contains empty segment (double slash): \"{}\"",
                path
            ),
        ));
    }

    // Validate path parameter syntax
    let mut brace_depth = 0;
    let mut param_start = None;

    for (i, ch) in path.char_indices() {
        match ch {
            '{' => {
                if brace_depth > 0 {
                    return Err(syn::Error::new(
                        span,
                        format!(
                            "nested braces are not allowed in route path at position {}: \"{}\"",
                            i, path
                        ),
                    ));
                }
                brace_depth += 1;
                param_start = Some(i);
            }
            '}' => {
                if brace_depth == 0 {
                    return Err(syn::Error::new(
                        span,
                        format!(
                            "unmatched closing brace '}}' at position {} in route path: \"{}\"",
                            i, path
                        ),
                    ));
                }
                brace_depth -= 1;

                // Check that parameter name is not empty
                if let Some(start) = param_start {
                    let param_name = &path[start + 1..i];
                    if param_name.is_empty() {
                        return Err(syn::Error::new(
                            span,
                            format!(
                                "empty parameter name '{{}}' at position {} in route path: \"{}\"",
                                start, path
                            ),
                        ));
                    }
                    // Validate parameter name contains only valid identifier characters
                    if !param_name.chars().all(|c| c.is_alphanumeric() || c == '_') {
                        return Err(syn::Error::new(
                            span,
                            format!(
                                "invalid parameter name '{{{}}}' at position {} - parameter names must contain only alphanumeric characters and underscores: \"{}\"",
                                param_name, start, path
                            ),
                        ));
                    }
                    // Parameter name must not start with a digit
                    if param_name
                        .chars()
                        .next()
                        .map(|c| c.is_ascii_digit())
                        .unwrap_or(false)
                    {
                        return Err(syn::Error::new(
                            span,
                            format!(
                                "parameter name '{{{}}}' cannot start with a digit at position {}: \"{}\"",
                                param_name, start, path
                            ),
                        ));
                    }
                }
                param_start = None;
            }
            // Check for invalid characters in path (outside of parameters)
            _ if brace_depth == 0 => {
                // Allow alphanumeric, -, _, ., /, and common URL characters
                if !ch.is_alphanumeric() && !"-_./*".contains(ch) {
                    return Err(syn::Error::new(
                        span,
                        format!(
                            "invalid character '{}' at position {} in route path: \"{}\"",
                            ch, i, path
                        ),
                    ));
                }
            }
            _ => {}
        }
    }

    // Check for unclosed braces
    if brace_depth > 0 {
        return Err(syn::Error::new(
            span,
            format!(
                "unclosed brace '{{' in route path (missing closing '}}'): \"{}\"",
                path
            ),
        ));
    }

    Ok(())
}

/// Main entry point macro for RustAPI applications
///
/// This macro wraps your async main function with the tokio runtime.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// #[rustapi::main]
/// async fn main() -> Result<()> {
///     RustApi::new()
///         .mount(hello)
///         .run("127.0.0.1:8080")
///         .await
/// }
/// ```
#[proc_macro_attribute]
pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);

    let attrs = &input.attrs;
    let vis = &input.vis;
    let sig = &input.sig;
    let block = &input.block;

    let expanded = quote! {
        #(#attrs)*
        #[::tokio::main]
        #vis #sig {
            #block
        }
    };

    debug_output("main", &expanded);

    TokenStream::from(expanded)
}

/// Check if a type is a body-consuming extractor (Json, Body, ValidatedJson, etc.)
///
/// Body-consuming extractors implement `FromRequest` (not `FromRequestParts`)
/// and consume the request body. They MUST be the last parameter in a handler
/// function because the body can only be read once.
fn is_body_consuming_type(ty: &Type) -> bool {
    match ty {
        Type::Path(tp) => {
            if let Some(seg) = tp.path.segments.last() {
                matches!(
                    seg.ident.to_string().as_str(),
                    "Json" | "Body" | "ValidatedJson" | "AsyncValidatedJson" | "Multipart"
                )
            } else {
                false
            }
        }
        _ => false,
    }
}

/// Validate that body-consuming extractors are the last parameter(s) in a handler.
///
/// This prevents a common runtime error where the request body is consumed
/// before a later extractor tries to read it. By checking at compile time,
/// we give developers a clear error message instead of a confusing runtime failure.
fn validate_extractor_order(input: &ItemFn) -> Result<(), syn::Error> {
    let params: Vec<_> = input
        .sig
        .inputs
        .iter()
        .filter_map(|arg| {
            if let FnArg::Typed(pat_ty) = arg {
                Some(pat_ty)
            } else {
                None
            }
        })
        .collect();

    if params.is_empty() {
        return Ok(());
    }

    // Find all body-consuming parameter indices
    let body_indices: Vec<usize> = params
        .iter()
        .enumerate()
        .filter(|(_, p)| is_body_consuming_type(&p.ty))
        .map(|(i, _)| i)
        .collect();

    if body_indices.is_empty() {
        return Ok(());
    }

    // Find the last non-body parameter index
    let last_non_body = params
        .iter()
        .enumerate()
        .filter(|(_, p)| !is_body_consuming_type(&p.ty))
        .map(|(i, _)| i)
        .max();

    // If there are non-body params after any body param, that's an error
    if let Some(last_non_body_idx) = last_non_body {
        let first_body_idx = body_indices[0];
        if first_body_idx < last_non_body_idx {
            let offending_param = &params[first_body_idx];
            let ty_name = quote!(#offending_param).to_string();
            return Err(syn::Error::new_spanned(
                &offending_param.ty,
                format!(
                    "Body-consuming extractor must be the LAST parameter.\n\
                     \n\
                     Found `{}` before non-body extractor(s).\n\
                     \n\
                     Body extractors (Json, Body, ValidatedJson, AsyncValidatedJson, Multipart) \
                     consume the request body, which can only be read once. Place them after all \
                     non-body extractors (State, Path, Query, Headers, etc.).\n\
                     \n\
                     Example:\n\
                     \x20 async fn handler(\n\
                     \x20     State(db): State<AppState>,   // non-body: OK first\n\
                     \x20     Path(id): Path<i64>,          // non-body: OK second\n\
                     \x20     Json(body): Json<CreateUser>,  // body: MUST be last\n\
                     \x20 ) -> Result<Json<User>> {{ ... }}",
                    ty_name,
                ),
            ));
        }
    }

    // Also check for multiple body-consuming extractors (only one allowed)
    if body_indices.len() > 1 {
        let second_body_param = &params[body_indices[1]];
        return Err(syn::Error::new_spanned(
            &second_body_param.ty,
            "Multiple body-consuming extractors detected.\n\
             \n\
             Only ONE body-consuming extractor (Json, Body, ValidatedJson, AsyncValidatedJson, \
             Multipart) is allowed per handler, because the request body can only be consumed once.\n\
             \n\
             Remove the extra body extractor or combine the data into a single type.",
        ));
    }

    Ok(())
}

/// Internal helper to generate route handler macros
fn generate_route_handler(method: &str, attr: TokenStream, item: TokenStream) -> TokenStream {
    let path = parse_macro_input!(attr as LitStr);
    let input = parse_macro_input!(item as ItemFn);
    let rustapi_path = get_rustapi_path();

    let fn_name = &input.sig.ident;
    let fn_vis = &input.vis;
    let fn_attrs = &input.attrs;
    let fn_async = &input.sig.asyncness;
    let fn_inputs = &input.sig.inputs;
    let fn_output = &input.sig.output;
    let fn_block = &input.block;
    let fn_generics = &input.sig.generics;

    let schema_types = collect_handler_schema_types(&input);

    let path_value = path.value();

    // Validate path syntax at compile time
    if let Err(err) = validate_path_syntax(&path_value, path.span()) {
        return err.to_compile_error().into();
    }

    // Validate extractor ordering at compile time
    if let Err(err) = validate_extractor_order(&input) {
        return err.to_compile_error().into();
    }

    // Generate a companion module with route info
    let route_fn_name = syn::Ident::new(&format!("{}_route", fn_name), fn_name.span());
    // Generate unique name for auto-registration static
    let auto_route_name = syn::Ident::new(&format!("__AUTO_ROUTE_{}", fn_name), fn_name.span());

    // Generate unique names for schema registration
    let schema_reg_fn_name =
        syn::Ident::new(&format!("__{}_register_schemas", fn_name), fn_name.span());
    let auto_schema_name = syn::Ident::new(&format!("__AUTO_SCHEMA_{}", fn_name), fn_name.span());

    // Pick the right route helper function based on method
    let route_helper = match method {
        "GET" => quote!(#rustapi_path::get_route),
        "POST" => quote!(#rustapi_path::post_route),
        "PUT" => quote!(#rustapi_path::put_route),
        "PATCH" => quote!(#rustapi_path::patch_route),
        "DELETE" => quote!(#rustapi_path::delete_route),
        _ => quote!(#rustapi_path::get_route),
    };

    // Auto-detect path parameters from function arguments
    let auto_params = collect_path_params(&input);

    // Extract metadata from attributes to chain builder methods
    let mut chained_calls = quote!();

    // Add auto-detected parameters first (can be overridden by attributes)
    for (name, schema) in auto_params {
        chained_calls = quote! { #chained_calls .param(#name, #schema) };
    }

    for attr in fn_attrs {
        // Check for tag, summary, description, param
        // Use loose matching on the last segment to handle crate renaming or fully qualified paths
        if let Some(ident) = attr.path().segments.last().map(|s| &s.ident) {
            let ident_str = ident.to_string();
            if ident_str == "tag" {
                if let Ok(lit) = attr.parse_args::<LitStr>() {
                    let val = lit.value();
                    chained_calls = quote! { #chained_calls .tag(#val) };
                }
            } else if ident_str == "summary" {
                if let Ok(lit) = attr.parse_args::<LitStr>() {
                    let val = lit.value();
                    chained_calls = quote! { #chained_calls .summary(#val) };
                }
            } else if ident_str == "description" {
                if let Ok(lit) = attr.parse_args::<LitStr>() {
                    let val = lit.value();
                    chained_calls = quote! { #chained_calls .description(#val) };
                }
            } else if ident_str == "param" {
                // Parse #[param(name, schema = "type")] or #[param(name = "type")]
                if let Ok(param_args) = attr.parse_args_with(
                    syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated,
                ) {
                    let mut param_name: Option<String> = None;
                    let mut param_schema: Option<String> = None;

                    for meta in param_args {
                        match &meta {
                            // Simple ident: #[param(id, ...)]
                            Meta::Path(path) => {
                                if param_name.is_none() {
                                    if let Some(ident) = path.get_ident() {
                                        param_name = Some(ident.to_string());
                                    }
                                }
                            }
                            // Named value: #[param(schema = "uuid")] or #[param(id = "uuid")]
                            Meta::NameValue(nv) => {
                                let key = nv.path.get_ident().map(|i| i.to_string());
                                if let Some(key) = key {
                                    if key == "schema" || key == "type" {
                                        if let Expr::Lit(lit) = &nv.value {
                                            if let Lit::Str(s) = &lit.lit {
                                                param_schema = Some(s.value());
                                            }
                                        }
                                    } else if param_name.is_none() {
                                        // Treat as #[param(name = "schema")]
                                        param_name = Some(key);
                                        if let Expr::Lit(lit) = &nv.value {
                                            if let Lit::Str(s) = &lit.lit {
                                                param_schema = Some(s.value());
                                            }
                                        }
                                    }
                                }
                            }
                            _ => {}
                        }
                    }

                    if let (Some(pname), Some(pschema)) = (param_name, param_schema) {
                        chained_calls = quote! { #chained_calls .param(#pname, #pschema) };
                    }
                }
            } else if ident_str == "errors" {
                // Parse #[errors(404 = "Not Found", 403 = "Forbidden")]
                if let Ok(error_args) = attr.parse_args_with(
                    syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated,
                ) {
                    for meta in error_args {
                        if let Meta::NameValue(nv) = &meta {
                            // The path is the status code (e.g., 404)
                            // We need to parse it as an integer from the ident
                            let status_str = nv.path.get_ident().map(|i| i.to_string());
                            if let Some(status_key) = status_str {
                                // Status code may be a name like `not_found` or number-prefixed
                                if let Expr::Lit(lit) = &nv.value {
                                    if let Lit::Str(s) = &lit.lit {
                                        let desc = s.value();
                                        chained_calls = quote! {
                                            #chained_calls .error_response(#status_key, #desc)
                                        };
                                    }
                                }
                            }
                        } else if let Meta::List(list) = &meta {
                            // Handle #[errors(404(description = "Not Found"))]
                            // For now, skip complex forms
                            let _ = list;
                        }
                    }
                }
                // Also try parsing as direct key-value with integer keys:
                // #[errors(404 = "Not Found")] - integers can't be Meta idents
                // So we parse the raw token stream manually
                if let Ok(ts) = attr.parse_args::<proc_macro2::TokenStream>() {
                    let tokens: Vec<proc_macro2::TokenTree> = ts.into_iter().collect();
                    let mut i = 0;
                    while i < tokens.len() {
                        // Look for pattern: INTEGER = "string" [,]
                        if let proc_macro2::TokenTree::Literal(lit) = &tokens[i] {
                            let lit_str = lit.to_string();
                            if let Ok(status_code) = lit_str.parse::<u16>() {
                                // Next should be '='
                                if i + 2 < tokens.len() {
                                    if let proc_macro2::TokenTree::Punct(p) = &tokens[i + 1] {
                                        if p.as_char() == '=' {
                                            if let proc_macro2::TokenTree::Literal(desc_lit) =
                                                &tokens[i + 2]
                                            {
                                                let desc_str = desc_lit.to_string();
                                                // Remove surrounding quotes
                                                let desc = desc_str.trim_matches('"').to_string();
                                                chained_calls = quote! {
                                                    #chained_calls .error_response(#status_code, #desc)
                                                };
                                                i += 3;
                                                // Skip comma
                                                if i < tokens.len() {
                                                    if let proc_macro2::TokenTree::Punct(p) =
                                                        &tokens[i]
                                                    {
                                                        if p.as_char() == ',' {
                                                            i += 1;
                                                        }
                                                    }
                                                }
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        i += 1;
                    }
                }
            }
        }
    }

    let expanded = quote! {
        // The original handler function
        #(#fn_attrs)*
        #fn_vis #fn_async fn #fn_name #fn_generics (#fn_inputs) #fn_output #fn_block

        // Route info function - creates a Route for this handler
        #[doc(hidden)]
        #fn_vis fn #route_fn_name() -> #rustapi_path::Route {
            #route_helper(#path_value, #fn_name)
                #chained_calls
        }

        // Auto-register route with linkme
        #[doc(hidden)]
        #[allow(non_upper_case_globals)]
        #[#rustapi_path::__private::linkme::distributed_slice(#rustapi_path::__private::AUTO_ROUTES)]
        #[linkme(crate = #rustapi_path::__private::linkme)]
        static #auto_route_name: fn() -> #rustapi_path::Route = #route_fn_name;

        // Auto-register referenced schemas with linkme (best-effort)
        #[doc(hidden)]
        #[allow(non_snake_case)]
        fn #schema_reg_fn_name(spec: &mut #rustapi_path::__private::openapi::OpenApiSpec) {
            #( spec.register_in_place::<#schema_types>(); )*
        }

        #[doc(hidden)]
        #[allow(non_upper_case_globals)]
        #[#rustapi_path::__private::linkme::distributed_slice(#rustapi_path::__private::AUTO_SCHEMAS)]
        #[linkme(crate = #rustapi_path::__private::linkme)]
        static #auto_schema_name: fn(&mut #rustapi_path::__private::openapi::OpenApiSpec) = #schema_reg_fn_name;
    };

    debug_output(&format!("{} {}", method, path_value), &expanded);

    TokenStream::from(expanded)
}

/// GET route handler macro
///
/// # Example
///
/// ```rust,ignore
/// #[rustapi::get("/users")]
/// async fn list_users() -> Json<Vec<User>> {
///     Json(vec![])
/// }
///
/// #[rustapi::get("/users/{id}")]
/// async fn get_user(Path(id): Path<i64>) -> Result<User> {
///     Ok(User { id, name: "John".into() })
/// }
/// ```
#[proc_macro_attribute]
pub fn get(attr: TokenStream, item: TokenStream) -> TokenStream {
    generate_route_handler("GET", attr, item)
}

/// POST route handler macro
#[proc_macro_attribute]
pub fn post(attr: TokenStream, item: TokenStream) -> TokenStream {
    generate_route_handler("POST", attr, item)
}

/// PUT route handler macro
#[proc_macro_attribute]
pub fn put(attr: TokenStream, item: TokenStream) -> TokenStream {
    generate_route_handler("PUT", attr, item)
}

/// PATCH route handler macro
#[proc_macro_attribute]
pub fn patch(attr: TokenStream, item: TokenStream) -> TokenStream {
    generate_route_handler("PATCH", attr, item)
}

/// DELETE route handler macro
#[proc_macro_attribute]
pub fn delete(attr: TokenStream, item: TokenStream) -> TokenStream {
    generate_route_handler("DELETE", attr, item)
}

// ============================================
// Route Metadata Macros
// ============================================

/// Tag macro for grouping endpoints in OpenAPI documentation
///
/// # Example
///
/// ```rust,ignore
/// #[rustapi::get("/users")]
/// #[rustapi::tag("Users")]
/// async fn list_users() -> Json<Vec<User>> {
///     Json(vec![])
/// }
/// ```
#[proc_macro_attribute]
pub fn tag(attr: TokenStream, item: TokenStream) -> TokenStream {
    let tag = parse_macro_input!(attr as LitStr);
    let input = parse_macro_input!(item as ItemFn);

    let attrs = &input.attrs;
    let vis = &input.vis;
    let sig = &input.sig;
    let block = &input.block;
    let tag_value = tag.value();

    // Add a doc comment with the tag info for documentation
    let expanded = quote! {
        #[doc = concat!("**Tag:** ", #tag_value)]
        #(#attrs)*
        #vis #sig #block
    };

    TokenStream::from(expanded)
}

/// Summary macro for endpoint summary in OpenAPI documentation
///
/// # Example
///
/// ```rust,ignore
/// #[rustapi::get("/users")]
/// #[rustapi::summary("List all users")]
/// async fn list_users() -> Json<Vec<User>> {
///     Json(vec![])
/// }
/// ```
#[proc_macro_attribute]
pub fn summary(attr: TokenStream, item: TokenStream) -> TokenStream {
    let summary = parse_macro_input!(attr as LitStr);
    let input = parse_macro_input!(item as ItemFn);

    let attrs = &input.attrs;
    let vis = &input.vis;
    let sig = &input.sig;
    let block = &input.block;
    let summary_value = summary.value();

    // Add a doc comment with the summary
    let expanded = quote! {
        #[doc = #summary_value]
        #(#attrs)*
        #vis #sig #block
    };

    TokenStream::from(expanded)
}

/// Description macro for detailed endpoint description in OpenAPI documentation
///
/// # Example
///
/// ```rust,ignore
/// #[rustapi::get("/users")]
/// #[rustapi::description("Returns a list of all users in the system. Supports pagination.")]
/// async fn list_users() -> Json<Vec<User>> {
///     Json(vec![])
/// }
/// ```
#[proc_macro_attribute]
pub fn description(attr: TokenStream, item: TokenStream) -> TokenStream {
    let desc = parse_macro_input!(attr as LitStr);
    let input = parse_macro_input!(item as ItemFn);

    let attrs = &input.attrs;
    let vis = &input.vis;
    let sig = &input.sig;
    let block = &input.block;
    let desc_value = desc.value();

    // Add a doc comment with the description
    let expanded = quote! {
        #[doc = ""]
        #[doc = #desc_value]
        #(#attrs)*
        #vis #sig #block
    };

    TokenStream::from(expanded)
}

/// Path parameter schema macro for OpenAPI documentation
///
/// Use this to specify the OpenAPI schema type for a path parameter when
/// the auto-inferred type is incorrect. This is particularly useful for
/// UUID parameters that might be named `id`.
///
/// # Supported schema types
/// - `"uuid"` - String with UUID format
/// - `"integer"` or `"int"` - Integer with int64 format
/// - `"string"` - Plain string
/// - `"boolean"` or `"bool"` - Boolean
/// - `"number"` - Number (float)
///
/// # Example
///
/// ```rust,ignore
/// use uuid::Uuid;
///
/// #[rustapi::get("/users/{id}")]
/// #[rustapi::param(id, schema = "uuid")]
/// async fn get_user(Path(id): Path<Uuid>) -> Json<User> {
///     // ...
/// }
///
/// // Alternative syntax:
/// #[rustapi::get("/posts/{post_id}")]
/// #[rustapi::param(post_id = "uuid")]
/// async fn get_post(Path(post_id): Path<Uuid>) -> Json<Post> {
///     // ...
/// }
/// ```
#[proc_macro_attribute]
pub fn param(_attr: TokenStream, item: TokenStream) -> TokenStream {
    // The param attribute is processed by the route macro (get, post, etc.)
    // This macro just passes through the function unchanged
    item
}

/// Error responses macro for OpenAPI documentation
///
/// Declares possible error responses for a handler endpoint. These are
/// automatically added to the OpenAPI specification.
///
/// # Syntax
///
/// ```rust,ignore
/// #[rustapi::errors(404 = "User not found", 403 = "Access denied", 409 = "Email already exists")]
/// ```
///
/// # Example
///
/// ```rust,ignore
/// #[rustapi::get("/users/{id}")]
/// #[rustapi::errors(404 = "User not found", 403 = "Forbidden")]
/// async fn get_user(Path(id): Path<Uuid>) -> Result<Json<User>> {
///     // ...
/// }
/// ```
///
/// This generates OpenAPI responses for 404 and 403 status codes,
/// each referencing the standard ErrorSchema component.
#[proc_macro_attribute]
pub fn errors(_attr: TokenStream, item: TokenStream) -> TokenStream {
    // The errors attribute is processed by the route macro (get, post, etc.)
    // This macro just passes through the function unchanged
    item
}

// ============================================
// Validation Derive Macro
// ============================================

/// Parsed validation rule from field attributes
#[derive(Debug)]
struct ValidationRuleInfo {
    rule_type: String,
    params: Vec<(String, String)>,
    message: Option<String>,
    groups: Vec<String>,
}

/// Parse validation attributes from a field
fn parse_validate_attrs(attrs: &[Attribute]) -> Vec<ValidationRuleInfo> {
    let mut rules = Vec::new();

    for attr in attrs {
        if !attr.path().is_ident("validate") {
            continue;
        }

        // Parse the validate attribute
        if let Ok(meta) = attr.parse_args::<Meta>() {
            if let Some(rule) = parse_validate_meta(&meta) {
                rules.push(rule);
            }
        } else if let Ok(nested) = attr
            .parse_args_with(syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated)
        {
            for meta in nested {
                if let Some(rule) = parse_validate_meta(&meta) {
                    rules.push(rule);
                }
            }
        }
    }

    rules
}

/// Parse a single validation meta item
fn parse_validate_meta(meta: &Meta) -> Option<ValidationRuleInfo> {
    match meta {
        Meta::Path(path) => {
            // Simple rule like #[validate(email)]
            let ident = path.get_ident()?.to_string();
            Some(ValidationRuleInfo {
                rule_type: ident,
                params: Vec::new(),
                message: None,
                groups: Vec::new(),
            })
        }
        Meta::List(list) => {
            // Rule with params like #[validate(length(min = 3, max = 50))]
            let rule_type = list.path.get_ident()?.to_string();
            let mut params = Vec::new();
            let mut message = None;
            let mut groups = Vec::new();

            // Parse nested params
            if let Ok(nested) = list.parse_args_with(
                syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated,
            ) {
                for nested_meta in nested {
                    if let Meta::NameValue(nv) = &nested_meta {
                        let key = nv.path.get_ident()?.to_string();

                        if key == "groups" {
                            let vec = expr_to_string_vec(&nv.value);
                            groups.extend(vec);
                        } else if let Some(value) = expr_to_string(&nv.value) {
                            if key == "message" {
                                message = Some(value);
                            } else if key == "group" {
                                groups.push(value);
                            } else {
                                params.push((key, value));
                            }
                        }
                    } else if let Meta::Path(path) = &nested_meta {
                        // Handle flags like #[validate(ip(v4))]
                        if let Some(ident) = path.get_ident() {
                            params.push((ident.to_string(), "true".to_string()));
                        }
                    }
                }
            }

            Some(ValidationRuleInfo {
                rule_type,
                params,
                message,
                groups,
            })
        }
        Meta::NameValue(nv) => {
            // Rule like #[validate(regex = "pattern")]
            let rule_type = nv.path.get_ident()?.to_string();
            let value = expr_to_string(&nv.value)?;

            Some(ValidationRuleInfo {
                rule_type: rule_type.clone(),
                params: vec![(rule_type.clone(), value)],
                message: None,
                groups: Vec::new(),
            })
        }
    }
}

/// Convert an expression to a string value
fn expr_to_string(expr: &Expr) -> Option<String> {
    match expr {
        Expr::Lit(lit) => match &lit.lit {
            Lit::Str(s) => Some(s.value()),
            Lit::Int(i) => Some(i.base10_digits().to_string()),
            Lit::Float(f) => Some(f.base10_digits().to_string()),
            Lit::Bool(b) => Some(b.value.to_string()),
            _ => None,
        },
        _ => None,
    }
}

/// Convert an expression to a vector of strings
fn expr_to_string_vec(expr: &Expr) -> Vec<String> {
    match expr {
        Expr::Array(arr) => {
            let mut result = Vec::new();
            for elem in &arr.elems {
                if let Some(s) = expr_to_string(elem) {
                    result.push(s);
                }
            }
            result
        }
        _ => {
            if let Some(s) = expr_to_string(expr) {
                vec![s]
            } else {
                Vec::new()
            }
        }
    }
}

/// Determine the path to rustapi_validate based on the user's dependencies.
///
/// Checks for (in order):
/// 1. `rustapi-rs` → `::rustapi_rs::__private::rustapi_validate`
/// 2. `rustapi-validate` → `::rustapi_validate`
///
/// This allows the Validate derive macro to work in both user projects
/// (which depend on rustapi-rs) and internal crates (which depend on
/// rustapi-validate directly).
fn get_validate_path() -> proc_macro2::TokenStream {
    let rustapi_rs_found = crate_name("rustapi-rs").or_else(|_| crate_name("rustapi_rs"));

    if let Ok(found) = rustapi_rs_found {
        match found {
            FoundCrate::Itself => {
                quote! { ::rustapi_rs::__private::validate }
            }
            FoundCrate::Name(name) => {
                let normalized = name.replace('-', "_");
                let ident = syn::Ident::new(&normalized, proc_macro2::Span::call_site());
                quote! { ::#ident::__private::validate }
            }
        }
    } else if let Ok(found) =
        crate_name("rustapi-validate").or_else(|_| crate_name("rustapi_validate"))
    {
        match found {
            FoundCrate::Itself => quote! { crate },
            FoundCrate::Name(name) => {
                let normalized = name.replace('-', "_");
                let ident = syn::Ident::new(&normalized, proc_macro2::Span::call_site());
                quote! { ::#ident }
            }
        }
    } else {
        // Default fallback
        quote! { ::rustapi_validate }
    }
}

/// Determine the path to rustapi_core based on the user's dependencies.
///
/// Checks for (in order):
/// 1. `rustapi-rs` (which re-exports rustapi-core via glob)
/// 2. `rustapi-core` directly
fn get_core_path() -> proc_macro2::TokenStream {
    let rustapi_rs_found = crate_name("rustapi-rs").or_else(|_| crate_name("rustapi_rs"));

    if let Ok(found) = rustapi_rs_found {
        match found {
            FoundCrate::Itself => quote! { ::rustapi_rs::__private::core },
            FoundCrate::Name(name) => {
                let normalized = name.replace('-', "_");
                let ident = syn::Ident::new(&normalized, proc_macro2::Span::call_site());
                quote! { ::#ident::__private::core }
            }
        }
    } else if let Ok(found) = crate_name("rustapi-core").or_else(|_| crate_name("rustapi_core")) {
        match found {
            FoundCrate::Itself => quote! { crate },
            FoundCrate::Name(name) => {
                let normalized = name.replace('-', "_");
                let ident = syn::Ident::new(&normalized, proc_macro2::Span::call_site());
                quote! { ::#ident }
            }
        }
    } else {
        quote! { ::rustapi_core }
    }
}

/// Determine the path to async_trait based on the user's dependencies.
///
/// Checks for (in order):
/// 1. `rustapi-rs` → `::rustapi_rs::__private::async_trait`
/// 2. `async-trait` directly
fn get_async_trait_path() -> proc_macro2::TokenStream {
    let rustapi_rs_found = crate_name("rustapi-rs").or_else(|_| crate_name("rustapi_rs"));

    if let Ok(found) = rustapi_rs_found {
        match found {
            FoundCrate::Itself => {
                quote! { ::rustapi_rs::__private::async_trait }
            }
            FoundCrate::Name(name) => {
                let normalized = name.replace('-', "_");
                let ident = syn::Ident::new(&normalized, proc_macro2::Span::call_site());
                quote! { ::#ident::__private::async_trait }
            }
        }
    } else if let Ok(found) = crate_name("async-trait").or_else(|_| crate_name("async_trait")) {
        match found {
            FoundCrate::Itself => quote! { crate },
            FoundCrate::Name(name) => {
                let normalized = name.replace('-', "_");
                let ident = syn::Ident::new(&normalized, proc_macro2::Span::call_site());
                quote! { ::#ident }
            }
        }
    } else {
        quote! { ::async_trait }
    }
}

fn generate_rule_validation(
    field_name: &str,
    _field_type: &Type,
    rule: &ValidationRuleInfo,
    validate_path: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let field_ident = syn::Ident::new(field_name, proc_macro2::Span::call_site());
    let field_name_str = field_name;

    // Generate group check
    let group_check = if rule.groups.is_empty() {
        quote! { true }
    } else {
        let group_names = rule.groups.iter().map(|g| g.as_str());
        quote! {
            {
                let rule_groups = [#(#validate_path::v2::ValidationGroup::from(#group_names)),*];
                rule_groups.iter().any(|g| g.matches(&group))
            }
        }
    };

    let validation_logic = match rule.rule_type.as_str() {
        "email" => {
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();
            quote! {
                {
                    let rule = #validate_path::v2::EmailRule::new() #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "length" => {
            let min = rule
                .params
                .iter()
                .find(|(k, _)| k == "min")
                .and_then(|(_, v)| v.parse::<usize>().ok());
            let max = rule
                .params
                .iter()
                .find(|(k, _)| k == "max")
                .and_then(|(_, v)| v.parse::<usize>().ok());
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();

            let rule_creation = match (min, max) {
                (Some(min), Some(max)) => {
                    quote! { #validate_path::v2::LengthRule::new(#min, #max) }
                }
                (Some(min), None) => quote! { #validate_path::v2::LengthRule::min(#min) },
                (None, Some(max)) => quote! { #validate_path::v2::LengthRule::max(#max) },
                (None, None) => quote! { #validate_path::v2::LengthRule::new(0, usize::MAX) },
            };

            quote! {
                {
                    let rule = #rule_creation #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "range" => {
            let min = rule
                .params
                .iter()
                .find(|(k, _)| k == "min")
                .map(|(_, v)| v.clone());
            let max = rule
                .params
                .iter()
                .find(|(k, _)| k == "max")
                .map(|(_, v)| v.clone());
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();

            // Determine the numeric type from the field type
            let rule_creation = match (min, max) {
                (Some(min), Some(max)) => {
                    let min_lit: proc_macro2::TokenStream = min.parse().unwrap();
                    let max_lit: proc_macro2::TokenStream = max.parse().unwrap();
                    quote! { #validate_path::v2::RangeRule::new(#min_lit, #max_lit) }
                }
                (Some(min), None) => {
                    let min_lit: proc_macro2::TokenStream = min.parse().unwrap();
                    quote! { #validate_path::v2::RangeRule::min(#min_lit) }
                }
                (None, Some(max)) => {
                    let max_lit: proc_macro2::TokenStream = max.parse().unwrap();
                    quote! { #validate_path::v2::RangeRule::max(#max_lit) }
                }
                (None, None) => {
                    return quote! {};
                }
            };

            quote! {
                {
                    let rule = #rule_creation #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "regex" => {
            let pattern = rule
                .params
                .iter()
                .find(|(k, _)| k == "regex" || k == "pattern")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();

            quote! {
                {
                    let rule = #validate_path::v2::RegexRule::new(#pattern) #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "url" => {
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();
            quote! {
                {
                    let rule = #validate_path::v2::UrlRule::new() #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "required" => {
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();
            quote! {
                {
                    let rule = #validate_path::v2::RequiredRule::new() #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "credit_card" => {
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();
            quote! {
                {
                    let rule = #validate_path::v2::CreditCardRule::new() #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "ip" => {
            let v4 = rule.params.iter().any(|(k, _)| k == "v4");
            let v6 = rule.params.iter().any(|(k, _)| k == "v6");

            let rule_creation = if v4 && !v6 {
                quote! { #validate_path::v2::IpRule::v4() }
            } else if !v4 && v6 {
                quote! { #validate_path::v2::IpRule::v6() }
            } else {
                quote! { #validate_path::v2::IpRule::new() }
            };

            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();

            quote! {
                {
                    let rule = #rule_creation #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "phone" => {
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();
            quote! {
                {
                    let rule = #validate_path::v2::PhoneRule::new() #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "contains" => {
            let needle = rule
                .params
                .iter()
                .find(|(k, _)| k == "needle")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();

            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();

            quote! {
                {
                    let rule = #validate_path::v2::ContainsRule::new(#needle) #message;
                    if let Err(e) = #validate_path::v2::ValidationRule::validate(&rule, &self.#field_ident) {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        _ => {
            // Unknown rule - skip
            quote! {}
        }
    };

    quote! {
        if #group_check {
            #validation_logic
        }
    }
}

/// Generate async validation code for a single rule
fn generate_async_rule_validation(
    field_name: &str,
    rule: &ValidationRuleInfo,
    validate_path: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let field_ident = syn::Ident::new(field_name, proc_macro2::Span::call_site());
    let field_name_str = field_name;

    // Generate group check
    let group_check = if rule.groups.is_empty() {
        quote! { true }
    } else {
        let group_names = rule.groups.iter().map(|g| g.as_str());
        quote! {
            {
                let rule_groups = [#(#validate_path::v2::ValidationGroup::from(#group_names)),*];
                rule_groups.iter().any(|g| g.matches(&group))
            }
        }
    };

    let validation_logic = match rule.rule_type.as_str() {
        "async_unique" => {
            let table = rule
                .params
                .iter()
                .find(|(k, _)| k == "table")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            let column = rule
                .params
                .iter()
                .find(|(k, _)| k == "column")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();

            quote! {
                {
                    let rule = #validate_path::v2::AsyncUniqueRule::new(#table, #column) #message;
                    if let Err(e) = #validate_path::v2::AsyncValidationRule::validate_async(&rule, &self.#field_ident, ctx).await {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "async_exists" => {
            let table = rule
                .params
                .iter()
                .find(|(k, _)| k == "table")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            let column = rule
                .params
                .iter()
                .find(|(k, _)| k == "column")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();

            quote! {
                {
                    let rule = #validate_path::v2::AsyncExistsRule::new(#table, #column) #message;
                    if let Err(e) = #validate_path::v2::AsyncValidationRule::validate_async(&rule, &self.#field_ident, ctx).await {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "async_api" => {
            let endpoint = rule
                .params
                .iter()
                .find(|(k, _)| k == "endpoint")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            let message = rule
                .message
                .as_ref()
                .map(|m| quote! { .with_message(#m) })
                .unwrap_or_default();

            quote! {
                {
                    let rule = #validate_path::v2::AsyncApiRule::new(#endpoint) #message;
                    if let Err(e) = #validate_path::v2::AsyncValidationRule::validate_async(&rule, &self.#field_ident, ctx).await {
                        errors.add(#field_name_str, e);
                    }
                }
            }
        }
        "custom_async" => {
            // #[validate(custom_async = "function_path")]
            let function_path = rule
                .params
                .iter()
                .find(|(k, _)| k == "custom_async" || k == "function")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();

            if function_path.is_empty() {
                // If path is missing, don't generate invalid code
                quote! {}
            } else {
                let func: syn::Path = syn::parse_str(&function_path).unwrap();
                let message_handling = if let Some(msg) = &rule.message {
                    quote! {
                        let e = #validate_path::v2::RuleError::new("custom_async", #msg);
                        errors.add(#field_name_str, e);
                    }
                } else {
                    quote! {
                        errors.add(#field_name_str, e);
                    }
                };

                quote! {
                    {
                        // Call the custom async function: async fn(&T, &ValidationContext) -> Result<(), RuleError>
                        if let Err(e) = #func(&self.#field_ident, ctx).await {
                            #message_handling
                        }
                    }
                }
            }
        }
        _ => {
            // Not an async rule
            quote! {}
        }
    };

    quote! {
        if #group_check {
            #validation_logic
        }
    }
}

/// Check if a rule is async
fn is_async_rule(rule: &ValidationRuleInfo) -> bool {
    matches!(
        rule.rule_type.as_str(),
        "async_unique" | "async_exists" | "async_api" | "custom_async"
    )
}

/// Derive macro for implementing Validate and AsyncValidate traits
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_macros::Validate;
///
/// #[derive(Validate)]
/// struct CreateUser {
///     #[validate(email, message = "Invalid email format")]
///     email: String,
///     
///     #[validate(length(min = 3, max = 50))]
///     username: String,
///     
///     #[validate(range(min = 18, max = 120))]
///     age: u8,
///     
///     #[validate(async_unique(table = "users", column = "email"))]
///     email: String,
/// }
/// ```
#[proc_macro_derive(Validate, attributes(validate))]
pub fn derive_validate(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let generics = &input.generics;
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    // Only support structs with named fields
    let fields = match &input.data {
        Data::Struct(data) => match &data.fields {
            Fields::Named(fields) => &fields.named,
            _ => {
                return syn::Error::new_spanned(
                    &input,
                    "Validate can only be derived for structs with named fields",
                )
                .to_compile_error()
                .into();
            }
        },
        _ => {
            return syn::Error::new_spanned(&input, "Validate can only be derived for structs")
                .to_compile_error()
                .into();
        }
    };

    // Resolve crate paths dynamically based on the caller's dependencies
    let validate_path = get_validate_path();
    let core_path = get_core_path();
    let async_trait_path = get_async_trait_path();

    // Collect sync and async validation code for each field
    let mut sync_validations = Vec::new();
    let mut async_validations = Vec::new();
    let mut has_async_rules = false;

    for field in fields {
        let field_name = field.ident.as_ref().unwrap().to_string();
        let field_type = &field.ty;
        let rules = parse_validate_attrs(&field.attrs);

        for rule in &rules {
            if is_async_rule(rule) {
                has_async_rules = true;
                let validation = generate_async_rule_validation(&field_name, rule, &validate_path);
                async_validations.push(validation);
            } else {
                let validation =
                    generate_rule_validation(&field_name, field_type, rule, &validate_path);
                sync_validations.push(validation);
            }
        }
    }

    // Generate the Validate impl
    let validate_impl = quote! {
        impl #impl_generics #validate_path::v2::Validate for #name #ty_generics #where_clause {
            fn validate_with_group(&self, group: #validate_path::v2::ValidationGroup) -> Result<(), #validate_path::v2::ValidationErrors> {
                let mut errors = #validate_path::v2::ValidationErrors::new();

                #(#sync_validations)*

                errors.into_result()
            }
        }
    };

    // Generate the AsyncValidate impl if there are async rules
    let async_validate_impl = if has_async_rules {
        quote! {
            #[#async_trait_path::async_trait]
            impl #impl_generics #validate_path::v2::AsyncValidate for #name #ty_generics #where_clause {
                async fn validate_async_with_group(&self, ctx: &#validate_path::v2::ValidationContext, group: #validate_path::v2::ValidationGroup) -> Result<(), #validate_path::v2::ValidationErrors> {
                    let mut errors = #validate_path::v2::ValidationErrors::new();

                    #(#async_validations)*

                    errors.into_result()
                }
            }
        }
    } else {
        // Provide a default AsyncValidate impl that just returns Ok
        quote! {
            #[#async_trait_path::async_trait]
            impl #impl_generics #validate_path::v2::AsyncValidate for #name #ty_generics #where_clause {
                async fn validate_async_with_group(&self, _ctx: &#validate_path::v2::ValidationContext, _group: #validate_path::v2::ValidationGroup) -> Result<(), #validate_path::v2::ValidationErrors> {
                    Ok(())
                }
            }
        }
    };

    // Generate the Validatable impl for rustapi-core integration (exposed via rustapi-rs)
    // Paths are resolved dynamically so this works from both rustapi-rs and internal crates.
    let validatable_impl = quote! {
        impl #impl_generics #core_path::validation::Validatable for #name #ty_generics #where_clause {
            fn do_validate(&self) -> Result<(), #core_path::ApiError> {
                match #validate_path::v2::Validate::validate(self) {
                    Ok(_) => Ok(()),
                    Err(e) => Err(#core_path::validation::convert_v2_errors(e)),
                }
            }
        }
    };

    let expanded = quote! {
        #validate_impl
        #async_validate_impl
        #validatable_impl
    };

    debug_output("Validate derive", &expanded);

    TokenStream::from(expanded)
}

// ============================================
// ApiError Derive Macro
// ============================================

/// Derive macro for implementing IntoResponse for error enums
///
/// # Example
///
/// ```rust,ignore
/// #[derive(ApiError)]
/// enum UserError {
///     #[error(status = 404, message = "User not found")]
///     NotFound(i64),
///     
///     #[error(status = 400, code = "validation_error")]
///     InvalidInput(String),
/// }
/// ```
#[proc_macro_derive(ApiError, attributes(error))]
pub fn derive_api_error(input: TokenStream) -> TokenStream {
    api_error::expand_derive_api_error(input)
}

// ============================================
// TypedPath Derive Macro
// ============================================

/// Derive macro for TypedPath
///
/// # Example
///
/// ```rust,ignore
/// #[derive(TypedPath, Deserialize, Serialize)]
/// #[typed_path("/users/{id}/posts/{post_id}")]
/// struct PostPath {
///     id: u64,
///     post_id: String,
/// }
/// ```
#[proc_macro_derive(TypedPath, attributes(typed_path))]
pub fn derive_typed_path(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let generics = &input.generics;
    let rustapi_path = get_rustapi_path();
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    // Find the #[typed_path("...")] attribute
    let mut path_str = None;
    for attr in &input.attrs {
        if attr.path().is_ident("typed_path") {
            if let Ok(lit) = attr.parse_args::<LitStr>() {
                path_str = Some(lit.value());
            }
        }
    }

    let path = match path_str {
        Some(p) => p,
        None => {
            return syn::Error::new_spanned(
                &input,
                "#[derive(TypedPath)] requires a #[typed_path(\"...\")] attribute",
            )
            .to_compile_error()
            .into();
        }
    };

    // Validate path syntax
    if let Err(err) = validate_path_syntax(&path, proc_macro2::Span::call_site()) {
        return err.to_compile_error().into();
    }

    // Generate to_uri implementation
    // We need to parse the path and replace {param} with self.param
    let mut format_string = String::new();
    let mut format_args = Vec::new();

    let mut chars = path.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '{' {
            let mut param_name = String::new();
            while let Some(&c) = chars.peek() {
                if c == '}' {
                    chars.next(); // Consume '}'
                    break;
                }
                param_name.push(chars.next().unwrap());
            }

            if param_name.is_empty() {
                return syn::Error::new_spanned(
                    &input,
                    "Empty path parameter not allowed in typed_path",
                )
                .to_compile_error()
                .into();
            }

            format_string.push_str("{}");
            let ident = syn::Ident::new(&param_name, proc_macro2::Span::call_site());
            format_args.push(quote! { self.#ident });
        } else {
            format_string.push(ch);
        }
    }

    let expanded = quote! {
        impl #impl_generics #rustapi_path::prelude::TypedPath for #name #ty_generics #where_clause {
            const PATH: &'static str = #path;

            fn to_uri(&self) -> String {
                format!(#format_string, #(#format_args),*)
            }
        }
    };

    debug_output("TypedPath derive", &expanded);
    TokenStream::from(expanded)
}