oas-forge 0.1.4

The zero-runtime OpenAPI 3.1 compiler for Rust. Extracts, links, and merges code-first documentation.
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
use serde_json::{Value, json};
use syn::spanned::Spanned;
use syn::visit::{self, Visit};
use syn::{Attribute, Expr, File, ImplItemFn, ItemEnum, ItemFn, ItemMod, ItemStruct, ItemType};

/// Extracted item type
#[derive(Debug)]
pub enum ExtractedItem {
    /// Standard @openapi body
    Schema {
        name: Option<String>,
        content: String,
        line: usize,
    },
    /// @openapi-fragment Name(args...)
    Fragment {
        name: String,
        params: Vec<String>,
        content: String,
        line: usize,
    },
    /// @openapi<T, U>
    Blueprint {
        name: String,
        params: Vec<String>,
        content: String,
        line: usize,
    },
    // Raw DSL block (for late binding)
    RouteDSL {
        content: String,
        line: usize,
        operation_id: String,
    },
}

#[derive(Default)]
pub struct OpenApiVisitor {
    pub items: Vec<ExtractedItem>,
    pub current_tags: Vec<String>,
}

impl OpenApiVisitor {
    // Process doc attributes on items (structs, fns, types)
    // Updated: No longer accepts generated_content. Strictly for @openapi blocks (Paths/Fragments).
    fn check_attributes(
        &mut self,
        attrs: &[Attribute],
        item_ident: Option<String>,
        item_line: usize,
    ) {
        let doc_lines = crate::doc_parser::extract_doc_comments(attrs);

        let has_openapi = doc_lines.iter().any(|l| l.contains("@openapi"));

        // Safety: Only process if explicit @openapi tag exists
        if !has_openapi {
            return;
        }

        let full_doc = doc_lines.join("\n");
        self.parse_doc_block(&full_doc, item_ident, item_line);
    }

    fn parse_doc_block(&mut self, doc: &str, item_ident: Option<String>, line: usize) {
        let lines: Vec<&str> = doc.lines().collect();
        // Naive unindent
        let min_indent = lines
            .iter()
            .filter(|line| !line.trim().is_empty())
            .map(|line| line.chars().take_while(|c| *c == ' ').count())
            .min()
            .unwrap_or(0);

        let unindented: Vec<String> = lines
            .into_iter()
            .map(|l| {
                if l.len() >= min_indent {
                    l[min_indent..].to_string()
                } else {
                    l.to_string()
                }
            })
            .collect();
        let content = unindented.join("\n");

        let mut sections = Vec::new();
        let mut current_header = String::new();
        let mut current_body = Vec::new();

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("@openapi") {
                if !current_header.is_empty() || !current_body.is_empty() {
                    sections.push((current_header.clone(), current_body.join("\n")));
                }
                current_header = trimmed.to_string();
                current_body.clear();
            } else if trimmed.starts_with('{') && current_header.is_empty() {
                if !current_header.is_empty() || !current_body.is_empty() {
                    sections.push((current_header.clone(), current_body.join("\n")));
                }
                current_header = "@json".to_string();
                current_body.push(line.to_string());
            } else {
                current_body.push(line.to_string());
            }
        }
        if !current_header.is_empty() || !current_body.is_empty() {
            sections.push((current_header, current_body.join("\n")));
        }

