macroforge_ts 0.1.78

TypeScript macro expansion engine - write compile-time macros in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
//! # Serde (Serialization/Deserialization) Module
//!
//! This module provides the `Serialize` and `Deserialize` macros for JSON
//! serialization with cycle detection and validation support.
//!
//! ## Generated Methods
//!
//! ### Serialize
//!
//! - `serialize(): string` - Serialize to JSON string
//! - `SerializeWithContext(ctx): Record<string, unknown>` - Internal method with cycle detection
//!
//! ### Deserialize
//!
//! - `static deserialize(input: unknown): Result<T, Error[]>` - Parse and validate (auto-detects string vs object)
//! - `static deserializeWithContext(value, ctx): T` - Internal method with cycle resolution
//!
//! ## Cycle Detection
//!
//! Both macros support cycle detection for object graphs with circular references:
//!
//! ```typescript
//! /** @derive(Serialize, Deserialize) */
//! class Node {
//!     value: number;
//!     next: Node | null;
//! }
//! // Creates: { __type: "Node", __id: 1, value: 1, next: { __ref: 1 } }
//! ```
//!
//! ## Field-Level Options
//!
//! The `@serde` decorator supports many options:
//!
//! | Option | Description |
//! |--------|-------------|
//! | `skip` | Skip both serialization and deserialization |
//! | `skipSerializing` | Skip only during serialization |
//! | `skipDeserializing` | Skip only during deserialization |
//! | `rename = "name"` | Use a different JSON key |
//! | `default` | Use type's default if missing |
//! | `default = "expr"` | Use specific expression if missing |
//! | `flatten` | Flatten nested object fields into parent |
//! | `serializeWith = "fn"` | Use custom function for serialization |
//! | `deserializeWith = "fn"` | Use custom function for deserialization |
//!
//! ## Container-Level Options
//!
//! | Option | Description |
//! |--------|-------------|
//! | `renameAll = "camelCase"` | Apply naming convention to all fields |
//! | `denyUnknownFields` | Reject JSON with extra fields |
//! | `tag = "fieldName"` | Custom type discriminator field name (default: `"__type"`) |
//!
//! ## Naming Conventions
//!
//! Supported values for `renameAll`:
//! - `camelCase` - `user_name` → `userName`
//! - `snake_case` - `userName` → `user_name`
//! - `SCREAMING_SNAKE_CASE` - `userName` → `USER_NAME`
//! - `kebab-case` - `userName` → `user-name`
//! - `PascalCase` - `user_name` → `UserName`
//!
//! ## Validation
//!
//! The Deserialize macro supports 30+ validators for runtime validation:
//!
//! ### String Validators
//! - `email` - Valid email format
//! - `url` - Valid URL format
//! - `uuid` - Valid UUID format
//! - `pattern("regex")` - Match regex pattern
//! - `minLength(n)`, `maxLength(n)`, `length(n)` - Length constraints
//! - `nonEmpty`, `trimmed` - Content requirements
//! - `lowercase`, `uppercase`, `capitalized` - Case requirements
//! - `startsWith("prefix")`, `endsWith("suffix")`, `includes("text")`
//!
//! ### Number Validators
//! - `int` - Must be integer
//! - `positive`, `negative`, `nonNegative`, `nonPositive`
//! - `greaterThan(n)`, `lessThan(n)`, `between(min, max)`
//! - `multipleOf(n)`, `uint8`, `finite`, `nonNaN`
//!
//! ### Array Validators
//! - `minItems(n)`, `maxItems(n)`, `itemsCount(n)`
//!
//! ### Date Validators
//! - `validDate` - Must be valid Date
//! - `afterDate("2020-01-01")`, `beforeDate("2030-01-01")`
//! - `betweenDates("start", "end")`
//!
//! ### Custom Validators
//! - `custom(functionName)` - Call custom validation function
//!
//! ## Example
//!
//! ```typescript
//! /** @derive(Serialize, Deserialize) @serde({ renameAll: "camelCase" }) */
//! class User {
//!     /** @serde({ validate: { email: true } }) */
//!     emailAddress: string;
//!
//!     /** @serde({ validate: { minLength: 3, maxLength: 50 } }) */
//!     username: string;
//!
//!     /** @serde({ skipSerializing: true }) */
//!     password: string;
//!
//!     /** @serde({ default: true }) */
//!     role: string;
//!
//!     /** @serde({ flatten: true }) */
//!     metadata: UserMetadata;
//! }
//! ```
//!
//! ## Custom Serialization Functions
//!
//! For foreign types that can't be automatically serialized, use custom functions:
//!
//! ```typescript
//! import { ZonedDateTime } from "@internationalized/date";
//!
//! // Custom serializer/deserializer functions
//! function serializeZoned(value: ZonedDateTime): unknown {
//!     return value.toAbsoluteString();
//! }
//! function deserializeZoned(raw: unknown): ZonedDateTime {
//!     return parseZonedDateTime(raw as string);
//! }
//!
//! /** @derive(Serialize, Deserialize) */
//! interface Event {
//!     name: string;
//!     /** @serde({ serializeWith: "serializeZoned", deserializeWith: "deserializeZoned" }) */
//!     startTime: ZonedDateTime;
//! }
//! ```
//!
//! ## Foreign Types (Global Configuration)
//!
//! Instead of adding `serializeWith`/`deserializeWith` to every field, you can configure
//! foreign type handlers globally in `macroforge.config.js`:
//!
//! ```javascript
//! // macroforge.config.js
//! import { DateTime } from "effect";
//!
//! export default {
//!   foreignTypes: {
//!     "DateTime.DateTime": {
//!       from: ["effect"],
//!       aliases: [
//!         { name: "DateTime", from: "effect/DateTime" }
//!       ],
//!       serialize: (v) => DateTime.formatIso(v),
//!       deserialize: (raw) => DateTime.unsafeFromDate(new Date(raw)),
//!       default: () => DateTime.unsafeNow()
//!     }
//!   }
//! }
//! ```
//!
//! With this configuration, any field typed as `DateTime.DateTime` (imported from `effect`)
//! or `DateTime` (imported from `effect/DateTime`) will automatically use the configured
//! handlers without needing per-field decorators.
//!
//! ### Foreign Type Options
//!
//! | Option | Description |
//! |--------|-------------|
//! | `from` | Array of module paths this type can be imported from |
//! | `aliases` | Array of `{ name, from }` objects for alternative type-package pairs |
//! | `serialize` | Function `(value) => unknown` for serialization |
//! | `deserialize` | Function `(raw) => T` for deserialization |
//! | `default` | Function `() => T` for default value generation |
//!
//! ### Import Source Validation
//!
//! Foreign types are only matched when the type is imported from one of the configured
//! sources. Types with the same name from different packages are ignored and fall back
//! to generic handling (TypeScript will catch any issues downstream).
//!
//! See the [Configuration](crate::host::config) module for more details.

/// Deserialize macro implementation.
pub mod derive_deserialize;

/// Serialize macro implementation.
pub mod derive_serialize;

use crate::host::ForeignTypeConfig;
use crate::host::import_registry::{with_registry, with_registry_mut};
use crate::ts_syn::abi::{DecoratorIR, DiagnosticCollector, SpanIR};

// Re-export the registry type and thread-local accessors from their canonical location.
pub use crate::host::import_registry::{
    ImportRegistry, clear_registry, install_registry, take_registry,
};

// ============================================================================
// Compat wrappers — thin delegates to with_registry / with_registry_mut.
// These keep existing serde macro code working without changes.
// They can be deprecated and inlined later.
// ============================================================================

/// Get a clone of the current foreign types, including built-in global types.
/// User-configured types are listed first (higher priority), followed by built-ins.
pub fn get_foreign_types() -> Vec<ForeignTypeConfig> {
    let mut types = crate::host::import_registry::with_foreign_types(|ft| ft.to_vec());
    types.extend(get_builtin_foreign_types());
    types
}

/// Built-in foreign type registrations for global JS/TS types.
/// These have empty `from` lists so they skip import validation.
fn get_builtin_foreign_types() -> Vec<ForeignTypeConfig> {
    let ft = |name: &str, ser: &str, deser: &str| ForeignTypeConfig {
        name: name.to_string(),
        namespace: None,
        from: vec![],
        serialize_expr: Some(ser.to_string()),
        serialize_import: None,
        deserialize_expr: Some(deser.to_string()),
        deserialize_import: None,
        default_expr: None,
        default_import: None,
        has_shape_expr: None,
        has_shape_import: None,
        aliases: vec![],
        expression_namespaces: vec![],
    };

    let typed_array = |name: &str| {
        ft(
            name,
            "(v) => Array.from(v)",
            &format!("(v) => new {name}(v as number[])"),
        )
    };

    let big_typed_array = |name: &str| {
        ft(
            name,
            "(v) => Array.from(v, (n) => String(n))",
            &format!("(v) => new {name}((v as string[]).map((s) => BigInt(s)))"),
        )
    };

    vec![
        ft("bigint", "(v) => String(v)", "(v) => BigInt(v as string)"),
        ft("URL", "(v) => v.toString()", "(v) => new URL(v as string)"),
        ft(
            "URLSearchParams",
            "(v) => v.toString()",
            "(v) => new URLSearchParams(v as string)",
        ),
        ft(
            "RegExp",
            "(v) => ({ source: v.source, flags: v.flags })",
            "(v) => new RegExp((v as any).source, (v as any).flags)",
        ),
        ft(
            "Error",
            "(v) => ({ name: v.name, message: v.message, stack: v.stack })",
            "(v) => Object.assign(new Error((v as any).message), { name: (v as any).name })",
        ),
        typed_array("Int8Array"),
        typed_array("Uint8Array"),
        typed_array("Uint8ClampedArray"),
        typed_array("Int16Array"),
        typed_array("Uint16Array"),
        typed_array("Int32Array"),
        typed_array("Uint32Array"),
        typed_array("Float32Array"),
        typed_array("Float64Array"),
        big_typed_array("BigInt64Array"),
        big_typed_array("BigUint64Array"),
        ft(
            "ArrayBuffer",
            "(v) => Array.from(new Uint8Array(v))",
            "(v) => new Uint8Array(v as number[]).buffer",
        ),
    ]
}

/// Naming convention for JSON field renaming
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum RenameAll {
    #[default]
    None,
    CamelCase,
    SnakeCase,
    ScreamingSnakeCase,
    KebabCase,
    PascalCase,
}

impl std::str::FromStr for RenameAll {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().replace(['-', '_'], "").as_str() {
            "camelcase" => Ok(Self::CamelCase),
            "snakecase" => Ok(Self::SnakeCase),
            "screamingsnakecase" => Ok(Self::ScreamingSnakeCase),
            "kebabcase" => Ok(Self::KebabCase),
            "pascalcase" => Ok(Self::PascalCase),
            _ => Err(()),
        }
    }
}

impl RenameAll {
    pub fn apply(&self, name: &str) -> String {
        use convert_case::{Case, Casing};
        match self {
            Self::None => name.to_string(),
            Self::CamelCase => name.to_case(Case::Camel),
            Self::SnakeCase => name.to_case(Case::Snake),
            Self::ScreamingSnakeCase => name.to_case(Case::UpperSnake),
            Self::KebabCase => name.to_case(Case::Kebab),
            Self::PascalCase => name.to_case(Case::Pascal),
        }
    }
}

/// Enum tagging strategy for serialized unions.
/// Mirrors Rust serde's enum representation options.
#[derive(Debug, Clone, PartialEq)]
pub enum TaggingMode {
    /// Internally tagged: `{ tag: "TypeName", ...fields }`
    /// This is the default (using `__type` as the tag field).
    InternallyTagged { tag: String },
    /// Externally tagged: `{ "TypeName": { ...fields } }` or just `"TypeName"` for unit variants
    ExternallyTagged,
    /// Adjacently tagged: `{ tag: "TypeName", content: { ...fields } }`
    AdjacentlyTagged { tag: String, content: String },
    /// Untagged: raw value with no type information wrapper
    Untagged,
}

impl Default for TaggingMode {
    fn default() -> Self {
        Self::InternallyTagged {
            tag: "__type".to_string(),
        }
    }
}

/// Container-level serde options (on the class/interface itself)
#[derive(Debug, Clone, Default)]
pub struct SerdeContainerOptions {
    pub rename_all: RenameAll,
    pub deny_unknown_fields: bool,
    /// The tagging mode for this container. Determines how type discrimination
    /// is handled in serialized union representations.
    pub tagging: TaggingMode,
}

impl SerdeContainerOptions {
    pub fn from_decorators(decorators: &[DecoratorIR]) -> Self {
        let mut opts = Self::default();
        for decorator in decorators {
            if !decorator.name.eq_ignore_ascii_case("serde") {
                continue;
            }
            let args = decorator.args_src.trim();

            if let Some(rename_all) = extract_named_string(args, "renameAll")
                && let Ok(convention) = rename_all.parse::<RenameAll>()
            {
                opts.rename_all = convention;
            }

            if has_flag(args, "denyUnknownFields") {
                opts.deny_unknown_fields = true;
            }

            // Resolve tagging mode from combination of attributes
            let tag = extract_named_string(args, "tag");
            let content = extract_named_string(args, "content");
            let untagged = has_flag(args, "untagged");
            let externally_tagged = has_flag(args, "externallyTagged");

            if untagged {
                opts.tagging = TaggingMode::Untagged;
            } else if externally_tagged {
                opts.tagging = TaggingMode::ExternallyTagged;
            } else if let Some(tag_name) = tag {
                if let Some(content_name) = content {
                    opts.tagging = TaggingMode::AdjacentlyTagged {
                        tag: tag_name,
                        content: content_name,
                    };
                } else {
                    opts.tagging = TaggingMode::InternallyTagged { tag: tag_name };
                }
            }
            // else: default remains InternallyTagged { tag: "__type" }
        }
        opts
    }

    /// Returns the tag field name for internally-tagged or adjacently-tagged modes.
    /// Returns None for externally-tagged and untagged modes.
    pub fn tag_field(&self) -> Option<&str> {
        match &self.tagging {
            TaggingMode::InternallyTagged { tag } => Some(tag.as_str()),
            TaggingMode::AdjacentlyTagged { tag, .. } => Some(tag.as_str()),
            _ => None,
        }
    }

    /// Returns the discriminator field name with a fallback default of `"__type"`.
    /// Used by individual class/interface serializers that always embed a tag.
    pub fn tag_field_or_default(&self) -> &str {
        match &self.tagging {
            TaggingMode::InternallyTagged { tag } => tag.as_str(),
            TaggingMode::AdjacentlyTagged { tag, .. } => tag.as_str(),
            _ => "__type",
        }
    }

    /// Returns the content field name for adjacently-tagged mode.
    pub fn content_field(&self) -> Option<&str> {
        match &self.tagging {
            TaggingMode::AdjacentlyTagged { content, .. } => Some(content.as_str()),
            _ => None,
        }
    }
}

/// Field-level serde options
#[derive(Debug, Clone, Default)]
pub struct SerdeFieldOptions {
    pub skip: bool,
    pub skip_serializing: bool,
    pub skip_deserializing: bool,
    pub rename: Option<String>,
    pub default: bool,
    pub default_expr: Option<String>,
    pub flatten: bool,
    pub validators: Vec<ValidatorSpec>,
    /// Custom serialization function name (like Rust's `#[serde(serialize_with)]`)
    pub serialize_with: Option<String>,
    /// Custom deserialization function name (like Rust's `#[serde(deserialize_with)]`)
    pub deserialize_with: Option<String>,
    /// Format hint for serialization/deserialization (e.g., "decimal" to serialize numbers as strings)
    pub format: Option<String>,
}

/// Result of parsing field options, containing both options and any diagnostics
#[derive(Debug, Clone, Default)]
pub struct SerdeFieldParseResult {
    pub options: SerdeFieldOptions,
    pub diagnostics: DiagnosticCollector,
}

impl SerdeFieldOptions {
    /// Parse field options from decorators, collecting diagnostics for invalid configurations
    pub fn from_decorators(decorators: &[DecoratorIR], field_name: &str) -> SerdeFieldParseResult {
        let mut opts = Self::default();
        let mut diagnostics = DiagnosticCollector::new();

        for decorator in decorators {
            if !decorator.name.eq_ignore_ascii_case("serde") {
                continue;
            }
            let args = decorator.args_src.trim();
            let decorator_span = decorator.span;

            if has_flag(args, "skip") {
                opts.skip = true;
            }
            if has_flag(args, "skipSerializing") {
                opts.skip_serializing = true;
            }
            if has_flag(args, "skipDeserializing") {
                opts.skip_deserializing = true;
            }
            if has_flag(args, "flatten") {
                opts.flatten = true;
            }

            // Check for default (both boolean flag and expression)
            if let Some(default_expr) = extract_named_string(args, "default") {
                opts.default = true;
                opts.default_expr = Some(default_expr);
            } else if has_flag(args, "default") {
                opts.default = true;
            }

            if let Some(rename) = extract_named_string(args, "rename") {
                opts.rename = Some(rename);
            }

            // Parse custom serialization/deserialization functions (like Rust's serde)
            if let Some(fn_name) = extract_named_string(args, "serializeWith") {
                opts.serialize_with = Some(fn_name);
            }
            if let Some(fn_name) = extract_named_string(args, "deserializeWith") {
                opts.deserialize_with = Some(fn_name);
            }

            if let Some(format) = extract_named_string(args, "format") {
                opts.format = Some(format);
            }

            // Extract validators with diagnostic collection
            let validators = extract_validators(args, decorator_span, field_name, &mut diagnostics);
            opts.validators.extend(validators);
        }

        SerdeFieldParseResult {
            options: opts,
            diagnostics,
        }
    }

    pub fn should_serialize(&self) -> bool {
        !self.skip && !self.skip_serializing
    }

    pub fn should_deserialize(&self) -> bool {
        !self.skip && !self.skip_deserializing
    }
}

/// Determines the serialization strategy for a TypeScript type
#[derive(Debug, Clone, PartialEq)]
pub enum TypeCategory {
    Primitive,
    Array(String),
    Optional(String),
    Nullable(String),
    Date,
    Map(String, String),
    Set(String),
    Record(String, String),
    /// Wrapper types like Partial<T>, Required<T>, Readonly<T>, Pick<T, K>, Omit<T, K>, NonNullable<T>
    /// These don't change the runtime value structure, so we serialize based on the inner type.
    /// Contains the inner type name (e.g., "User" for Partial<User>)
    Wrapper(String),
    Serializable(String),
    Unknown,
}

impl TypeCategory {
    pub fn from_ts_type(ts_type: &str) -> Self {
        let trimmed = ts_type.trim();

        // Handle string literal types (e.g., "Zoned", 'foo') - these are primitive-like
        if (trimmed.starts_with('"') && trimmed.ends_with('"'))
            || (trimmed.starts_with('\'') && trimmed.ends_with('\''))
        {
            return Self::Primitive;
        }

        // Handle primitives
        match trimmed {
            "string" | "number" | "boolean" | "null" | "undefined" | "bigint" => {
                return Self::Primitive;
            }
            "Date" => return Self::Date,
            _ => {}
        }

        // Handle Array<T> or T[]
        if trimmed.starts_with("Array<") && trimmed.ends_with('>') {
            let inner = &trimmed[6..trimmed.len() - 1];
            return Self::Array(inner.to_string());
        }
        if let Some(inner) = trimmed.strip_suffix("[]") {
            return Self::Array(inner.to_string());
        }

        // Handle Map<K, V>
        if trimmed.starts_with("Map<") && trimmed.ends_with('>') {
            let inner = &trimmed[4..trimmed.len() - 1];
            if let Some(comma_pos) = find_top_level_comma(inner) {
                let key = inner[..comma_pos].trim().to_string();
                let value = inner[comma_pos + 1..].trim().to_string();
                return Self::Map(key, value);
            }
        }

        // Handle Set<T>
        if trimmed.starts_with("Set<") && trimmed.ends_with('>') {
            let inner = &trimmed[4..trimmed.len() - 1];
            return Self::Set(inner.to_string());
        }

        // Handle Record<K, V>
        if trimmed.starts_with("Record<") && trimmed.ends_with('>') {
            let inner = &trimmed[7..trimmed.len() - 1];
            if let Some(comma_pos) = find_top_level_comma(inner) {
                let key = inner[..comma_pos].trim().to_string();
                let value = inner[comma_pos + 1..].trim().to_string();
                return Self::Record(key, value);
            }
        }

        // Handle union types (T | undefined, T | null)
        // Only split on top-level `|` — pipes inside <>, (), [], or string
        // literals (e.g. Pick<User, 'a' | 'b'>) are ignored.
        if let Some(parts) = split_top_level_union(trimmed) {
            if parts.contains(&"undefined") {
                let non_undefined: Vec<&str> = parts
                    .iter()
                    .filter(|p| *p != &"undefined")
                    .copied()
                    .collect();
                return Self::Optional(non_undefined.join(" | "));
            }
            if parts.contains(&"null") {
                let non_null: Vec<&str> = parts.iter().filter(|p| *p != &"null").copied().collect();
                return Self::Nullable(non_null.join(" | "));
            }
            // Remaining unions (e.g., Utc | number) are not a single serializable type
            return Self::Unknown;
        }

        // Check if it looks like a class/interface name (starts with uppercase)
        // Exclude built-in types and utility types
        if let Some(first_char) = trimmed.chars().next()
            && first_char.is_uppercase()
            && !matches!(
                trimmed,
                "String"
                    | "Number"
                    | "Boolean"
                    | "Object"
                    | "Function"
                    | "Symbol"
                    | "URL"
                    | "URLSearchParams"
                    | "RegExp"
                    | "Error"
                    | "EvalError"
                    | "RangeError"
                    | "ReferenceError"
                    | "SyntaxError"
                    | "TypeError"
                    | "URIError"
                    | "Int8Array"
                    | "Uint8Array"
                    | "Uint8ClampedArray"
                    | "Int16Array"
                    | "Uint16Array"
                    | "Int32Array"
                    | "Uint32Array"
                    | "Float32Array"
                    | "Float64Array"
                    | "BigInt64Array"
                    | "BigUint64Array"
                    | "ArrayBuffer"
                    | "DataView"
            )
        {
            // Extract base type name (handle generics like Foo<T>)
            let base_type = if let Some(idx) = trimmed.find('<') {
                &trimmed[..idx]
            } else {
                trimmed
            };

            // Handle TypeScript wrapper utility types that preserve the inner type's structure
            // These don't change runtime values, so we serialize based on the inner type
            if matches!(
                base_type,
                "Partial" | "Required" | "Readonly" | "NonNullable"
            ) {
                // Single type argument: Partial<T>, Required<T>, Readonly<T>, NonNullable<T>
                if let Some(start) = trimmed.find('<') {
                    let inner = &trimmed[start + 1..trimmed.len() - 1];
                    return Self::Wrapper(inner.to_string());
                }
            }

            if matches!(base_type, "Pick" | "Omit") {
                // Two type arguments: Pick<T, K>, Omit<T, K> - we care about T
                if let Some(start) = trimmed.find('<') {
                    let inner = &trimmed[start + 1..trimmed.len() - 1];
                    if let Some(comma_pos) = find_top_level_comma(inner) {
                        let first_arg = inner[..comma_pos].trim();
                        return Self::Wrapper(first_arg.to_string());
                    }
                }
            }

            // These utility types don't have a meaningful serialization strategy
            // (they operate on function types, unions, or async types)
            if matches!(
                base_type,
                "Exclude"
                    | "Extract"
                    | "ReturnType"
                    | "Parameters"
                    | "InstanceType"
                    | "ThisType"
                    | "Awaited"
                    | "Promise"
            ) {
                return Self::Unknown;
            }

            let base = if let Some(idx) = trimmed.find('<') {
                &trimmed[..idx]
            } else {
                trimmed
            };

            // Dot-qualified types like DateTime.Utc are foreign types handled
            // via match_foreign_type at the field level. Classifying them as
            // Serializable would produce garbled function names (e.g.,
            // "dateTime.utcSerializeWithContext") because to_case(Camel)
            // doesn't handle dots correctly.
            if base.contains('.') {
                return Self::Unknown;
            }

            return Self::Serializable(base.to_string());
        }

        Self::Unknown
    }