        for (header, body) in sections {
            let mut body_content = body.trim().to_string();

            if header.starts_with("@openapi-fragment") {
                let rest = header.strip_prefix("@openapi-fragment").unwrap().trim();
                let (name, params) = if let Some(idx) = rest.find('(') {
                    let name = rest[..idx].trim().to_string();
                    let params_str = rest[idx + 1..].trim_end_matches(')');
                    let params: Vec<String> = params_str
                        .split(',')
                        .map(|p| p.trim().to_string())
                        .filter(|p| !p.is_empty())
                        .collect();
                    (name, params)
                } else {
                    (rest.to_string(), Vec::new())
                };

                self.items.push(ExtractedItem::Fragment {
                    name,
                    params,
                    content: body_content,
                    line,
                });
            } else if header.starts_with("@openapi-type") {
                let name = header
                    .strip_prefix("@openapi-type")
                    .unwrap()
                    .trim()
                    .to_string();
                // Wrap content in schema definition
                let wrapped = wrap_in_schema(&name, &body_content);
                self.items.push(ExtractedItem::Schema {
                    name: Some(name),
                    content: wrapped,
                    line,
                });
            } else if header.starts_with("@openapi") && header.contains('<') {
                if let Some(start) = header.find('<') {
                    if let Some(end) = header.rfind('>') {
                        let params_str = &header[start + 1..end];
                        let params: Vec<String> = params_str
                            .split(',')
                            .map(|p| p.trim().to_string())
                            .filter(|p| !p.is_empty())
                            .collect();

                        if let Some(ident) = &item_ident {
                            self.items.push(ExtractedItem::Blueprint {
                                name: ident.clone(),
                                params,
                                content: body_content,
                                line,
                            });
                        }
                    }
                }
            } else if (header.starts_with("@openapi") && !header.contains('<'))
                || header == "@json"
                || header.is_empty()
            {
                // TAG INJECTION
                if !self.current_tags.is_empty() {
                    let tags_yaml_list = self
                        .current_tags
                        .iter()
                        .map(|t| format!("- {}", t))
                        .collect::<Vec<_>>();

                    let verbs = [
                        "get:", "post:", "put:", "delete:", "patch:", "head:", "options:", "trace:",
                    ];
                    let mut new_lines = Vec::new();
                    let mut injected_any = false;

                    for line in body_content.lines() {
                        new_lines.push(line.to_string());
                        let trimmed = line.trim();
                        if verbs.contains(&trimmed) {
                            let indent = line.chars().take_while(|c| *c == ' ').count();
                            let child_indent = " ".repeat(indent + 2);

                            if !body_content.contains("tags:") {
                                new_lines.push(format!("{}tags:", child_indent));
                                for tag in &tags_yaml_list {
                                    new_lines.push(format!("{}  {}", child_indent, tag));
                                }
                                injected_any = true;
                            }
                        }
                    }

                    if injected_any {
                        body_content = new_lines.join("\n");
                    }
                }

                // Auto-Wrap Heuristic (Only for manual blocks now)
                let starts_with_toplevel = body_content.lines().any(|line| {
                    let trimmed = line.trim();
                    if trimmed.starts_with("#") {
                        return false;
                    }
                    if let Some(key) = trimmed.split(':').next() {
                        matches!(
                            key.trim(),
                            "openapi"
                                | "info"
                                | "paths"
                                | "components"
                                | "tags"
                                | "servers"
                                | "security"
                        )
                    } else {
                        false
                    }
                });

                let final_content = if !starts_with_toplevel && !body_content.trim().is_empty() {
                    if let Some(n) = &item_ident {
                        wrap_in_schema(n, &body_content)
                    } else {
                        body_content
                    }
                } else {
                    body_content
                };

                self.items.push(ExtractedItem::Schema {
                    name: item_ident.clone(),
                    content: final_content,
                    line,
                });
            }
        }
    }
    // Helper to process a single struct field
    fn process_struct_field(
        field: &syn::Field,
        rename_rule: &Option<String>,
    ) -> (String, Value, bool) {
        let default_field_name = field.ident.as_ref().unwrap().to_string();

        // Extract field info
        let (mut field_final_name, field_desc, _, field_doc_lines, _, _) =
            crate::doc_parser::extract_naming_and_doc(&field.attrs, &default_field_name);

        // Apply Rename Rule
        // Only apply if the name hasn't been explicitly renamed via attributes
        // AND there is a rename rule present.
        if field_final_name == default_field_name {
            if let Some(rule) = rename_rule {
                field_final_name = crate::doc_parser::apply_casing(&field_final_name, rule);
            }
        }

        let (mut field_schema, is_required) = map_syn_type_to_openapi(&field.ty);

        // Field Description
        if !field_desc.is_empty() {
            if let Value::Object(map) = &mut field_schema {
                map.insert("description".to_string(), Value::String(field_desc));
            }
        }

        // Validation Attributes
        let validation_props = crate::doc_parser::extract_validation(&field.attrs);
        if !validation_props.as_object().unwrap().is_empty() {
            json_merge(&mut field_schema, validation_props);
        }

        // Field Overrides (@openapi lines)
        let mut field_openapi_lines = Vec::new();
        let mut collecting_openapi = false;
        for line in &field_doc_lines {
            let trimmed = line.trim();
            if trimmed.starts_with("@openapi") {
                collecting_openapi = true;
                let rest = trimmed.strip_prefix("@openapi").unwrap().trim();
                if !rest.is_empty() && !rest.starts_with("rename") {
                    field_openapi_lines.push(rest.to_string());
                }
            } else if collecting_openapi {
                field_openapi_lines.push(line.to_string());
            }
        }

        if !field_openapi_lines.is_empty() {
            let override_yaml = field_openapi_lines.join("\n");
            match serde_yaml_ng::from_str::<Value>(&override_yaml) {
                Ok(override_val) => {
                    if !override_val.is_null() {
                        json_merge(&mut field_schema, override_val);
                    }
                }
                Err(e) => {
                    log::warn!(
                        "Failed to parse @openapi override for field '{}': {}",
                        default_field_name,
                        e
                    );
                }
            }
        }

        (field_final_name, field_schema, is_required)
    }
    fn process_enum_variant(
        variant: &syn::Variant,
        rename_rule: &Option<String>,
    ) -> Option<String> {
        if !matches!(variant.fields, syn::Fields::Unit) {
            return None;
        }
        let default_variant_name = variant.ident.to_string();
        // Extract variant info (renaming only)
        let (mut variant_final_name, _, _, _, _, _) =
            crate::doc_parser::extract_naming_and_doc(&variant.attrs, &default_variant_name);

        // Apply Rename Rule
        if variant_final_name == default_variant_name {
            if let Some(rule) = rename_rule {
                variant_final_name = crate::doc_parser::apply_casing(&variant_final_name, rule);
            }
        }
        Some(variant_final_name)
    }
}

// Helper to wrap content in components/schemas
fn wrap_in_schema(name: &str, content: &str) -> String {
    let indented = content
        .lines()
        .map(|l| format!("      {}", l))
        .collect::<Vec<_>>()
        .join("\n");
    format!("components:\n  schemas:\n    {}:\n{}", name, indented)
}

pub use crate::type_mapper::map_syn_type_to_openapi;

// Deep Merge Helper for JSON Values
pub fn json_merge(a: &mut Value, b: Value) {
    match (a, b) {
        (Value::Object(a), Value::Object(b)) => {
            for (k, v) in b {
                json_merge(a.entry(k).or_insert(Value::Null), v);
            }
        }
        (a, b) => *a = b,
    }
}

impl<'ast> Visit<'ast> for OpenApiVisitor {
    fn visit_file(&mut self, i: &'ast File) {
        // State machine for file-level doc blocks
        let mut current_block_type: Option<String> = None;
        let mut current_block_lines = Vec::new();
        let mut start_line = 1;

        // Process file attributes (inner doc comments)
        for attr in &i.attrs {
            if attr.path().is_ident("doc") {
                if let syn::Meta::NameValue(meta) = &attr.meta {
                    if let Expr::Lit(expr_lit) = &meta.value {
                        if let syn::Lit::Str(lit_str) = &expr_lit.lit {
                            let raw_line = lit_str.value();
                            let trimmed = raw_line.trim();

                            if trimmed.starts_with("@openapi-type") {
                                // Flush previous if exists
                                if !current_block_lines.is_empty() {
                                    let body = current_block_lines.join("\n");
                                    if let Some(name) = current_block_type.take() {
                                        let wrapped = wrap_in_schema(&name, &body);
                                        self.items.push(ExtractedItem::Schema {
                                            name: Some(name),
                                            content: wrapped,
                                            line: start_line,
                                        });
                                    } else {
                                        // Standard Root/Fragment block
                                        self.parse_doc_block(&body, None, start_line);
                                    }
                                    current_block_lines.clear();
                                }

                                // Start New Type
                                if let Some(name) = trimmed.strip_prefix("@openapi-type") {
                                    current_block_type = Some(name.trim().to_string());
                                    start_line = attr.span().start().line;
                                }
                            } else if trimmed.starts_with("@openapi") {
                                // Flush previous
                                if !current_block_lines.is_empty() {
                                    let body = current_block_lines.join("\n");
                                    if let Some(name) = current_block_type.take() {
                                        let wrapped = wrap_in_schema(&name, &body);
                                        self.items.push(ExtractedItem::Schema {
                                            name: Some(name),
                                            content: wrapped,
                                            line: start_line,
                                        });
                                    } else {
                                        self.parse_doc_block(&body, None, start_line);
                                    }
                                    current_block_lines.clear();
                                }

                                // Start Root/Fragment
                                current_block_type = None;
                                start_line = attr.span().start().line;
                                current_block_lines.push(raw_line); // preserve header
                            } else if trimmed.starts_with("@route") {
                                // Flush previous unless it was just general docs
                                if !current_block_lines.is_empty() && current_block_type.is_some() {
                                    // If we were building a type, flush it
                                    let body = current_block_lines.join("\n");
                                    if let Some(name) = current_block_type.take() {
                                        let wrapped = wrap_in_schema(&name, &body);
                                        self.items.push(ExtractedItem::Schema {
                                            name: Some(name),
                                            content: wrapped,
                                            line: start_line,
                                        });
                                    }
                                    current_block_lines.clear();
                                    start_line = attr.span().start().line;
                                } else if current_block_lines.is_empty() {
                                    start_line = attr.span().start().line;
                                }

                                current_block_type = None;
                                current_block_lines.push(raw_line);
                            } else if !current_block_lines.is_empty()
                                || current_block_type.is_some()
                            {
                                current_block_lines.push(raw_line);
                            }
                        }
                    }
                }
            } else {
                // Flush on non-doc attr to be safe
                if !current_block_lines.is_empty() {
                    let body = current_block_lines.join("\n");
                    if let Some(name) = current_block_type.take() {
                        let wrapped = wrap_in_schema(&name, &body);
                        self.items.push(ExtractedItem::Schema {
                            name: Some(name),
                            content: wrapped,
                            line: start_line,
                        });
                    } else {
                        // Check if it's a virtual route
                        if body.contains("@route") {
                            self.items.push(ExtractedItem::RouteDSL {
                                content: body,
                                line: start_line,
                                operation_id: format!("virtual_route_{}", start_line),
                            });
                        } else {
                            self.parse_doc_block(&body, None, start_line);
                        }
                    }
                    current_block_lines.clear();
                }
            }
        }

        // Flush EOF
        if !current_block_lines.is_empty() {
            let body = current_block_lines.join("\n");
            if let Some(name) = current_block_type {
                let wrapped = wrap_in_schema(&name, &body);
                self.items.push(ExtractedItem::Schema {
                    name: Some(name),
                    content: wrapped,
                    line: start_line,
                });
            } else {
                // Check if it's a virtual route
                if body.contains("@route") {
                    self.items.push(ExtractedItem::RouteDSL {
                        content: body,
                        line: start_line,
                        operation_id: format!("virtual_route_{}", start_line),
                    });
                } else {
                    self.parse_doc_block(&body, None, start_line);
                }
            }
        }

        visit::visit_file(self, i);
    }

    fn visit_item_fn(&mut self, i: &'ast ItemFn) {
        let mut doc_lines = Vec::new();
        for attr in &i.attrs {
            if attr.path().is_ident("doc") {
                if let syn::Meta::NameValue(meta) = &attr.meta {
                    if let Expr::Lit(expr_lit) = &meta.value {
                        if let syn::Lit::Str(lit_str) = &expr_lit.lit {
                            doc_lines.push(lit_str.value());
                        }
                    }
                }
            }
        }

        // Check for DSL trigger
        let has_route = doc_lines.iter().any(|l| l.trim().starts_with("@route"));

        if !has_route {
            // Legacy Fallback
            self.check_attributes(&i.attrs, None, i.span().start().line);
            visit::visit_item_fn(self, i);
            return;
        }

        // Emitting Raw DSL for late binding
        let content = doc_lines.join("\n");
        self.items.push(ExtractedItem::RouteDSL {
            content,
            line: i.span().start().line,
            operation_id: i.sig.ident.to_string(),
        });

        visit::visit_item_fn(self, i);
    }

    fn visit_item_type(&mut self, i: &'ast ItemType) {
        let ident = i.ident.to_string();
        let (mut schema, _) = map_syn_type_to_openapi(&i.ty);

        // Docs & Overrides
        let mut desc_lines = Vec::new();
        let mut openapi_lines = Vec::new();
        let mut collecting_openapi = false;

        for attr in &i.attrs {
            if attr.path().is_ident("doc") {
                if let syn::Meta::NameValue(meta) = &attr.meta {
                    if let Expr::Lit(expr_lit) = &meta.value {
                        if let syn::Lit::Str(lit_str) = &expr_lit.lit {
                            let val = lit_str.value();
                            let trimmed = val.trim();

                            if trimmed.starts_with("@openapi") {
                                collecting_openapi = true;
                                let rest = trimmed.strip_prefix("@openapi").unwrap().trim();
                                if !rest.is_empty() {
                                    openapi_lines.push(rest.to_string());
                                }
                            } else if collecting_openapi {
                                openapi_lines.push(val.to_string());
                            } else {
                                desc_lines.push(val.trim().to_string());
                            }
                        }
                    }
                }
            } else {
                collecting_openapi = false;
            }
        }

        if !desc_lines.is_empty() {
            let desc_str = desc_lines.join(" ");
            if let Value::Object(map) = &mut schema {
                map.insert("description".to_string(), Value::String(desc_str));
            }
        }

        if !openapi_lines.is_empty() {
            let override_yaml = openapi_lines.join("\n");
            if let Ok(override_val) = serde_yaml_ng::from_str::<Value>(&override_yaml) {
                if !override_val.is_null() {
                    json_merge(&mut schema, override_val);
                }
            }
        }

        if let Ok(generated) = serde_yaml_ng::to_string(&schema) {
            let trimmed = generated.trim_start_matches("---\n").to_string();
            let wrapped = wrap_in_schema(&ident, &trimmed);
            self.items.push(ExtractedItem::Schema {
                name: Some(ident),
                content: wrapped,
                line: i.span().start().line,
            });
        }

        visit::visit_item_type(self, i);
    }