    /// Check if a type matches a configured foreign type.
    ///
    /// Attempts to match the type name against the configured foreign types,
    /// checking both exact name matches and imports from configured sources.
    ///
    /// # Arguments
    ///
    /// * `ts_type` - The TypeScript type string (e.g., "DateTime", "ZonedDateTime")
    /// * `foreign_types` - List of configured foreign type handlers
    ///
    /// # Returns
    ///
    /// The matching foreign type configuration, if found.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let foreign_types = vec![ForeignTypeConfig {
    ///     name: "DateTime".to_string(),
    ///     from: vec!["effect".to_string()],
    ///     ..Default::default()
    /// }];
    ///
    /// // Matches by exact name
    /// assert!(TypeCategory::match_foreign_type("DateTime", &foreign_types).is_some());
    ///
    /// // Doesn't match other types
    /// assert!(TypeCategory::match_foreign_type("Date", &foreign_types).is_none());
    /// ```
    /// Match a TypeScript type against configured foreign types with import source validation.
    ///
    /// # Arguments
    ///
    /// * `ts_type` - The TypeScript type string (e.g., "DateTime.DateTime", "Duration")
    /// * `foreign_types` - List of configured foreign type handlers
    ///
    /// # Returns
    ///
    /// A `ForeignTypeMatch` containing the matched config (if any) and potential warnings
    /// about near-matches that failed due to import source validation.
    pub fn match_foreign_type<'a>(
        ts_type: &str,
        foreign_types: &'a [ForeignTypeConfig],
    ) -> ForeignTypeMatch<'a> {
        let trimmed = ts_type.trim();
        let import_sources = with_registry(|r| r.source_modules());
        let import_aliases = with_registry(|r| r.aliases());

        // Skip empty types
        if trimmed.is_empty() {
            return ForeignTypeMatch::none();
        }

        // Extract the base type name (handle generics like Foo<T>)
        let base_type = if let Some(idx) = trimmed.find('<') {
            &trimmed[..idx]
        } else {
            trimmed
        };

        // For qualified types like DateTime.DateTime, extract parts
        let (namespace_part, type_name) = if let Some(dot_idx) = base_type.rfind('.') {
            (Some(&base_type[..dot_idx]), &base_type[dot_idx + 1..])
        } else {
            (None, base_type)
        };

        // Extract the first part of the namespace for import lookup
        // For A.B.C, the import name is A (the first part before any dot)
        let first_namespace_part = namespace_part.map(|ns| {
            if let Some(dot_idx) = ns.find('.') {
                &ns[..dot_idx]
            } else {
                ns
            }
        });

        // Resolve the import name - use first namespace part if qualified, otherwise type_name
        let import_name = first_namespace_part.unwrap_or(type_name);

        // For unqualified types (no namespace), the type_name itself might be an alias
        // e.g., EffectOption -> Option. For qualified types, only the namespace is aliased.
        let resolved_type_name = if namespace_part.is_none() {
            import_aliases
                .get(type_name)
                .map(String::as_str)
                .unwrap_or(type_name)
        } else {
            // For qualified types, the type_name (last part) is not aliased
            type_name
        };

        // For unqualified aliased types, resolve the base_type
        let resolved_base_type = if namespace_part.is_none() {
            import_aliases
                .get(base_type)
                .map(String::as_str)
                .unwrap_or(base_type)
        } else {
            base_type
        };

        // For qualified types, resolve the namespace alias
        // e.g., EffectDateTime.DateTime with import { DateTime as EffectDateTime }
        // should resolve namespace EffectDateTime -> DateTime
        // For A.B.C where A is aliased to X, resolve to X.B.C
        let resolved_namespace: Option<String> = namespace_part.map(|ns| {
            let parts: Vec<&str> = ns.split('.').collect();
            if let Some(first_part) = parts.first() {
                if let Some(resolved_first) = import_aliases.get(*first_part) {
                    // Replace the first part with the resolved alias and rejoin
                    let mut resolved_parts: Vec<&str> = vec![resolved_first.as_str()];
                    resolved_parts.extend(&parts[1..]);
                    resolved_parts.join(".")
                } else {
                    ns.to_string()
                }
            } else {
                ns.to_string()
            }
        });

        let mut near_match: Option<(&ForeignTypeConfig, String)> = None;

        for ft in foreign_types {
            let ft_type_name = ft.get_type_name();
            let ft_namespace = ft.get_namespace();
            let ft_qualified = ft.get_qualified_name();

            // Check if the type name matches (using resolved name for aliased imports)
            let name_matches = type_name == ft_type_name
                || base_type == ft.name
                || base_type == ft_qualified
                || resolved_type_name == ft_type_name
                || resolved_base_type == ft.name
                || resolved_base_type == ft_qualified;

            // Also check namespace matches if both have namespaces
            // Use resolved namespace for aliased imports (e.g., EffectDateTime -> DateTime)
            let namespace_matches = match (namespace_part, ft_namespace) {
                (Some(ns), Some(ft_ns)) => {
                    // Match either original namespace or resolved (aliased) namespace
                    let resolved_ns = resolved_namespace.as_deref().unwrap_or(ns);
                    ns == ft_ns || resolved_ns == ft_ns
                }
                (None, None) => true,
                // If config has namespace but type doesn't, it's not a match
                (None, Some(_)) => false,
                // If type has namespace but config doesn't, require exact base_type match
                (Some(_), None) => base_type == ft.name || resolved_base_type == ft.name,
            };

            if name_matches && namespace_matches {
                // Global types (empty from list) don't need import validation
                if ft.from.is_empty() {
                    return ForeignTypeMatch::matched(ft);
                }
                // Now validate import source
                if let Some(actual_source) = import_sources.get(import_name) {
                    // Check if the actual import source matches any configured source
                    let source_matches = ft.from.iter().any(|configured_source| {
                        actual_source == configured_source
                            || actual_source.ends_with(configured_source)
                            || configured_source.ends_with(actual_source)
                    });

                    if source_matches {
                        // Register required namespace imports for this foreign type
                        register_foreign_type_namespaces(ft, actual_source);
                        return ForeignTypeMatch::matched(ft);
                    }
                    // Type is imported from a different source - don't match
                    // We can't know if that library's type has the right methods
                    // Let it fall through to generic handling; TypeScript will catch issues
                } else {
                    // No import found for this type - likely a local type or re-exported
                    // Don't match foreign type config for types we can't verify the source of
                }
            } else if (type_name == ft_type_name || resolved_type_name == ft_type_name)
                && !name_matches
            {
                // Type name matches but qualified form doesn't - helpful hint
                let warning = format!(
                    "Type '{}' has the same name as foreign type '{}' but uses different qualification. \
                     Expected '{}' or configure with namespace: '{}'.",
                    base_type,
                    ft.name,
                    ft_qualified,
                    namespace_part.unwrap_or(type_name)
                );
                if near_match.is_none() {
                    near_match = Some((ft, warning));
                }
            }

            // Check aliases for this foreign type
            for alias in &ft.aliases {
                // Parse alias name for potential namespace
                let (alias_namespace, alias_type_name) =
                    if let Some(dot_idx) = alias.name.rfind('.') {
                        (Some(&alias.name[..dot_idx]), &alias.name[dot_idx + 1..])
                    } else {
                        (None, alias.name.as_str())
                    };

                // Check if alias name matches the type
                let alias_name_matches = type_name == alias_type_name || base_type == alias.name;

                // Check namespace matches for alias
                let alias_namespace_matches = match (namespace_part, alias_namespace) {
                    (Some(ns), Some(alias_ns)) => ns == alias_ns,
                    (None, None) => true,
                    (None, Some(_)) => false,
                    (Some(_), None) => base_type == alias.name,
                };

                if alias_name_matches && alias_namespace_matches {
                    // Global types (empty from list) don't need import validation
                    if ft.from.is_empty() {
                        return ForeignTypeMatch::matched(ft);
                    }
                    // Validate import source against alias's from
                    let import_name = namespace_part.unwrap_or(type_name);

                    if let Some(actual_source) = import_sources.get(import_name) {
                        // Check if import source matches the alias's from
                        if actual_source == &alias.from
                            || actual_source.ends_with(&alias.from)
                            || alias.from.ends_with(actual_source)
                        {
                            // Register required namespace imports for this foreign type
                            register_foreign_type_namespaces(ft, actual_source);
                            return ForeignTypeMatch::matched(ft);
                        }
                    }
                }
            }
        }

        if let Some((ft, warning)) = near_match {
            ForeignTypeMatch::near_match(ft, warning)
        } else {
            ForeignTypeMatch::none()
        }
    }
}

/// Rewrite namespace references in an expression to use the generated aliases.
///
/// For namespaces that need to be imported (registered via `register_required_namespace`),
/// this function replaces the namespace identifier with its alias.
///
/// For example, if `DateTime` is registered with alias `__mf_DateTime`, then:
/// - `(v) => DateTime.formatIso(v)` becomes `(v) => __mf_DateTime.formatIso(v)`
/// - `DateTime.unsafeNow()` becomes `__mf_DateTime.unsafeNow()`
///
/// # Arguments
/// * `expr` - The expression string to rewrite
///
/// # Returns
/// The rewritten expression string with namespace aliases applied
pub fn rewrite_expression_namespaces(expr: &str) -> String {
    with_registry(|r| {
        let mut result = expr.to_string();
        let mut found_any = false;

        for import in r.generated_imports() {
            if let Some(ref original) = import.original_name
                && !import.is_type_only
            {
                let pattern = format!("{}.", original);
                let replacement = format!("{}.", import.local_name);
                if result.contains(&pattern) {
                    result = result.replace(&pattern, &replacement);
                    found_any = true;
                }
            }
        }

        if !found_any {
            return expr.to_string();
        }

        result
    })
}

/// Register required namespace imports for a matched foreign type.
///
/// Checks each namespace referenced in the foreign type's expressions and determines
/// if it needs to be imported (i.e., if it's not already available as a value import).
///
/// The import source is determined by looking at the config file's imports first
/// (e.g., if the config has `import { DateTime } from "effect"`, we use "effect").
/// This ensures we import from the same place the config uses for its expressions.
///
/// # Arguments
/// * `ft` - The matched foreign type configuration
/// * `import_module` - The module the type is imported from (fallback if not in config)
fn register_foreign_type_namespaces(ft: &ForeignTypeConfig, import_module: &str) {
    with_registry_mut(|r| {
        for ns in &ft.expression_namespaces {
            let has_import = r.is_available(ns);
            let has_config_import = r.config_imports.contains_key(ns);

            if !has_import && !has_config_import {
                continue;
            }

            let is_type_only = r.is_type_only(ns);

            if is_type_only || (!r.source_map().contains_key(ns) && has_config_import) {
                let module = r.config_imports.get(ns).cloned().unwrap_or_else(|| {
                    ft.from
                        .first()
                        .cloned()
                        .unwrap_or_else(|| import_module.to_string())
                });

                let alias = format!("__mf_{}", ns);
                r.request_namespace_import(ns, &module, &alias);
            }
        }

        let type_name = ft.get_type_name();
        if !r.is_available(&ft.name) && !r.is_available(type_name) && !ft.from.is_empty() {
            r.request_type_import(type_name, &ft.from[0]);
        }
    });
}

/// Result of matching a type against foreign type configurations.
#[derive(Debug)]
pub struct ForeignTypeMatch<'a> {
    /// The matched foreign type config, if any.
    pub config: Option<&'a ForeignTypeConfig>,
    /// Warning message for informational hints.
    pub warning: Option<String>,
    /// Error message for import source mismatches (should fail the build).
    pub error: Option<String>,
}

impl<'a> ForeignTypeMatch<'a> {
    /// Create a successful match.
    pub fn matched(config: &'a ForeignTypeConfig) -> Self {
        Self {
            config: Some(config),
            warning: None,
            error: None,
        }
    }

    /// Create an import mismatch error (type matches but import source doesn't).
    /// This should cause a build failure.
    pub fn import_mismatch(_config: &'a ForeignTypeConfig, error: String) -> Self {
        Self {
            config: None,
            warning: None,
            error: Some(error),
        }
    }

    /// Create a near-match (no match, but with a helpful warning).
    /// The config parameter is for API consistency but not stored since this is a non-match.
    pub fn near_match(_config: &'a ForeignTypeConfig, warning: String) -> Self {
        Self {
            config: None,
            warning: Some(warning),
            error: None,
        }
    }

    /// Create an empty result (no match, no warning, no error).
    pub fn none() -> Self {
        Self {
            config: None,
            warning: None,
            error: None,
        }
    }

    /// Returns true if there was a successful match.
    pub fn is_match(&self) -> bool {
        self.config.is_some()
    }

    /// Returns true if there was an error (import source mismatch).
    pub fn has_error(&self) -> bool {
        self.error.is_some()
    }
}

// ============================================================================
// Validator types for field validation
// ============================================================================

/// A single validator with optional custom message
#[derive(Debug, Clone)]
pub struct ValidatorSpec {
    pub validator: Validator,
    pub custom_message: Option<String>,
}

/// All supported validators for field validation during deserialization
#[derive(Debug, Clone, PartialEq)]
pub enum Validator {
    // String validators
    Email,
    Url,
    Uuid,
    MaxLength(usize),
    MinLength(usize),
    Length(usize),
    LengthRange(usize, usize),
    Pattern(String),
    NonEmpty,
    Trimmed,
    Lowercase,
    Uppercase,
    Capitalized,
    Uncapitalized,
    StartsWith(String),
    EndsWith(String),
    Includes(String),

    // Number validators
    GreaterThan(f64),
    GreaterThanOrEqualTo(f64),
    LessThan(f64),
    LessThanOrEqualTo(f64),
    Between(f64, f64),
    Int,
    NonNaN,
    Finite,
    Positive,
    NonNegative,
    Negative,
    NonPositive,
    MultipleOf(f64),
    Uint8,

    // Array validators
    MaxItems(usize),
    MinItems(usize),
    ItemsCount(usize),

    // Date validators
    ValidDate,
    GreaterThanDate(String),
    GreaterThanOrEqualToDate(String),
    LessThanDate(String),
    LessThanOrEqualToDate(String),
    BetweenDate(String, String),

    // BigInt validators
    GreaterThanBigInt(String),
    GreaterThanOrEqualToBigInt(String),
    LessThanBigInt(String),
    LessThanOrEqualToBigInt(String),
    BetweenBigInt(String, String),
    PositiveBigInt,
    NonNegativeBigInt,
    NegativeBigInt,
    NonPositiveBigInt,

    // Custom validator
    Custom(String),
}

// ============================================================================
// Validator parsing errors
// ============================================================================

/// Error information from parsing a validator string
#[derive(Debug, Clone)]
pub struct ValidatorParseError {
    pub message: String,
    pub help: Option<String>,
}

impl ValidatorParseError {
    /// Create error for an unknown validator name
    pub fn unknown_validator(name: &str) -> Self {
        let similar = find_similar_validator(name);
        Self {
            message: format!("unknown validator '{}'", name),
            help: similar.map(|s| format!("did you mean '{}'?", s)),
        }
    }

    /// Create error for invalid arguments
    pub fn invalid_args(name: &str, reason: &str) -> Self {
        Self {
            message: format!("invalid arguments for '{}': {}", name, reason),
            help: None,
        }
    }
}

/// List of all known validator names for typo detection
const KNOWN_VALIDATORS: &[&str] = &[
    "email",
    "url",
    "uuid",
    "maxLength",
    "minLength",
    "length",
    "pattern",
    "nonEmpty",
    "trimmed",
    "lowercase",
    "uppercase",
    "capitalized",
    "uncapitalized",
    "startsWith",
    "endsWith",
    "includes",
    "greaterThan",
    "greaterThanOrEqualTo",
    "lessThan",
    "lessThanOrEqualTo",
    "between",
    "int",
    "nonNaN",
    "finite",
    "positive",
    "nonNegative",
    "negative",
    "nonPositive",
    "multipleOf",
    "uint8",
    "maxItems",
    "minItems",
    "itemsCount",
    "validDate",
    "greaterThanDate",
    "greaterThanOrEqualToDate",
    "lessThanDate",
    "lessThanOrEqualToDate",
    "betweenDate",
    "positiveBigInt",
    "nonNegativeBigInt",
    "negativeBigInt",
    "nonPositiveBigInt",
    "greaterThanBigInt",
    "greaterThanOrEqualToBigInt",
    "lessThanBigInt",
    "lessThanOrEqualToBigInt",
    "betweenBigInt",
    "custom",
];

/// Find a similar validator name for typo suggestions using Levenshtein distance
fn find_similar_validator(name: &str) -> Option<&'static str> {
    let name_lower = name.to_lowercase();
    KNOWN_VALIDATORS
        .iter()
        .filter_map(|v| {
            let dist = levenshtein_distance(&v.to_lowercase(), &name_lower);
            if dist <= 2 { Some((*v, dist)) } else { None }
        })
        .min_by_key(|(_, dist)| *dist)
        .map(|(v, _)| v)
}

/// Calculate Levenshtein distance between two strings
fn levenshtein_distance(a: &str, b: &str) -> usize {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let len_a = a_chars.len();
    let len_b = b_chars.len();

    if len_a == 0 {
        return len_b;
    }
    if len_b == 0 {
        return len_a;
    }

    let mut prev_row: Vec<usize> = (0..=len_b).collect();
    let mut curr_row: Vec<usize> = vec![0; len_b + 1];

    for i in 1..=len_a {
        curr_row[0] = i;
        for j in 1..=len_b {
            let cost = if a_chars[i - 1] == b_chars[j - 1] {
                0
            } else {
                1
            };
            curr_row[j] = (prev_row[j] + 1)
                .min(curr_row[j - 1] + 1)
                .min(prev_row[j - 1] + cost);
        }
        std::mem::swap(&mut prev_row, &mut curr_row);
    }
    prev_row[len_b]
}

// ============================================================================
// Helper functions (adapted from derive_debug.rs)
// ============================================================================

pub fn has_flag(args: &str, flag: &str) -> bool {
    if flag_explicit_false(args, flag) {
        return false;
    }

    args.split(|c: char| !c.is_alphanumeric() && c != '_')
        .any(|token| token.eq_ignore_ascii_case(flag))
}

fn flag_explicit_false(args: &str, flag: &str) -> bool {
    let lower = args.to_ascii_lowercase();
    let condensed: String = lower.chars().filter(|c| !c.is_whitespace()).collect();
    condensed.contains(&format!("{flag}:false")) || condensed.contains(&format!("{flag}=false"))
}

pub fn extract_named_string(args: &str, name: &str) -> Option<String> {
    let lower = args.to_ascii_lowercase();
    let name_lower = name.to_ascii_lowercase();

    // Find all occurrences and check for whole-word match
    let mut search_start = 0;
    while let Some(relative_idx) = lower[search_start..].find(&name_lower) {
        let idx = search_start + relative_idx;

        // Check that we're at a word boundary (not part of a larger identifier)
        // The character before must be non-alphanumeric (or we're at the start)
        let at_word_start = idx == 0 || {
            let prev_char = lower.chars().nth(idx - 1).unwrap_or(' ');
            !prev_char.is_alphanumeric() && prev_char != '_'
        };

        if at_word_start {
            let remainder = &args[idx + name.len()..];
            let remainder = remainder.trim_start();

            if remainder.starts_with(':') || remainder.starts_with('=') {
                let value = remainder[1..].trim_start();
                return parse_string_literal(value);
            }

            if remainder.starts_with('(')
                && let Some(close) = remainder.rfind(')')
            {
                let inner = remainder[1..close].trim();
                return parse_string_literal(inner);
            }
        }

        // Continue searching from after this match
        search_start = idx + 1;
    }

    None
}

fn parse_string_literal(input: &str) -> Option<String> {
    let trimmed = input.trim();
    let mut chars = trimmed.chars();
    let quote = chars.next()?;
    if quote != '"' && quote != '\'' {
        return None;
    }

    let mut escaped = false;
    let mut buf = String::new();
    for c in chars {
        if escaped {
            buf.push(c);
            escaped = false;
            continue;
        }
        if c == '\\' {
            escaped = true;
            continue;
        }
        if c == quote {
            return Some(buf);
        }
        buf.push(c);
    }
    None
}

/// Find the position of a comma at the top level (not inside <> brackets)
pub(super) fn find_top_level_comma(s: &str) -> Option<usize> {
    let mut depth = 0;
    for (i, c) in s.char_indices() {
        match c {
            '<' => depth += 1,
            '>' => depth -= 1,
            ',' if depth == 0 => return Some(i),
            _ => {}
        }
    }
    None
}