    fn visit_item_struct(&mut self, i: &'ast ItemStruct) {
        // 1. Extract Info & Renaming
        let default_name = i.ident.to_string();
        let (final_name, struct_desc, rename_rule, doc_lines, _, _) =
            crate::doc_parser::extract_naming_and_doc(&i.attrs, &default_name);

        // Safety: Explicit export only (check raw doc lines for @openapi tag)
        if !doc_lines.iter().any(|l| l.contains("@openapi")) {
            visit::visit_item_struct(self, i);
            return;
        }

        let mut properties = serde_json::Map::new();
        let mut required_fields = Vec::new();
        let mut has_fields = false;

        if let syn::Fields::Named(fields) = &i.fields {
            for field in &fields.named {
                has_fields = true;
                let (field_final_name, field_schema, is_required) =
                    Self::process_struct_field(field, &rename_rule);

                properties.insert(field_final_name.clone(), field_schema);
                if is_required {
                    required_fields.push(field_final_name);
                }
            }
        }

        // Struct Level Schema
        let mut schema = if has_fields {
            let mut s = json!({
                "type": "object",
                "properties": properties
            });
            if !required_fields.is_empty() {
                if let Value::Object(map) = &mut s {
                    map.insert("required".to_string(), json!(required_fields));
                }
            }
            s
        } else {
            // Unit Struct
            json!({ "type": "object" })
        };

        // Struct Description
        if !struct_desc.is_empty() {
            json_merge(&mut schema, json!({ "description": struct_desc }));
        }

        // Struct Overrides & Blueprint
        let mut openapi_lines = Vec::new();
        let mut collecting_openapi = false;
        let mut blueprint_params: Option<Vec<String>> = None;

        for line in &doc_lines {
            let trimmed = line.trim();
            if trimmed.starts_with("@openapi") {
                collecting_openapi = true;
                let rest = trimmed.strip_prefix("@openapi").unwrap().trim();

                if !rest.is_empty() && !rest.starts_with("rename") && !rest.starts_with("-type") {
                    if rest.contains('<') {
                        // Blueprint detection
                        if let Some(start) = rest.find('<') {
                            if let Some(end) = rest.rfind('>') {
                                let params_str = &rest[start + 1..end];
                                blueprint_params = Some(
                                    params_str
                                        .split(',')
                                        .map(|p| p.trim().to_string())
                                        .filter(|p| !p.is_empty())
                                        .collect(),
                                );

                                let after_gt = rest[end + 1..].trim();
                                if !after_gt.is_empty() {
                                    openapi_lines.push(after_gt.to_string());
                                }
                            }
                        }
                    } else {
                        openapi_lines.push(rest.to_string());
                    }
                }
            } else if collecting_openapi {
                openapi_lines.push(line.to_string());
            }
        }

        if !openapi_lines.is_empty() {
            let override_yaml = openapi_lines.join("\n");
            match serde_yaml_ng::from_str::<Value>(&override_yaml) {
                Ok(override_val) => {
                    if !override_val.is_null() {
                        json_merge(&mut schema, override_val);
                    }
                }
                Err(e) => {
                    log::warn!(
                        "Failed to parse @openapi override for struct '{}': {}",
                        final_name,
                        e
                    );
                }
            }
        }

        // Final Serialize
        match serde_yaml_ng::to_string(&schema) {
            Ok(generated) => {
                let trimmed = generated.trim_start_matches("---\n").to_string();

                if let Some(params) = blueprint_params {
                    self.items.push(ExtractedItem::Blueprint {
                        name: final_name,
                        params,
                        content: trimmed,
                        line: i.span().start().line,
                    });
                } else {
                    let wrapped = wrap_in_schema(&final_name, &trimmed);
                    self.items.push(ExtractedItem::Schema {
                        name: Some(final_name),
                        content: wrapped,
                        line: i.span().start().line,
                    });
                }
            }
            Err(e) => {
                log::error!(
                    "Failed to serialize schema for struct '{}': {}",
                    default_name,
                    e
                );
            }
        }

        visit::visit_item_struct(self, i);
    }