/// Split a type string on `|` at the top level only.
///
/// Respects `<>`, `()`, `[]` nesting and string literals (`'...'`, `"..."`),
/// so `Pick<User, 'name' | 'email'>` is **not** split on the `|` inside the
/// angle brackets.  Returns `None` when no top-level `|` exists.
pub(crate) fn split_top_level_union(s: &str) -> Option<Vec<&str>> {
    let mut parts = Vec::new();
    let mut depth = 0usize;
    let mut in_string = false;
    let mut string_char = '"';
    let mut start = 0;
    let mut found_pipe = false;

    for (i, c) in s.char_indices() {
        if in_string {
            if c == string_char {
                in_string = false;
            }
            continue;
        }
        match c {
            '\'' | '"' => {
                in_string = true;
                string_char = c;
            }
            '<' | '(' | '[' | '{' => depth += 1,
            '>' | ')' | ']' | '}' => depth = depth.saturating_sub(1),
            '|' if depth == 0 => {
                parts.push(s[start..i].trim());
                start = i + 1;
                found_pipe = true;
            }
            _ => {}
        }
    }

    if !found_pipe {
        return None;
    }
    parts.push(s[start..].trim());
    Some(parts)
}

// ============================================================================
// Validator parsing functions
// ============================================================================

/// Known options that are NOT validators (to avoid false positives)
const KNOWN_OPTIONS: &[&str] = &[
    "skip",
    "skipSerializing",
    "skipDeserializing",
    "flatten",
    "default",
    "rename",
    "validate",
    "message",
    "serializeWith",
    "deserializeWith",
    "format",
];

/// Extract validators from decorator arguments with diagnostic collection
/// Supports:
/// - Explicit array: validate: ["email", "maxLength(255)"]
/// - Object array: validate: [{ validate: "email", message: "..." }]
/// - Shorthand: @serde(email) or @serde(minLength(2), maxLength(50))
pub fn extract_validators(
    args: &str,
    decorator_span: SpanIR,
    field_name: &str,
    diagnostics: &mut DiagnosticCollector,
) -> Vec<ValidatorSpec> {
    let mut validators = Vec::new();

    // First, check for explicit validate: [...] format
    let lower = args.to_ascii_lowercase();
    if let Some(idx) = lower.find("validate") {
        let remainder = &args[idx + 8..].trim_start();
        if remainder.starts_with(':') || remainder.starts_with('=') {
            let value_start = &remainder[1..].trim_start();
            if value_start.starts_with('[') {
                return parse_validator_array(value_start, decorator_span, field_name, diagnostics);
            } else {
                diagnostics.error(
                    decorator_span,
                    format!(
                        "field '{}': validate must be an array, e.g., validate: [\"email\"]",
                        field_name
                    ),
                );
                return validators;
            }
        }
    }

    // Parse shorthand validators: @serde(email) or @serde(minLength(2), maxLength(50))
    for item in split_decorator_args(args) {
        let item = item.trim();
        if item.is_empty() {
            continue;
        }

        // Skip known options
        let item_lower = item.to_ascii_lowercase();
        let base_name = item_lower.split('(').next().unwrap_or(&item_lower);
        let base_name = base_name.split(':').next().unwrap_or(base_name).trim();

        if KNOWN_OPTIONS.contains(&base_name) {
            continue;
        }

        // Check if this looks like a validator (either a known name or has function syntax)
        let is_likely_validator = KNOWN_VALIDATORS.contains(&base_name) || item.contains('('); // Function-like syntax suggests validator

        if is_likely_validator {
            match parse_validator_string(item) {
                Ok(v) => validators.push(ValidatorSpec {
                    validator: v,
                    custom_message: None,
                }),
                Err(err) => {
                    if let Some(help) = err.help {
                        diagnostics.error_with_help(
                            decorator_span,
                            format!("field '{}': {}", field_name, err.message),
                            help,
                        );
                    } else {
                        diagnostics.error(
                            decorator_span,
                            format!("field '{}': {}", field_name, err.message),
                        );
                    }
                }
            }
        }
    }

    validators
}

/// Split decorator arguments by commas, respecting nested parentheses and strings
fn split_decorator_args(input: &str) -> Vec<String> {
    let mut items = Vec::new();
    let mut current = String::new();
    let mut depth = 0;
    let mut in_string = false;
    let mut string_char = '"';

    for c in input.chars() {
        if in_string {
            current.push(c);
            if c == string_char {
                in_string = false;
            }
            continue;
        }

        match c {
            '"' | '\'' => {
                in_string = true;
                string_char = c;
                current.push(c);
            }
            '(' | '[' | '{' => {
                depth += 1;
                current.push(c);
            }
            ')' | ']' | '}' => {
                depth -= 1;
                current.push(c);
            }
            ',' if depth == 0 => {
                let trimmed = current.trim().to_string();
                if !trimmed.is_empty() {
                    items.push(trimmed);
                }
                current.clear();
            }
            _ => current.push(c),
        }
    }

    let trimmed = current.trim().to_string();
    if !trimmed.is_empty() {
        items.push(trimmed);
    }

    items
}

/// Parse array content: ["email", "maxLength(255)", { validate: "...", message: "..." }]
fn parse_validator_array(
    input: &str,
    decorator_span: SpanIR,
    field_name: &str,
    diagnostics: &mut DiagnosticCollector,
) -> Vec<ValidatorSpec> {
    let mut validators = Vec::new();

    // Find matching ] bracket
    let Some(content) = extract_bracket_content(input, '[', ']') else {
        diagnostics.error(
            decorator_span,
            format!("field '{}': malformed validator array", field_name),
        );
        return validators;
    };

    // Split by commas (respecting nested structures)
    for item in split_array_items(&content) {
        let item = item.trim();
        if item.starts_with('{') {
            // Object form: { validate: "...", message: "..." }
            match parse_validator_object(item) {
                Ok(spec) => validators.push(spec),
                Err(err) => {
                    if let Some(help) = err.help {
                        diagnostics.error_with_help(
                            decorator_span,
                            format!("field '{}': {}", field_name, err.message),
                            help,
                        );
                    } else {
                        diagnostics.error(
                            decorator_span,
                            format!("field '{}': {}", field_name, err.message),
                        );
                    }
                }
            }
        } else if item.starts_with('"') || item.starts_with('\'') {
            // String form: "email" or "maxLength(255)"
            if let Some(s) = parse_string_literal(item) {
                match parse_validator_string(&s) {
                    Ok(v) => validators.push(ValidatorSpec {
                        validator: v,
                        custom_message: None,
                    }),
                    Err(err) => {
                        if let Some(help) = err.help {
                            diagnostics.error_with_help(
                                decorator_span,
                                format!("field '{}': {}", field_name, err.message),
                                help,
                            );
                        } else {
                            diagnostics.error(
                                decorator_span,
                                format!("field '{}': {}", field_name, err.message),
                            );
                        }
                    }
                }
            }
        }
    }
    validators
}

/// Extract content between matching brackets
fn extract_bracket_content(input: &str, open: char, close: char) -> Option<String> {
    let mut depth = 0;
    let mut start = None;

    for (i, c) in input.char_indices() {
        if c == open {
            if depth == 0 {
                start = Some(i + 1);
            }
            depth += 1;
        } else if c == close {
            depth -= 1;
            if depth == 0
                && let Some(s) = start
            {
                return Some(input[s..i].to_string());
            }
        }
    }
    None
}

/// Split array items by commas, respecting nested brackets and strings
fn split_array_items(input: &str) -> Vec<String> {
    let mut items = Vec::new();
    let mut current = String::new();
    let mut depth = 0;
    let mut in_string = false;
    let mut string_char = '"';

    for c in input.chars() {
        if in_string {
            current.push(c);
            if c == string_char {
                in_string = false;
            }
            continue;
        }

        match c {
            '"' | '\'' => {
                in_string = true;
                string_char = c;
                current.push(c);
            }
            '[' | '{' | '(' => {
                depth += 1;
                current.push(c);
            }
            ']' | '}' | ')' => {
                depth -= 1;
                current.push(c);
            }
            ',' if depth == 0 => {
                let trimmed = current.trim().to_string();
                if !trimmed.is_empty() {
                    items.push(trimmed);
                }
                current.clear();
            }
            _ => current.push(c),
        }
    }

    let trimmed = current.trim().to_string();
    if !trimmed.is_empty() {
        items.push(trimmed);
    }

    items
}

/// Parse object form: { validate: "email", message: "Invalid email" }
fn parse_validator_object(input: &str) -> Result<ValidatorSpec, ValidatorParseError> {
    let content = extract_bracket_content(input, '{', '}')
        .ok_or_else(|| ValidatorParseError::invalid_args("object", "malformed validator object"))?;

    let validator_str = extract_named_string(&content, "validate")
        .ok_or_else(|| ValidatorParseError::invalid_args("object", "missing 'validate' field"))?;
    let validator = parse_validator_string(&validator_str)?;
    let custom_message = extract_named_string(&content, "message");

    Ok(ValidatorSpec {
        validator,
        custom_message,
    })
}

/// Parse a validator string like "email", "maxLength(255)", "custom(myValidator)"
fn parse_validator_string(s: &str) -> Result<Validator, ValidatorParseError> {
    let trimmed = s.trim();

    // Check for function-call style: name(args)
    if let Some(paren_idx) = trimmed.find('(') {
        let name = &trimmed[..paren_idx];
        let Some(args_end) = trimmed.rfind(')') else {
            return Err(ValidatorParseError::invalid_args(
                name,
                "missing closing parenthesis",
            ));
        };
        let args = &trimmed[paren_idx + 1..args_end];
        return parse_validator_with_args(name, args);
    }

    // Simple validators without args
    match trimmed.to_lowercase().as_str() {
        "email" => Ok(Validator::Email),
        "url" => Ok(Validator::Url),
        "uuid" => Ok(Validator::Uuid),
        "nonempty" | "nonemptystring" => Ok(Validator::NonEmpty),
        "trimmed" => Ok(Validator::Trimmed),
        "lowercase" | "lowercased" => Ok(Validator::Lowercase),
        "uppercase" | "uppercased" => Ok(Validator::Uppercase),
        "capitalized" => Ok(Validator::Capitalized),
        "uncapitalized" => Ok(Validator::Uncapitalized),
        "int" => Ok(Validator::Int),
        "nonnan" => Ok(Validator::NonNaN),
        "finite" => Ok(Validator::Finite),
        "positive" => Ok(Validator::Positive),
        "nonnegative" => Ok(Validator::NonNegative),
        "negative" => Ok(Validator::Negative),
        "nonpositive" => Ok(Validator::NonPositive),
        "uint8" => Ok(Validator::Uint8),
        "validdate" | "validdatefromself" => Ok(Validator::ValidDate),
        "positivebigint" | "positivebigintfromself" => Ok(Validator::PositiveBigInt),
        "nonnegativebigint" | "nonnegativebigintfromself" => Ok(Validator::NonNegativeBigInt),
        "negativebigint" | "negativebigintfromself" => Ok(Validator::NegativeBigInt),
        "nonpositivebigint" | "nonpositivebigintfromself" => Ok(Validator::NonPositiveBigInt),
        "nonnegativeint" => Ok(Validator::Int), // Int + NonNegative combined
        _ => Err(ValidatorParseError::unknown_validator(trimmed)),
    }
}