    fn visit_item_enum(&mut self, i: &'ast ItemEnum) {
        // 1. Extract Info & Renaming
        let default_name = i.ident.to_string();
        let (final_name, enum_desc, rename_rule, doc_lines, serde_tag, serde_content) =
            crate::doc_parser::extract_naming_and_doc(&i.attrs, &default_name);

        // Safety: Explicit export only
        if !doc_lines.iter().any(|l| l.contains("@openapi")) {
            visit::visit_item_enum(self, i);
            return;
        }

        // ADJACENTLY TAGGED ENUM LOGIC
        if let Some(tag_prop) = serde_tag {
            // This is a "oneOf" container enum
            // 1. Generate Variant Schemas
            let mut variant_refs = Vec::new();
            let mut mapping = serde_json::Map::new();

            for v in &i.variants {
                let default_variant_name = v.ident.to_string();
                let (variant_final_value, variant_desc, _, _, _, _) =
                    crate::doc_parser::extract_naming_and_doc(&v.attrs, &default_variant_name);

                // Apply Rename Rule (to the TAG value, NOT the schema name)
                let tag_value = if variant_final_value == default_variant_name {
                    if let Some(rule) = &rename_rule {
                        crate::doc_parser::apply_casing(&variant_final_value, rule)
                    } else {
                        variant_final_value
                    }
                } else {
                    variant_final_value
                };

                // Variant Schema Name: {EnumName}{VariantName} (PascalCase)
                let variant_schema_name = format!("{}{}", final_name, v.ident);
                let variant_ref = format!("#/components/schemas/{}", variant_schema_name);

                variant_refs.push(json!({ "$ref": variant_ref }));
                mapping.insert(tag_value.clone(), json!(variant_ref));

                // Build Variant Schema
                let mut properties = serde_json::Map::new();
                let mut required = vec![tag_prop.clone()];

                // Force Tag Property
                properties.insert(
                    tag_prop.clone(),
                    json!({
                        "type": "string",
                        "enum": [tag_value],
                        "description": format!("Discriminator: {}", tag_value)
                    }),
                );

                // Variant Fields
                let mut content_schema = None;

                if let syn::Fields::Named(fields) = &v.fields {
                    let mut inner_props = serde_json::Map::new();
                    let mut inner_req = Vec::new();

                    for field in &fields.named {
                        let (f_name, f_schema, f_req) =
                            Self::process_struct_field(field, &rename_rule);
                        inner_props.insert(f_name.clone(), f_schema);
                        if f_req {
                            inner_req.push(f_name);
                        }
                    }
                    content_schema = Some(json!({
                        "type": "object",
                        "properties": inner_props,
                        "required": inner_req
                    }));
                } else if let syn::Fields::Unnamed(fields) = &v.fields {
                    // Tuple Variants
                    if fields.unnamed.len() == 1 {
                        let field = &fields.unnamed[0];
                        let (mut schema, _) =
                            crate::type_mapper::map_syn_type_to_openapi(&field.ty);

                        // Apply validation attributes
                        let validation = crate::doc_parser::extract_validation(&field.attrs);
                        if validation.is_object() {
                            crate::visitor::json_merge(&mut schema, validation);
                        }

                        content_schema = Some(schema);
                    } else {
                        log::warn!(
                            "Tuple variants with >1 fields in tagged enums are complex. Skipping fields for {}",
                            default_variant_name
                        );
                    }
                }

                if let Some(content_prop) = &serde_content {
                    // ADJACENTLY TAGGED: { "tag": "...", "content": <Inner> }
                    if let Some(inner) = content_schema {
                        properties.insert(content_prop.clone(), inner);
                        required.push(content_prop.clone());
                    }
                } else {
                    // INTERNALLY TAGGED: { "tag": "...", ...fields }
                    // Only works for Struct variants or Unit variants.
                    // Tuple variants in Internally Tagged are usually invalid or map to something else, but here we merge fields.
                    if let Some(inner) = content_schema {
                        if let Some(props) = inner.get("properties").and_then(|p| p.as_object()) {
                            for (k, v) in props {
                                properties.insert(k.clone(), v.clone());
                            }
                        }
                        if let Some(req) = inner.get("required").and_then(|r| r.as_array()) {
                            for r in req {
                                if let Some(s) = r.as_str() {
                                    required.push(s.to_string());
                                }
                            }
                        }
                    }
                }

                let mut variant_schema = json!({
                    "type": "object",
                    "properties": properties,
                    "required": required
                });

                if !variant_desc.is_empty() {
                    json_merge(&mut variant_schema, json!({ "description": variant_desc }));
                }

                // Emit Variant Schema
                if let Ok(generated) = serde_yaml_ng::to_string(&variant_schema) {
                    let trimmed = generated.trim_start_matches("---\n").to_string();
                    let wrapped = wrap_in_schema(&variant_schema_name, &trimmed);
                    self.items.push(ExtractedItem::Schema {
                        name: Some(variant_schema_name),
                        content: wrapped,
                        line: v.span().start().line,
                    });
                }
            }

            // 2. Generate Main Discriminator Schema
            let mut main_schema = json!({
                "type": "object",
                "oneOf": variant_refs,
                "discriminator": {
                    "propertyName": tag_prop,
                    "mapping": mapping
                }
            });

            if !enum_desc.is_empty() {
                json_merge(&mut main_schema, json!({ "description": enum_desc }));
            }

            // Emit Main Schema
            if let Ok(generated) = serde_yaml_ng::to_string(&main_schema) {
                let trimmed = generated.trim_start_matches("---\n").to_string();
                let wrapped = wrap_in_schema(&final_name, &trimmed);
                self.items.push(ExtractedItem::Schema {
                    name: Some(final_name),
                    content: wrapped,
                    line: i.span().start().line,
                });
            }

            visit::visit_item_enum(self, i);
            return;
        }

        // STANDARD STRING ENUM LOGIC
        let mut variants = Vec::new();
        for v in &i.variants {
            if let Some(variant_name) = Self::process_enum_variant(v, &rename_rule) {
                variants.push(variant_name);
            }
        }

        let mut schema = if !variants.is_empty() {
            json!({
                "type": "string",
                "enum": variants
            })
        } else {
            json!({ "type": "string" }) // fallback
        };

        // Enum Description
        if !enum_desc.is_empty() {
            json_merge(&mut schema, json!({ "description": enum_desc }));
        }

        // Enum Overrides & Blueprint
        let mut openapi_lines = Vec::new();
        let mut collecting_openapi = false;
        let mut blueprint_params: Option<Vec<String>> = None;

        for line in &doc_lines {
            let trimmed = line.trim();
            if trimmed.starts_with("@openapi") {
                collecting_openapi = true;
                let rest = trimmed.strip_prefix("@openapi").unwrap().trim();

                if !rest.is_empty() && !rest.starts_with("rename") && !rest.starts_with("-type") {
                    if rest.contains('<') {
                        // Blueprint detection
                        if let Some(start) = rest.find('<') {
                            if let Some(end) = rest.rfind('>') {
                                let params_str = &rest[start + 1..end];
                                blueprint_params = Some(
                                    params_str
                                        .split(',')
                                        .map(|p| p.trim().to_string())
                                        .filter(|p| !p.is_empty())
                                        .collect(),
                                );

                                let after_gt = rest[end + 1..].trim();
                                if !after_gt.is_empty() {
                                    openapi_lines.push(after_gt.to_string());
                                }
                            }
                        }
                    } else {
                        openapi_lines.push(rest.to_string());
                    }
                }
            } else if collecting_openapi {
                openapi_lines.push(line.to_string());
            }
        }

        if !openapi_lines.is_empty() {
            let override_yaml = openapi_lines.join("\n");
            match serde_yaml_ng::from_str::<Value>(&override_yaml) {
                Ok(override_val) => {
                    if !override_val.is_null() {
                        json_merge(&mut schema, override_val);
                    }
                }
                Err(e) => {
                    log::warn!(
                        "Failed to parse @openapi override for enum '{}': {}",
                        final_name,
                        e
                    );
                }
            }
        }

        // Only emit if we have variants OR overrides
        if !variants.is_empty() || !openapi_lines.is_empty() {
            if let Ok(generated) = serde_yaml_ng::to_string(&schema) {
                let trimmed = generated.trim_start_matches("---\n").to_string();

                if let Some(params) = blueprint_params {
                    self.items.push(ExtractedItem::Blueprint {
                        name: final_name,
                        params,
                        content: trimmed,
                        line: i.span().start().line,
                    });
                } else {
                    let wrapped = wrap_in_schema(&final_name, &trimmed);
                    self.items.push(ExtractedItem::Schema {
                        name: Some(final_name),
                        content: wrapped,
                        line: i.span().start().line,
                    });
                }
            }
        }

        visit::visit_item_enum(self, i);
    }

    fn visit_item_mod(&mut self, i: &'ast ItemMod) {
        let mut found_tags = Vec::new();
        for attr in &i.attrs {
            if attr.path().is_ident("doc") {
                if let syn::Meta::NameValue(meta) = &attr.meta {
                    if let Expr::Lit(expr_lit) = &meta.value {
                        if let syn::Lit::Str(lit_str) = &expr_lit.lit {
                            let val = lit_str.value();
                            if val.contains("tags:") {
                                if let Some(start) = val.find('[') {
                                    if let Some(end) = val.find(']') {
                                        let content = &val[start + 1..end];
                                        for t in content.split(',') {
                                            found_tags.push(t.trim().to_string());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        let old_len = self.current_tags.len();
        self.current_tags.extend(found_tags);

        self.check_attributes(&i.attrs, None, i.span().start().line);
        visit::visit_item_mod(self, i);

        self.current_tags.truncate(old_len);
    }

    fn visit_impl_item_fn(&mut self, i: &'ast ImplItemFn) {
        self.check_attributes(&i.attrs, None, i.span().start().line);
        visit::visit_impl_item_fn(self, i);
    }
}

pub fn extract_from_file(path: std::path::PathBuf) -> crate::error::Result<Vec<ExtractedItem>> {
    let content = std::fs::read_to_string(&path)?;
    let parsed_file = syn::parse_file(&content).map_err(|e| crate::error::Error::Parse {
        file: path.clone(),
        source: e,
    })?;

    let mut visitor = OpenApiVisitor::default();
    visitor.visit_file(&parsed_file);

    Ok(visitor.items)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_struct_reflection() {
        let code = r#"
            /// @openapi
            struct MyStruct {
                pub id: String,
                pub count: i32,
                pub active: bool,
                pub tags: Vec<String>,
                pub meta: Option<String>
            }
        "#;
        let item_struct: ItemStruct = syn::parse_str(code).expect("Failed to parse struct");

        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_struct(&item_struct);

        assert_eq!(visitor.items.len(), 1);
        match &visitor.items[0] {
            ExtractedItem::Schema { name, content, .. } => {
                assert_eq!(name.as_ref().unwrap(), "MyStruct");
                // Check reflection
                assert!(content.contains("type: object"));
                assert!(content.contains("properties"));
                assert!(content.contains("id"));
                assert!(content.contains("type: string"));
                assert!(content.contains("count"));
                assert!(content.contains("type: integer"));

                // Vec
                assert!(content.contains("tags"));
                assert!(content.contains("type: array"));

                // Option -> Not required
                assert!(content.contains("required"));
                assert!(content.contains("id"));
                assert!(content.contains("count"));
                assert!(content.contains("tags"));
                // meta should NOT be in required
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_module_tags() {
        let code = r#"
            /// @openapi
            /// tags: [GroupA]
            mod my_mod {
                /// @openapi
                /// paths:
                ///   /test:
                ///     get:
                ///       description: op
                fn my_fn() {}
            }
        "#;
        let item_mod: ItemMod = syn::parse_str(code).expect("Failed to parse mod");

        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_mod(&item_mod);

        assert_eq!(visitor.items.len(), 2);
        match &visitor.items[1] {
            ExtractedItem::Schema { content, .. } => {
                assert!(
                    content.contains("tags:"),
                    "Function should have tags injected"
                );
                assert!(content.contains("- GroupA"));
                assert!(content.contains("/test:"));
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_complex_types_and_docs() {
        let code = r#"
            /// @openapi
            struct Complex {
                /// Primary Identifier
                pub id: Uuid,
                /// @openapi example: "user@example.com"
                pub email: String,
                pub created_at: DateTime<Utc>,
                pub metadata: HashMap<String, String>,
                pub scores: Vec<f64>,
                pub config: Option<serde_json::Value>
            }
        "#;
        let item_struct: ItemStruct = syn::parse_str(code).expect("Failed to parse struct");

        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_struct(&item_struct);

        match &visitor.items[0] {
            ExtractedItem::Schema { content, .. } => {
                // Check doc comment merge
                assert!(
                    content.contains("description: Primary Identifier"),
                    "Should merge doc comments"
                );

                // Check attribute override
                assert!(
                    content.contains("example: user@example.com"),
                    "Should merge @openapi attributes"
                );

                // Check Types
                assert!(content.contains("format: uuid"));
                assert!(content.contains("format: date-time"));
                assert!(content.contains("format: double"));
                assert!(content.contains("additionalProperties")); // Map

                // Option -> Not required
                let _required_idx = content.find("required").unwrap();
                let _config_idx = content.find("config").unwrap();
                // We can't strictly check line order easily with contains, but we know config (Option) shouldn't be in required list
                // However, let's just assert content does not have "- config" inside the required block.
                // Since this is YAML generated by serde, it's reliable.
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_visitor_bugs_v0_4_2() {
        // 1. Generic Fallback Test ($T)
        let code_generic = r#"
            /// @openapi
            struct Container<T> {
                pub item: T,
            }
        "#;
        let item_struct: ItemStruct = syn::parse_str(code_generic).expect("Failed to parse struct");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_struct(&item_struct);
        match &visitor.items[0] {
            ExtractedItem::Schema { content, .. } => {
                // FIX 3: Should contain $ref: $T, NOT #/components/schemas/T
                assert!(
                    content.contains("$ref: $T"),
                    "Should use Smart Ref for generics (expected $ref: $T)"
                );
            }
            _ => panic!("Expected Schema"),
        }

        // 2. Multi-line Field Docs Test
        let code_multiline = r#"
            /// @openapi
            struct User {
                /// @openapi
                /// example:
                ///   - "Alice"
                ///   - "Bob"
                pub names: Vec<String>
            }
        "#;
        let item_struct_m: ItemStruct =
            syn::parse_str(code_multiline).expect("Failed to parse struct");
        let mut visitor_m = OpenApiVisitor::default();
        visitor_m.visit_item_struct(&item_struct_m);
        match &visitor_m.items[0] {
            ExtractedItem::Schema { content, .. } => {
                // FIX 2: Should correctly parse the YAML list
                assert!(content.contains("example:"), "Should contain example key");
                assert!(
                    content.contains("- Alice"),
                    "Should parse multi-line attributes (- Alice)"
                );
            }
            _ => panic!("Expected Schema"),
        }

        // 3. Tag Injection Test (Indentation)
        let code_tags = r#"
            /// @openapi
            /// tags: [MyTag]
            mod my_mod {
                 /// @openapi
                 /// paths:
                 ///   /foo:
                 ///     get:
                 ///       description: op
                 fn my_fn() {}
            }
        "#;
        let item_mod: ItemMod = syn::parse_str(code_tags).expect("Failed to parse mod");
        let mut visitor_t = OpenApiVisitor::default();
        visitor_t.visit_item_mod(&item_mod);
        match &visitor_t.items[1] {
            // Item 1 is the fn
            ExtractedItem::Schema { content, .. } => {
                // FIX 1: Indentation check
                let get_idx = content.find("get:").unwrap();
                let tags_idx = content.find("tags:").unwrap();

                // Tags must appear AFTER get
                assert!(tags_idx > get_idx, "Tags should be inside/after get");

                // Tags must appear BEFORE description (if injected at top of block)
                let desc_idx = content.find("description:").unwrap();
                assert!(
                    tags_idx < desc_idx,
                    "Tags should be injected before description (top of block)"
                );
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_visitor_pollution_v0_4_3() {
        let code = r#"
            /// @openapi
            struct Clean {
                /// Clean Description
                /// @openapi example: "dirty"
                pub field: String,
            }
        "#;
        let item_struct: ItemStruct = syn::parse_str(code).expect("Failed to parse struct");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_struct(&item_struct);

        match &visitor.items[0] {
            ExtractedItem::Schema { content, .. } => {
                // Description should be "Clean Description"
                // It should NOT contain "@openapi" or "example: dirty"
                // But the example should be merged into the schema separately.

                assert!(content.contains("description: Clean Description"));
                assert!(
                    !content.contains("description: Clean Description @openapi"),
                    "Should Clean Description"
                );
                assert!(
                    content.contains("example: dirty"),
                    "Should still have the example"
                );
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_type_alias_reflection() {
        let code = r#"
            /// @openapi
            /// format: uuid
            /// description: User ID Alias
            type UserId = String;
        "#;
        let item_type: ItemType = syn::parse_str(code).expect("Failed to parse type");

        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_type(&item_type);

        assert_eq!(visitor.items.len(), 1);
        match &visitor.items[0] {
            ExtractedItem::Schema { name, content, .. } => {
                assert_eq!(name.as_ref().unwrap(), "UserId");
                assert!(content.contains("type: string"));
                assert!(content.contains("format: uuid"));
                assert!(content.contains("description: User ID Alias"));
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_virtual_types_unit_struct() {
        let code = r#"
            /// @openapi
            /// type: string
            /// enum: [A, B]
            struct MyEnum;
        "#;
        let item_struct: ItemStruct = syn::parse_str(code).expect("Failed to parse struct");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_struct(&item_struct);

        // This relies on implicit schema parsing from docs
        assert_eq!(visitor.items.len(), 1);
        match &visitor.items[0] {
            ExtractedItem::Schema { name, content, .. } => {
                assert_eq!(name.as_ref().unwrap(), "MyEnum");
                assert!(content.contains("type: string"));
                assert!(content.contains("enum:"));
                assert!(content.contains("A"));
                assert!(content.contains("B"));
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_global_virtual_type() {
        let code = r#"
            //! @openapi-type Email
            //! type: string
            //! format: email
            //! description: Valid email address
            
            // Other code...
            fn main() {}
        "#;
        // Parse as File because it's a file attribute (inner doc comment)
        let file: File = syn::parse_str(code).expect("Failed to parse file");

        let mut visitor = OpenApiVisitor::default();
        visitor.visit_file(&file);

        // Should find Email schema
        let email_schema = visitor.items.iter().find(|i| {
            if let ExtractedItem::Schema { name, .. } = i {
                name.as_deref() == Some("Email")
            } else {
                false
            }
        });

        assert!(email_schema.is_some(), "Should find Email schema");
        match email_schema.unwrap() {
            ExtractedItem::Schema { content, .. } => {
                assert!(content.contains("type: string"));
                assert!(content.contains("format: email"));
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_route_dsl_basic() {
        let code = r#"
            /// Get Users
            /// Returns a list of users.
            /// @route GET /users
            /// @tag Users
            fn get_users() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        assert_eq!(visitor.items.len(), 1);
        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let yaml =
                crate::dsl::parse_route_dsl(&lines, operation_id).expect("DSL Parsing failed");

            assert!(yaml.contains("paths:"));
            assert!(yaml.contains("/users:"));
            assert!(yaml.contains("get:"));
            assert!(yaml.contains("summary: Get Users"));
            assert!(yaml.contains("description:"));
            assert!(yaml.contains("Returns a list of users."));
            assert!(yaml.contains("tags:"));
            assert!(yaml.contains("- Users"));
        } else {
            panic!("Expected RouteDSL item, got {:?}", &visitor.items[0]);
        }
    }

    #[test]
    fn test_route_dsl_params() {
        let code = r#"
            /// @route GET /users/{id}
            /// @path-param id: u32 "User ID"
            /// @query-param filter: Option<String> "Name filter"
            fn get_user() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let yaml =
                crate::dsl::parse_route_dsl(&lines, operation_id).expect("DSL parsing failed");

            // Path Param
            assert!(yaml.contains("name: id"));
            assert!(yaml.contains("in: path"));

            assert!(yaml.contains("required: true"));
            assert!(yaml.contains("format: int32"));

            // Query Param
            assert!(yaml.contains("name: filter"));
            assert!(yaml.contains("in: query"));
            assert!(yaml.contains("required: false")); // Option<String>
        } else {
            panic!("Expected RouteDSL item");
        }
    }

    #[test]
    fn test_route_dsl_body_return() {
        let code = r#"
            /// @route POST /users
            /// @body String text/plain
            /// @return 201: u64 "Created ID"
            fn create_user() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let yaml =
                crate::dsl::parse_route_dsl(&lines, operation_id).expect("DSL parsing failed");

            // Body
            assert!(yaml.contains("requestBody:"));
            assert!(yaml.contains("text/plain:")); // MIME
            assert!(yaml.contains("schema:"));
            assert!(yaml.contains("type: string"));

            // Return
            assert!(yaml.contains("responses:"));
            assert!(yaml.contains("'201':"));
            assert!(yaml.contains("description: Created ID"));
            assert!(yaml.contains("format: int64"));
        } else {
            panic!("Expected RouteDSL item");
        }
    }

    #[test]
    fn test_route_dsl_security() {
        let code = r#"
            /// @route GET /secure
            /// @security oidcAuth("read")
            fn secure_op() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let yaml =
                crate::dsl::parse_route_dsl(&lines, operation_id).expect("DSL parsing failed");

            assert!(yaml.contains("security:"));
            assert!(yaml.contains("- oidcAuth:"));
            assert!(yaml.contains("- read"));
        } else {
            panic!("Expected RouteDSL item");
        }
    }

    #[test]
    fn test_route_dsl_generics_and_unit() {
        let code = r#"
            /// @route POST /test
            /// @return 200: $Page<User> "Generic List"
            /// @return 204: () "Nothing"
            fn test_op() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let yaml =
                crate::dsl::parse_route_dsl(&lines, operation_id).expect("DSL parsing failed");

            // 1. Verify Generic is RAW (Crucial for Monomorphizer)
            assert!(yaml.contains("$ref: $Page<User>"));
            assert!(!yaml.contains("#/components/schemas/$Page<User>")); // MUST FAIL if wrapped

            // 2. Verify Unit has NO content
            assert!(yaml.contains("'204':"));
            assert!(yaml.contains("description: Nothing"));
            // Ensure 204 block does not have "content:"
            // (We check strict context or absence of content key for 204)
            let json: serde_json::Value = serde_yaml_ng::from_str(&yaml).unwrap();
            let resp_204 = &json["paths"]["/test"]["post"]["responses"]["204"];
            assert!(
                resp_204.get("content").is_none(),
                "204 response should not have content"
            );
        } else {
            panic!("Expected RouteDSL item");
        }
    }

    #[test]
    fn test_route_dsl_unit_return() {
        let code = r#"
            /// @route DELETE /delete
            /// @return 204: "Deleted Successfully"
            /// @return 202: () "Accepted"
            fn delete_op() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let yaml =
                crate::dsl::parse_route_dsl(&lines, operation_id).expect("DSL parsing failed");

            // Parse to verify structure
            let json: serde_json::Value = serde_yaml_ng::from_str(&yaml).unwrap();
            let responses = &json["paths"]["/delete"]["delete"]["responses"];

            // Case 1: Implicit Unit ("Deleted Successfully")
            let resp_204 = &responses["204"];
            assert_eq!(resp_204["description"], "Deleted Successfully");
            assert!(
                resp_204.get("content").is_none(),
                "204 should have no content"
            );

            // Case 2: Explicit Unit (())
            let resp_202 = &responses["202"];
            assert_eq!(resp_202["description"], "Accepted");
            assert!(
                resp_202.get("content").is_none(),
                "202 should have no content"
            );
        } else {
            panic!("Expected RouteDSL item");
        }
    }
}

#[cfg(test)]
mod dsl_tests {
    use super::*;

    #[test]
    fn test_route_dsl_inline_params() {
        let code = r#"
            /// @route GET /items/{id: u32 "Item ID"}
            fn get_item() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let yaml =
                crate::dsl::parse_route_dsl(&lines, operation_id).expect("DSL parsing failed");

            // 1. Check path normalization
            assert!(yaml.contains("/items/{id}:"));

            // 2. Check parameter extraction
            let json: serde_json::Value = serde_yaml_ng::from_str(&yaml).unwrap();
            let params = &json["paths"]["/items/{id}"]["get"]["parameters"];
            assert!(params.is_array());
            assert_eq!(params.as_array().unwrap().len(), 1);

            let p = &params[0];
            assert_eq!(p["name"], "id");
            assert_eq!(p["in"], "path");
            assert_eq!(p["required"], true);
            assert_eq!(p["description"], "Item ID");
            assert_eq!(p["schema"]["type"], "integer");
            assert_eq!(p["schema"]["format"], "int32");
        } else {
            panic!("Expected RouteDSL item");
        }
    }

    #[test]
    fn test_route_dsl_flexible_params() {
        let code = r#"
            /// @route GET /search
            /// @query-param q: String "Search Query"
            /// @query-param sort: deprecated required example="desc" "Sort Order"
            fn search() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let yaml =
                crate::dsl::parse_route_dsl(&lines, operation_id).expect("DSL parsing failed");

            let json: serde_json::Value = serde_yaml_ng::from_str(&yaml).unwrap();
            let params = &json["paths"]["/search"]["get"]["parameters"];
            let params_arr = params.as_array().unwrap();

            // Param 'q' (Standard)
            let q = params_arr.iter().find(|p| p["name"] == "q").unwrap();
            assert_eq!(q["description"], "Search Query");

            // Param 'sort' (Flexible)
            let sort = params_arr.iter().find(|p| p["name"] == "sort").unwrap();
            assert_eq!(sort["deprecated"], true);
            assert_eq!(sort["required"], true);
            assert_eq!(sort["example"], "desc");
            assert_eq!(sort["description"], "Sort Order");
        } else {
            panic!("Expected RouteDSL item");
        }
    }

    #[test]
    fn test_route_dsl_validation_error() {
        let code = r#"
            /// @route GET /items/{id}
            fn get_item_fail() {}
        "#;
        let item_fn: ItemFn = syn::parse_str(code).expect("Failed to parse fn");
        let mut visitor = OpenApiVisitor::default();
        visitor.visit_item_fn(&item_fn);

        // Should gracefully return None instead of panicking
        if let ExtractedItem::RouteDSL {
            content,
            operation_id,
            ..
        } = &visitor.items[0]
        {
            let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
            let result = crate::dsl::parse_route_dsl(&lines, operation_id);
            assert!(
                result.is_none(),
                "Should return None for missing path param definition"
            );
        }
    }

    #[test]
    fn test_doc_comment_as_description() {
        let code = r#"
            /// This is a user struct.
            /// It has multiple lines.
            /// @openapi
            struct User { name: String }
        "#;
        let item: ItemStruct = syn::parse_str(code).unwrap();
        let mut v = OpenApiVisitor::default();
        v.visit_item_struct(&item);

        match &v.items[0] {
            ExtractedItem::Schema { content, .. } => {
                assert!(
                    content.contains("description: This is a user struct. It has multiple lines.")
                );
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_description_override() {
        let code = r#"
            /// Original Docs
            /// @openapi
            /// description: Overridden
            struct User { name: String }
        "#;
        let item: ItemStruct = syn::parse_str(code).unwrap();
        let mut v = OpenApiVisitor::default();
        v.visit_item_struct(&item);

        match &v.items[0] {
            ExtractedItem::Schema { content, .. } => {
                assert!(content.contains("description: Overridden"));
                // json_merge overwrites scalars, so Original Docs is lost in favor of explicit override
            }
            _ => panic!("Expected Schema"),
        }
    }

    #[test]
    fn test_implicit_safety() {
        let code = r#"
            /// Hidden internal struct
            struct Internal { secret: String }
        "#;
        let item: ItemStruct = syn::parse_str(code).unwrap();
        let mut v = OpenApiVisitor::default();
        v.visit_item_struct(&item);
        assert!(
            v.items.is_empty(),
            "Should not export struct without @openapi tag"
        );
    }
}