/// Parse validators with arguments
fn parse_validator_with_args(name: &str, args: &str) -> Result<Validator, ValidatorParseError> {
    let name_lower = name.to_lowercase();
    match name_lower.as_str() {
        "maxlength" => args
            .trim()
            .parse()
            .map(Validator::MaxLength)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a positive integer")),
        "minlength" => args
            .trim()
            .parse()
            .map(Validator::MinLength)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a positive integer")),
        "length" => {
            let parts: Vec<&str> = args.split(',').collect();
            match parts.len() {
                1 => parts[0].trim().parse().map(Validator::Length).map_err(|_| {
                    ValidatorParseError::invalid_args(name, "expected a positive integer")
                }),
                2 => {
                    let min = parts[0].trim().parse().map_err(|_| {
                        ValidatorParseError::invalid_args(name, "expected two positive integers")
                    })?;
                    let max = parts[1].trim().parse().map_err(|_| {
                        ValidatorParseError::invalid_args(name, "expected two positive integers")
                    })?;
                    Ok(Validator::LengthRange(min, max))
                }
                _ => Err(ValidatorParseError::invalid_args(
                    name,
                    "expected 1 or 2 arguments",
                )),
            }
        }
        "pattern" => parse_validator_string_arg(args)
            .map(Validator::Pattern)
            .ok_or_else(|| ValidatorParseError::invalid_args(name, "expected a string pattern")),
        "startswith" => parse_validator_string_arg(args)
            .map(Validator::StartsWith)
            .ok_or_else(|| ValidatorParseError::invalid_args(name, "expected a string")),
        "endswith" => parse_validator_string_arg(args)
            .map(Validator::EndsWith)
            .ok_or_else(|| ValidatorParseError::invalid_args(name, "expected a string")),
        "includes" => parse_validator_string_arg(args)
            .map(Validator::Includes)
            .ok_or_else(|| ValidatorParseError::invalid_args(name, "expected a string")),
        "greaterthan" => args
            .trim()
            .parse()
            .map(Validator::GreaterThan)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a number")),
        "greaterthanorequalto" => args
            .trim()
            .parse()
            .map(Validator::GreaterThanOrEqualTo)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a number")),
        "lessthan" => args
            .trim()
            .parse()
            .map(Validator::LessThan)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a number")),
        "lessthanorequalto" => args
            .trim()
            .parse()
            .map(Validator::LessThanOrEqualTo)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a number")),
        "between" => {
            let parts: Vec<&str> = args.split(',').collect();
            if parts.len() == 2 {
                let min = parts[0]
                    .trim()
                    .parse()
                    .map_err(|_| ValidatorParseError::invalid_args(name, "expected two numbers"))?;
                let max = parts[1]
                    .trim()
                    .parse()
                    .map_err(|_| ValidatorParseError::invalid_args(name, "expected two numbers"))?;
                Ok(Validator::Between(min, max))
            } else {
                Err(ValidatorParseError::invalid_args(
                    name,
                    "expected two numbers separated by comma",
                ))
            }
        }
        "multipleof" => args
            .trim()
            .parse()
            .map(Validator::MultipleOf)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a number")),
        "maxitems" => args
            .trim()
            .parse()
            .map(Validator::MaxItems)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a positive integer")),
        "minitems" => args
            .trim()
            .parse()
            .map(Validator::MinItems)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a positive integer")),
        "itemscount" => args
            .trim()
            .parse()
            .map(Validator::ItemsCount)
            .map_err(|_| ValidatorParseError::invalid_args(name, "expected a positive integer")),
        "greaterthandate" => parse_validator_string_arg(args)
            .map(Validator::GreaterThanDate)
            .ok_or_else(|| ValidatorParseError::invalid_args(name, "expected a date string")),
        "greaterthanorequaltodate" => parse_validator_string_arg(args)
            .map(Validator::GreaterThanOrEqualToDate)
            .ok_or_else(|| ValidatorParseError::invalid_args(name, "expected a date string")),
        "lessthandate" => parse_validator_string_arg(args)
            .map(Validator::LessThanDate)
            .ok_or_else(|| ValidatorParseError::invalid_args(name, "expected a date string")),
        "lessthanorequaltodate" => parse_validator_string_arg(args)
            .map(Validator::LessThanOrEqualToDate)
            .ok_or_else(|| ValidatorParseError::invalid_args(name, "expected a date string")),
        "betweendate" => {
            let parts: Vec<&str> = args.splitn(2, ',').collect();
            if parts.len() == 2 {
                let min = parse_validator_string_arg(parts[0].trim()).ok_or_else(|| {
                    ValidatorParseError::invalid_args(name, "expected two date strings")
                })?;
                let max = parse_validator_string_arg(parts[1].trim()).ok_or_else(|| {
                    ValidatorParseError::invalid_args(name, "expected two date strings")
                })?;
                Ok(Validator::BetweenDate(min, max))
            } else {
                Err(ValidatorParseError::invalid_args(
                    name,
                    "expected two date strings separated by comma",
                ))
            }
        }
        "greaterthanbigint" => Ok(Validator::GreaterThanBigInt(args.trim().to_string())),
        "greaterthanorequaltobigint" => Ok(Validator::GreaterThanOrEqualToBigInt(
            args.trim().to_string(),
        )),
        "lessthanbigint" => Ok(Validator::LessThanBigInt(args.trim().to_string())),
        "lessthanorequaltobigint" => {
            Ok(Validator::LessThanOrEqualToBigInt(args.trim().to_string()))
        }
        "betweenbigint" => {
            let parts: Vec<&str> = args.splitn(2, ',').collect();
            if parts.len() == 2 {
                Ok(Validator::BetweenBigInt(
                    parts[0].trim().to_string(),
                    parts[1].trim().to_string(),
                ))
            } else {
                Err(ValidatorParseError::invalid_args(
                    name,
                    "expected two bigint values separated by comma",
                ))
            }
        }
        "custom" => {
            // custom(myValidator) - extract function name (can be quoted or unquoted)
            let fn_name =
                parse_validator_string_arg(args).unwrap_or_else(|| args.trim().to_string());
            Ok(Validator::Custom(fn_name))
        }
        _ => Err(ValidatorParseError::unknown_validator(name)),
    }
}

/// Parse a string argument (handles both quoted and unquoted)
fn parse_validator_string_arg(input: &str) -> Option<String> {
    let trimmed = input.trim();
    // Try to parse as quoted string first
    if let Some(s) = parse_string_literal(trimmed) {
        return Some(s);
    }
    // Otherwise return as-is if not empty
    if !trimmed.is_empty() {
        return Some(trimmed.to_string());
    }
    None
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ts_syn::abi::SpanIR;

    fn span() -> SpanIR {
        SpanIR::new(0, 0)
    }

    fn make_decorator(args: &str) -> DecoratorIR {
        DecoratorIR {
            name: "serde".into(),
            args_src: args.into(),
            span: span(),
            node: None,
        }
    }

    #[test]
    fn test_field_skip() {
        let decorator = make_decorator("skip");
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert!(opts.skip);
        assert!(!opts.should_serialize());
        assert!(!opts.should_deserialize());
    }

    #[test]
    fn test_field_skip_serializing() {
        let decorator = make_decorator("skipSerializing");
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert!(opts.skip_serializing);
        assert!(!opts.should_serialize());
        assert!(opts.should_deserialize());
    }

    #[test]
    fn test_field_rename() {
        let decorator = make_decorator(r#"{ rename: "user_id" }"#);
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert_eq!(opts.rename.as_deref(), Some("user_id"));
    }

    #[test]
    fn test_field_default_flag() {
        let decorator = make_decorator("default");
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert!(opts.default);
        assert!(opts.default_expr.is_none());
    }

    #[test]
    fn test_field_default_expr() {
        let decorator = make_decorator(r#"{ default: "new Date()" }"#);
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert!(opts.default);
        assert_eq!(opts.default_expr.as_deref(), Some("new Date()"));
    }

    #[test]
    fn test_field_flatten() {
        let decorator = make_decorator("flatten");
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert!(opts.flatten);
    }

    #[test]
    fn test_container_rename_all() {
        let decorator = make_decorator(r#"{ renameAll: "camelCase" }"#);
        let opts = SerdeContainerOptions::from_decorators(&[decorator]);
        assert_eq!(opts.rename_all, RenameAll::CamelCase);
    }

    #[test]
    fn test_container_deny_unknown_fields() {
        let decorator = make_decorator("denyUnknownFields");
        let opts = SerdeContainerOptions::from_decorators(&[decorator]);
        assert!(opts.deny_unknown_fields);
    }

    #[test]
    fn test_container_tag_internally_tagged() {
        let decorator = make_decorator(r#"{ tag: "type" }"#);
        let opts = SerdeContainerOptions::from_decorators(&[decorator]);
        assert_eq!(
            opts.tagging,
            TaggingMode::InternallyTagged {
                tag: "type".to_string()
            }
        );
        assert_eq!(opts.tag_field(), Some("type"));
        assert_eq!(opts.tag_field_or_default(), "type");
        assert_eq!(opts.content_field(), None);
    }

    #[test]
    fn test_container_tag_default() {
        let opts = SerdeContainerOptions::default();
        assert_eq!(
            opts.tagging,
            TaggingMode::InternallyTagged {
                tag: "__type".to_string()
            }
        );
        assert_eq!(opts.tag_field(), Some("__type"));
        assert_eq!(opts.tag_field_or_default(), "__type");
    }

    #[test]
    fn test_container_externally_tagged() {
        let decorator = make_decorator(r#"{ externallyTagged: true }"#);
        let opts = SerdeContainerOptions::from_decorators(&[decorator]);
        assert_eq!(opts.tagging, TaggingMode::ExternallyTagged);
        assert_eq!(opts.tag_field(), None);
        assert_eq!(opts.tag_field_or_default(), "__type");
    }

    #[test]
    fn test_container_adjacently_tagged() {
        let decorator = make_decorator(r#"{ tag: "t", content: "c" }"#);
        let opts = SerdeContainerOptions::from_decorators(&[decorator]);
        assert_eq!(
            opts.tagging,
            TaggingMode::AdjacentlyTagged {
                tag: "t".to_string(),
                content: "c".to_string()
            }
        );
        assert_eq!(opts.tag_field(), Some("t"));
        assert_eq!(opts.tag_field_or_default(), "t");
        assert_eq!(opts.content_field(), Some("c"));
    }

    #[test]
    fn test_container_untagged() {
        let decorator = make_decorator(r#"{ untagged: true }"#);
        let opts = SerdeContainerOptions::from_decorators(&[decorator]);
        assert_eq!(opts.tagging, TaggingMode::Untagged);
        assert_eq!(opts.tag_field(), None);
        assert_eq!(opts.tag_field_or_default(), "__type");
        assert_eq!(opts.content_field(), None);
    }

    #[test]
    fn test_type_category_primitives() {
        assert_eq!(
            TypeCategory::from_ts_type("string"),
            TypeCategory::Primitive
        );
        assert_eq!(
            TypeCategory::from_ts_type("number"),
            TypeCategory::Primitive
        );
        assert_eq!(
            TypeCategory::from_ts_type("boolean"),
            TypeCategory::Primitive
        );
    }

    #[test]
    fn test_type_category_date() {
        assert_eq!(TypeCategory::from_ts_type("Date"), TypeCategory::Date);
    }

    #[test]
    fn test_type_category_array() {
        assert_eq!(
            TypeCategory::from_ts_type("string[]"),
            TypeCategory::Array("string".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("Array<number>"),
            TypeCategory::Array("number".into())
        );
    }

    #[test]
    fn test_type_category_map() {
        assert_eq!(
            TypeCategory::from_ts_type("Map<string, number>"),
            TypeCategory::Map("string".into(), "number".into())
        );
    }

    #[test]
    fn test_type_category_set() {
        assert_eq!(
            TypeCategory::from_ts_type("Set<string>"),
            TypeCategory::Set("string".into())
        );
    }

    #[test]
    fn test_type_category_optional() {
        assert_eq!(
            TypeCategory::from_ts_type("string | undefined"),
            TypeCategory::Optional("string".into())
        );
    }

    #[test]
    fn test_type_category_nullable() {
        assert_eq!(
            TypeCategory::from_ts_type("string | null"),
            TypeCategory::Nullable("string".into())
        );
    }

    #[test]
    fn test_type_category_serializable() {
        assert_eq!(
            TypeCategory::from_ts_type("User"),
            TypeCategory::Serializable("User".into())
        );
    }

    #[test]
    fn test_type_category_serializable_strips_generics() {
        // Generic type parameters must be stripped from the Serializable variant
        // so they don't leak into generated function names.
        assert_eq!(
            TypeCategory::from_ts_type("RecordLink<Employee>"),
            TypeCategory::Serializable("RecordLink".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("RecordLink<Account>"),
            TypeCategory::Serializable("RecordLink".into())
        );
    }

    #[test]
    fn test_convert_case_with_angle_brackets() {
        use convert_case::{Case, Casing};
        // Generics must be stripped before camelCase conversion since `<>` chars
        // are not recognized as word boundaries by convert_case.
        let base = "RecordLink";
        let fn_name = format!("{}SerializeWithContext", base.to_case(Case::Camel));
        assert_eq!(fn_name, "recordLinkSerializeWithContext");
    }

    #[test]
    fn test_rename_all_camel_case() {
        assert_eq!(RenameAll::CamelCase.apply("user_name"), "userName");
        assert_eq!(RenameAll::CamelCase.apply("created_at"), "createdAt");
    }

    #[test]
    fn test_rename_all_snake_case() {
        assert_eq!(RenameAll::SnakeCase.apply("userName"), "user_name");
        assert_eq!(RenameAll::SnakeCase.apply("createdAt"), "created_at");
    }

    #[test]
    fn test_rename_all_pascal_case() {
        assert_eq!(RenameAll::PascalCase.apply("user_name"), "UserName");
    }

    #[test]
    fn test_rename_all_kebab_case() {
        assert_eq!(RenameAll::KebabCase.apply("userName"), "user-name");
    }

    #[test]
    fn test_rename_all_screaming_snake_case() {
        assert_eq!(RenameAll::ScreamingSnakeCase.apply("userName"), "USER_NAME");
    }

    // ========================================================================
    // Validator parsing tests
    // ========================================================================

    #[test]
    fn test_parse_simple_validators() {
        assert!(matches!(
            parse_validator_string("email"),
            Ok(Validator::Email)
        ));
        assert!(matches!(parse_validator_string("url"), Ok(Validator::Url)));
        assert!(matches!(
            parse_validator_string("uuid"),
            Ok(Validator::Uuid)
        ));
        assert!(matches!(
            parse_validator_string("nonEmpty"),
            Ok(Validator::NonEmpty)
        ));
        assert!(matches!(
            parse_validator_string("trimmed"),
            Ok(Validator::Trimmed)
        ));
        assert!(matches!(
            parse_validator_string("lowercase"),
            Ok(Validator::Lowercase)
        ));
        assert!(matches!(
            parse_validator_string("uppercase"),
            Ok(Validator::Uppercase)
        ));
        assert!(matches!(parse_validator_string("int"), Ok(Validator::Int)));
        assert!(matches!(
            parse_validator_string("positive"),
            Ok(Validator::Positive)
        ));
        assert!(matches!(
            parse_validator_string("validDate"),
            Ok(Validator::ValidDate)
        ));
    }

    #[test]
    fn test_parse_validators_with_args() {
        assert!(matches!(
            parse_validator_string("maxLength(255)"),
            Ok(Validator::MaxLength(255))
        ));
        assert!(matches!(
            parse_validator_string("minLength(1)"),
            Ok(Validator::MinLength(1))
        ));
        assert!(matches!(
            parse_validator_string("length(36)"),
            Ok(Validator::Length(36))
        ));
        assert!(matches!(
            parse_validator_string("between(0, 100)"),
            Ok(Validator::Between(min, max)) if min == 0.0 && max == 100.0
        ));
        assert!(matches!(
            parse_validator_string("greaterThan(5)"),
            Ok(Validator::GreaterThan(n)) if n == 5.0
        ));
    }

    #[test]
    fn test_parse_validators_with_string_args() {
        assert!(matches!(
            parse_validator_string(r#"startsWith("https://")"#),
            Ok(Validator::StartsWith(s)) if s == "https://"
        ));
        assert!(matches!(
            parse_validator_string(r#"endsWith(".com")"#),
            Ok(Validator::EndsWith(s)) if s == ".com"
        ));
        assert!(matches!(
            parse_validator_string(r#"includes("@")"#),
            Ok(Validator::Includes(s)) if s == "@"
        ));
    }

    #[test]
    fn test_parse_custom_validator() {
        assert!(matches!(
            parse_validator_string("custom(myValidator)"),
            Ok(Validator::Custom(fn_name)) if fn_name == "myValidator"
        ));
    }

    #[test]
    fn test_extract_validators_from_args() {
        let mut diagnostics = DiagnosticCollector::new();
        let validators = extract_validators(
            r#"{ validate: ["email", "maxLength(255)"] }"#,
            span(),
            "test_field",
            &mut diagnostics,
        );
        assert_eq!(validators.len(), 2);
        assert!(matches!(validators[0].validator, Validator::Email));
        assert!(matches!(validators[1].validator, Validator::MaxLength(255)));
        assert!(!diagnostics.has_errors());
    }

    #[test]
    fn test_extract_validators_with_message() {
        let mut diagnostics = DiagnosticCollector::new();
        let validators = extract_validators(
            r#"{ validate: [{ validate: "email", message: "Invalid email!" }] }"#,
            span(),
            "test_field",
            &mut diagnostics,
        );
        assert_eq!(validators.len(), 1);
        assert!(matches!(validators[0].validator, Validator::Email));
        assert_eq!(
            validators[0].custom_message.as_deref(),
            Some("Invalid email!")
        );
        assert!(!diagnostics.has_errors());
    }

    #[test]
    fn test_extract_validators_mixed() {
        let mut diagnostics = DiagnosticCollector::new();
        let validators = extract_validators(
            r#"{ validate: ["nonEmpty", { validate: "email", message: "Bad email" }] }"#,
            span(),
            "test_field",
            &mut diagnostics,
        );
        assert_eq!(validators.len(), 2);
        assert!(matches!(validators[0].validator, Validator::NonEmpty));
        assert!(validators[0].custom_message.is_none());
        assert!(matches!(validators[1].validator, Validator::Email));
        assert_eq!(validators[1].custom_message.as_deref(), Some("Bad email"));
        assert!(!diagnostics.has_errors());
    }

    #[test]
    fn test_field_with_validators() {
        let decorator = make_decorator(r#"{ validate: ["email", "maxLength(255)"] }"#);
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert_eq!(opts.validators.len(), 2);
        assert!(matches!(opts.validators[0].validator, Validator::Email));
        assert!(matches!(
            opts.validators[1].validator,
            Validator::MaxLength(255)
        ));
    }

    // ========================================================================
    // Date validator parsing tests
    // ========================================================================

    #[test]
    fn test_parse_date_validators() {
        assert!(matches!(
            parse_validator_string("validDate"),
            Ok(Validator::ValidDate)
        ));
        assert!(matches!(
            parse_validator_string(r#"greaterThanDate("2020-01-01")"#),
            Ok(Validator::GreaterThanDate(d)) if d == "2020-01-01"
        ));
        assert!(matches!(
            parse_validator_string(r#"greaterThanOrEqualToDate("2020-01-01")"#),
            Ok(Validator::GreaterThanOrEqualToDate(d)) if d == "2020-01-01"
        ));
        assert!(matches!(
            parse_validator_string(r#"lessThanDate("2030-01-01")"#),
            Ok(Validator::LessThanDate(d)) if d == "2030-01-01"
        ));
        assert!(matches!(
            parse_validator_string(r#"lessThanOrEqualToDate("2030-01-01")"#),
            Ok(Validator::LessThanOrEqualToDate(d)) if d == "2030-01-01"
        ));
        assert!(matches!(
            parse_validator_string(r#"betweenDate("2020-01-01", "2030-12-31")"#),
            Ok(Validator::BetweenDate(min, max)) if min == "2020-01-01" && max == "2030-12-31"
        ));
    }

    // ========================================================================
    // BigInt validator parsing tests
    // ========================================================================

    #[test]
    fn test_parse_bigint_validators() {
        assert!(matches!(
            parse_validator_string("positiveBigInt"),
            Ok(Validator::PositiveBigInt)
        ));
        assert!(matches!(
            parse_validator_string("nonNegativeBigInt"),
            Ok(Validator::NonNegativeBigInt)
        ));
        assert!(matches!(
            parse_validator_string("negativeBigInt"),
            Ok(Validator::NegativeBigInt)
        ));
        assert!(matches!(
            parse_validator_string("nonPositiveBigInt"),
            Ok(Validator::NonPositiveBigInt)
        ));
        assert!(matches!(
            parse_validator_string("greaterThanBigInt(100)"),
            Ok(Validator::GreaterThanBigInt(n)) if n == "100"
        ));
        assert!(matches!(
            parse_validator_string("greaterThanOrEqualToBigInt(0)"),
            Ok(Validator::GreaterThanOrEqualToBigInt(n)) if n == "0"
        ));
        assert!(matches!(
            parse_validator_string("lessThanBigInt(1000)"),
            Ok(Validator::LessThanBigInt(n)) if n == "1000"
        ));
        assert!(matches!(
            parse_validator_string("lessThanOrEqualToBigInt(999)"),
            Ok(Validator::LessThanOrEqualToBigInt(n)) if n == "999"
        ));
        assert!(matches!(
            parse_validator_string("betweenBigInt(0, 100)"),
            Ok(Validator::BetweenBigInt(min, max)) if min == "0" && max == "100"
        ));
    }

    // ========================================================================
    // Array validator parsing tests
    // ========================================================================

    #[test]
    fn test_parse_array_validators() {
        assert!(matches!(
            parse_validator_string("maxItems(10)"),
            Ok(Validator::MaxItems(10))
        ));
        assert!(matches!(
            parse_validator_string("minItems(1)"),
            Ok(Validator::MinItems(1))
        ));
        assert!(matches!(
            parse_validator_string("itemsCount(5)"),
            Ok(Validator::ItemsCount(5))
        ));
    }

    // ========================================================================
    // Additional number validator parsing tests
    // ========================================================================

    #[test]
    fn test_parse_additional_number_validators() {
        assert!(matches!(
            parse_validator_string("nonNaN"),
            Ok(Validator::NonNaN)
        ));
        assert!(matches!(
            parse_validator_string("finite"),
            Ok(Validator::Finite)
        ));
        assert!(matches!(
            parse_validator_string("uint8"),
            Ok(Validator::Uint8)
        ));
        assert!(matches!(
            parse_validator_string("multipleOf(5)"),
            Ok(Validator::MultipleOf(n)) if n == 5.0
        ));
        assert!(matches!(
            parse_validator_string("negative"),
            Ok(Validator::Negative)
        ));
        assert!(matches!(
            parse_validator_string("nonNegative"),
            Ok(Validator::NonNegative)
        ));
        assert!(matches!(
            parse_validator_string("nonPositive"),
            Ok(Validator::NonPositive)
        ));
    }

    // ========================================================================
    // Additional string validator parsing tests
    // ========================================================================

    #[test]
    fn test_parse_additional_string_validators() {
        assert!(matches!(
            parse_validator_string("capitalized"),
            Ok(Validator::Capitalized)
        ));
        assert!(matches!(
            parse_validator_string("uncapitalized"),
            Ok(Validator::Uncapitalized)
        ));
        assert!(matches!(
            parse_validator_string("length(5, 10)"),
            Ok(Validator::LengthRange(5, 10))
        ));
    }

    // ========================================================================
    // Case sensitivity tests
    // ========================================================================

    #[test]
    fn test_parse_validators_case_insensitive() {
        // Validators should be case-insensitive
        assert!(matches!(
            parse_validator_string("EMAIL"),
            Ok(Validator::Email)
        ));
        assert!(matches!(
            parse_validator_string("Email"),
            Ok(Validator::Email)
        ));
        assert!(matches!(
            parse_validator_string("NONEMPTY"),
            Ok(Validator::NonEmpty)
        ));
        assert!(matches!(
            parse_validator_string("NonEmpty"),
            Ok(Validator::NonEmpty)
        ));
        assert!(matches!(
            parse_validator_string("MAXLENGTH(10)"),
            Ok(Validator::MaxLength(10))
        ));
    }

    // ========================================================================
    // Pattern validator with special characters
    // ========================================================================

    #[test]
    fn test_parse_pattern_with_special_chars() {
        // Test pattern with various regex special chars
        assert!(matches!(
            parse_validator_string(r#"pattern("^[A-Z]{3}$")"#),
            Ok(Validator::Pattern(p)) if p == "^[A-Z]{3}$"
        ));
        assert!(matches!(
            parse_validator_string(r#"pattern("\\d+")"#),
            Ok(Validator::Pattern(p)) if p == "\\d+"
        ));
        assert!(matches!(
            parse_validator_string(r#"pattern("^test\\.json$")"#),
            Ok(Validator::Pattern(p)) if p == "^test\\.json$"
        ));
    }

    // ========================================================================
    // Edge case: validators with whitespace
    // ========================================================================

    #[test]
    fn test_parse_validators_with_whitespace() {
        assert!(matches!(
            parse_validator_string("  email  "),
            Ok(Validator::Email)
        ));
        assert!(matches!(
            parse_validator_string("between( 1 , 100 )"),
            Ok(Validator::Between(min, max)) if min == 1.0 && max == 100.0
        ));
        assert!(matches!(
            parse_validator_string("maxLength( 50 )"),
            Ok(Validator::MaxLength(50))
        ));
    }

    // ========================================================================
    // Validator error tests
    // ========================================================================

    #[test]
    fn test_unknown_validator_returns_error() {
        let result = parse_validator_string("unknownValidator");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("unknown validator"));
        assert!(err.message.contains("unknownValidator"));
    }

    #[test]
    fn test_unknown_validator_with_typo_suggests_correction() {
        // "emai" is close to "email"
        let result = parse_validator_string("emai");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.help.is_some());
        assert!(err.help.as_ref().unwrap().contains("email"));
    }

    #[test]
    fn test_unknown_validator_no_suggestion_for_unrelated() {
        // "xyz" has no similar validators
        let result = parse_validator_string("xyz");
        assert!(result.is_err());
        let err = result.unwrap_err();
        // For short strings with no matches, help may be None
        assert!(err.help.is_none() || !err.help.as_ref().unwrap().contains("email"));
    }

    #[test]
    fn test_invalid_maxlength_args_returns_error() {
        let result = parse_validator_string("maxLength(abc)");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("maxLength"));
    }

    #[test]
    fn test_invalid_between_args_returns_error() {
        // between requires two numbers
        let result = parse_validator_string("between(abc, def)");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("between"));
    }

    #[test]
    fn test_extract_validators_collects_errors() {
        let mut diagnostics = DiagnosticCollector::new();
        let validators = extract_validators(
            r#"{ validate: ["unknownValidator", "email"] }"#,
            span(),
            "test_field",
            &mut diagnostics,
        );
        // Should still extract the valid "email" validator
        assert_eq!(validators.len(), 1);
        assert!(matches!(validators[0].validator, Validator::Email));
        // Should have recorded an error for the unknown validator
        assert!(diagnostics.has_errors());
        assert_eq!(diagnostics.len(), 1);
    }

    #[test]
    fn test_extract_validators_multiple_errors() {
        let mut diagnostics = DiagnosticCollector::new();
        let validators = extract_validators(
            r#"{ validate: ["unknown1", "unknown2", "email"] }"#,
            span(),
            "test_field",
            &mut diagnostics,
        );
        // Should still extract the valid "email" validator
        assert_eq!(validators.len(), 1);
        // Should have recorded two errors
        assert!(diagnostics.has_errors());
        assert_eq!(diagnostics.len(), 2);
    }

    #[test]
    fn test_typo_suggestion_url_vs_uuid() {
        // "rul" is close to "url"
        let result = parse_validator_string("rul");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.help.is_some());
        assert!(err.help.as_ref().unwrap().contains("url"));
    }

    #[test]
    fn test_typo_suggestion_maxlength() {
        // "maxLenth" is close to "maxLength"
        let result = parse_validator_string("maxLenth(10)");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.help.is_some());
        assert!(err.help.as_ref().unwrap().contains("maxLength"));
    }

    // ========================================================================
    // Custom serializer/deserializer tests (serializeWith/deserializeWith)
    // ========================================================================

    #[test]
    fn test_field_serialize_with() {
        let decorator = make_decorator(r#"{ serializeWith: "mySerializer" }"#);
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert_eq!(opts.serialize_with.as_deref(), Some("mySerializer"));
        assert!(opts.deserialize_with.is_none());
    }

    #[test]
    fn test_field_deserialize_with() {
        let decorator = make_decorator(r#"{ deserializeWith: "myDeserializer" }"#);
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert!(opts.serialize_with.is_none());
        assert_eq!(opts.deserialize_with.as_deref(), Some("myDeserializer"));
    }

    #[test]
    fn test_field_serialize_and_deserialize_with() {
        let decorator =
            make_decorator(r#"{ serializeWith: "toJson", deserializeWith: "fromJson" }"#);
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert_eq!(opts.serialize_with.as_deref(), Some("toJson"));
        assert_eq!(opts.deserialize_with.as_deref(), Some("fromJson"));
    }

    #[test]
    fn test_field_serialize_with_combined_with_other_options() {
        let decorator = make_decorator(
            r#"{ serializeWith: "customSerialize", rename: "custom_field", skip: false }"#,
        );
        let result = SerdeFieldOptions::from_decorators(&[decorator], "test_field");
        let opts = result.options;
        assert_eq!(opts.serialize_with.as_deref(), Some("customSerialize"));
        assert_eq!(opts.rename.as_deref(), Some("custom_field"));
        assert!(!opts.skip);
    }

    // ========================================================================
    // String literal type classification tests
    // ========================================================================

    #[test]
    fn test_type_category_string_literal_double_quotes() {
        // String literal types like "Zoned" should be treated as primitives
        assert_eq!(
            TypeCategory::from_ts_type(r#""Zoned""#),
            TypeCategory::Primitive
        );
        assert_eq!(
            TypeCategory::from_ts_type(r#""some_value""#),
            TypeCategory::Primitive
        );
    }

    #[test]
    fn test_type_category_string_literal_single_quotes() {
        // Single-quoted string literals should also be primitive
        assert_eq!(TypeCategory::from_ts_type("'foo'"), TypeCategory::Primitive);
        assert_eq!(
            TypeCategory::from_ts_type("'bar_baz'"),
            TypeCategory::Primitive
        );
    }

    #[test]
    fn test_type_category_non_literal_type_names() {
        // Regular type names should still be Serializable
        assert_eq!(
            TypeCategory::from_ts_type("Zoned"),
            TypeCategory::Serializable("Zoned".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("User"),
            TypeCategory::Serializable("User".into())
        );
    }

    // ========================================================================
    // TypeScript utility type classification tests
    // ========================================================================

    #[test]
    fn test_type_category_record() {
        // Record<K, V> should be properly parsed as a Record variant
        assert_eq!(
            TypeCategory::from_ts_type("Record<string, unknown>"),
            TypeCategory::Record("string".into(), "unknown".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("Record<string, number>"),
            TypeCategory::Record("string".into(), "number".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("Record<string, User>"),
            TypeCategory::Record("string".into(), "User".into())
        );
    }

    #[test]
    fn test_split_top_level_union_tracks_braces() {
        // Pipes inside braces should not split
        assert_eq!(split_top_level_union("{ a: string | number }"), None);
        assert_eq!(
            split_top_level_union("{ status: \"active\" | \"inactive\" }"),
            None
        );
        // Pipes outside braces should still split
        assert_eq!(
            split_top_level_union("{ a: string } | { b: number }"),
            Some(vec!["{ a: string }", "{ b: number }"])
        );
        // Mixed: pipe inside braces ignored, pipe outside splits
        assert_eq!(
            split_top_level_union("{ a: string | number } | null"),
            Some(vec!["{ a: string | number }", "null"])
        );
    }

    #[test]
    fn test_type_category_wrapper_utility_types() {
        // Wrapper utility types that preserve structure should extract the inner type
        assert_eq!(
            TypeCategory::from_ts_type("Partial<User>"),
            TypeCategory::Wrapper("User".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("Required<Config>"),
            TypeCategory::Wrapper("Config".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("Readonly<Data>"),
            TypeCategory::Wrapper("Data".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("NonNullable<User>"),
            TypeCategory::Wrapper("User".into())
        );
        // Pick and Omit extract the first type argument
        assert_eq!(
            TypeCategory::from_ts_type("Pick<User, 'name' | 'email'>"),
            TypeCategory::Wrapper("User".into())
        );
        assert_eq!(
            TypeCategory::from_ts_type("Omit<User, 'password'>"),
            TypeCategory::Wrapper("User".into())
        );
    }

    #[test]
    fn test_type_category_non_serializable_utility_types() {
        // Utility types operating on functions/unions/async should be Unknown
        assert_eq!(
            TypeCategory::from_ts_type("Promise<string>"),
            TypeCategory::Unknown
        );
        assert_eq!(
            TypeCategory::from_ts_type("ReturnType<typeof fn>"),
            TypeCategory::Unknown
        );
        assert_eq!(
            TypeCategory::from_ts_type("Awaited<Promise<User>>"),
            TypeCategory::Unknown
        );
    }
}