reinhardt-macros 0.1.2

Procedural macros for Reinhardt framework
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
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
//! Model derive macro for automatic ORM model registration
//!
//! Provides automatic `Model` trait implementation and registration to the global ModelRegistry.
//!
//! # Automatic Relationship Discovery
//!
//! The `#[model(...)]` attribute macro automatically detects relationship fields and registers
//! them in the global `RELATIONSHIPS` registry for reverse relation construction:
//!
//! - **`ForeignKeyField<T>`** → Registered as `RelationshipType::ForeignKey`
//! - **`OneToOneField<T>`** → Registered as `RelationshipType::OneToOne`
//! - **`ManyToManyField<T, U>`** → Registered as `RelationshipType::ManyToMany`
//!
//! # Type-Safe ManyToMany Accessor Methods
//!
//! The `#[model(...)]` macro automatically generates type-safe accessor methods for each `ManyToManyField`.
//!
//! **Benefits:**
//! - Compile-time field name validation (no typos)
//! - Type inference for Source and Target models
//! - IDE auto-completion support
//! - Cleaner, more idiomatic API
//!
//! The macro generates linkme distributed_slice registrations for each relationship,
//! enabling `build_reverse_relations()` to construct reverse accessors at runtime.

use std::collections::HashMap;

use proc_macro2::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Fields, GenericArgument, PathArguments, Result, Type, parse_quote};
use syn::{Ident, LitStr, bracketed, parenthesized};

use crate::crate_paths::{
	get_linkme_crate, get_reinhardt_core_crate, get_reinhardt_crate,
	get_reinhardt_migrations_crate, get_reinhardt_orm_crate,
};
use crate::rel::RelAttribute;

/// Constraint specification from `#[model(constraints = [...])]`
#[derive(Debug, Clone)]
enum ConstraintSpec {
	/// unique(fields = [...], name = "...", condition = "...")
	Unique {
		fields: Vec<String>,
		name: Option<String>,
		condition: Option<String>,
	},
}

/// Parsed model attributes (intermediate representation)
struct ModelAttributesParsed {
	app_label: Option<String>,
	table_name: Option<String>,
	constraints: Option<Vec<ConstraintSpec>>,
	unique_together: Vec<Vec<String>>, // Multiple Django-style unique_together constraints
	/// Optional custom manager path: `manager = MyManager` (Issue #3980).
	manager: Option<syn::Path>,
}

/// Validate a raw SQL expression to reject dangerous patterns.
///
/// This is a basic compile-time check that rejects obviously dangerous SQL
/// keywords and patterns that should never appear in `check`, `generated`,
/// or `condition` constraint attributes. It does not replace parameterized
/// queries, but prevents accidental or malicious injection of DDL/DML
/// statements in model attribute strings.
fn validate_sql_expression(sql: &str, attr_name: &str) -> Result<()> {
	let upper = sql.to_uppercase();

	// Reject statement terminators that could allow statement chaining
	if sql.contains(';') {
		return Err(syn::Error::new(
			proc_macro2::Span::call_site(),
			format!(
				"Semicolons are not allowed in {} expressions: {:?}",
				attr_name, sql
			),
		));
	}

	// Reject DDL/DML keywords that should never appear in check/generated/condition
	const BLOCKED_KEYWORDS: &[&str] = &[
		"DROP ",
		"DELETE ",
		"INSERT ",
		"UPDATE ",
		"ALTER ",
		"TRUNCATE ",
		"EXEC ",
		"EXECUTE ",
		"CREATE ",
		"GRANT ",
		"REVOKE ",
	];
	for keyword in BLOCKED_KEYWORDS {
		if upper.contains(keyword) {
			return Err(syn::Error::new(
				proc_macro2::Span::call_site(),
				format!(
					"Dangerous SQL keyword {:?} detected in {} expression: {:?}",
					keyword.trim(),
					attr_name,
					sql
				),
			));
		}
	}

	// Reject comment sequences that could hide injected SQL
	if sql.contains("--") || sql.contains("/*") {
		return Err(syn::Error::new(
			proc_macro2::Span::call_site(),
			format!(
				"SQL comments are not allowed in {} expressions: {:?}",
				attr_name, sql
			),
		));
	}

	Ok(())
}

/// Model configuration from `#[model(...)]` attribute
#[derive(Debug, Clone)]
struct ModelConfig {
	app_label: String,
	table_name: String,
	constraints: Vec<ConstraintSpec>,
	/// Custom manager type path from `manager = MyManager` (Issue #3980).
	///
	/// When `Some`, the macro emits an `impl HasCustomManager for Self`
	/// that wires the model to the user-supplied manager type.
	manager: Option<syn::Path>,
}

impl ModelConfig {
	/// Parse `#[model(...)]` attribute
	fn from_attrs(attrs: &[syn::Attribute], struct_name: &syn::Ident) -> Result<Self> {
		let mut app_label = None;
		let mut table_name = None;
		let mut constraints = Vec::new();
		let mut manager: Option<syn::Path> = None;

		for attr in attrs {
			// Accept both #[model(...)] and #[model_config(...)] helper attributes
			if !attr.path().is_ident("model") && !attr.path().is_ident("model_config") {
				continue;
			}

			// Use custom parser for all model attributes
			let model_attr = attr
				.parse_args_with(|input: syn::parse::ParseStream| {
					Self::parse_model_attributes(input)
				})
				.map_err(|e| {
					syn::Error::new_spanned(attr, format!("parse_args_with failed: {}", e))
				})?;

			if let Some(c) = model_attr.constraints {
				constraints = c;
			}
			// Convert each unique_together to ConstraintSpec::Unique
			for fields in model_attr.unique_together {
				constraints.push(ConstraintSpec::Unique {
					fields,
					name: None, // Auto-generate name
					condition: None,
				});
			}
			if let Some(al) = model_attr.app_label {
				app_label = Some(al);
			}
			if let Some(tn) = model_attr.table_name {
				table_name = Some(tn);
			}
			if let Some(m) = model_attr.manager {
				if manager.is_some() {
					return Err(syn::Error::new_spanned(
						struct_name,
						"#[model(manager = ...)] specified more than once",
					));
				}
				manager = Some(m);
			}
		}

		let table_name = table_name.ok_or_else(|| {
			syn::Error::new_spanned(
				struct_name,
				"table_name attribute is required in #[model(...)]",
			)
		})?;

		Ok(Self {
			app_label: app_label.unwrap_or_else(|| "default".to_string()),
			table_name,
			constraints,
			manager,
		})
	}

	/// Parse all model attributes using custom parser
	fn parse_model_attributes(input: syn::parse::ParseStream) -> Result<ModelAttributesParsed> {
		use syn::Token;

		let mut app_label = None;
		let mut table_name = None;
		let mut constraints = None;
		let mut unique_together = Vec::new();
		let mut manager: Option<syn::Path> = None;

		while !input.is_empty() {
			let ident: Ident = input.parse()?;
			input.parse::<Token![=]>()?;

			if ident == "app_label" {
				let value: LitStr = input.parse()?;
				app_label = Some(value.value());
			} else if ident == "table_name" {
				let value: LitStr = input.parse()?;
				table_name = Some(value.value());
			} else if ident == "manager" {
				// Custom object manager type: `manager = MyManager` (Issue #3980).
				let path: syn::Path = input.parse()?;
				manager = Some(path);
			} else if ident == "unique_together" {
				// Tuple syntax: unique_together = ("field1", "field2")
				use syn::punctuated::Punctuated;
				let content;
				parenthesized!(content in input);
				let fields: Punctuated<LitStr, Token![,]> =
					content.call(Punctuated::parse_terminated)?;
				unique_together.push(fields.iter().map(|lit| lit.value()).collect());
			} else if ident == "constraints" {
				// Parse array: [unique(...), ...]
				let array_content;
				bracketed!(array_content in input);

				let mut specs = Vec::new();
				while !array_content.is_empty() {
					specs.push(Self::parse_constraint(&array_content)?);

					if array_content.peek(Token![,]) {
						array_content.parse::<Token![,]>()?;
					} else {
						break;
					}
				}
				constraints = Some(specs);
			} else {
				return Err(syn::Error::new_spanned(
					&ident,
					format!("Unknown model attribute: {}", ident),
				));
			}

			// Parse optional comma
			if input.peek(Token![,]) {
				input.parse::<Token![,]>()?;
			} else {
				break;
			}
		}

		Ok(ModelAttributesParsed {
			app_label,
			table_name,
			constraints,
			unique_together,
			manager,
		})
	}

	/// Parse constraint specification: unique(fields = [...], name = "...", condition = "...")
	fn parse_constraint(input: syn::parse::ParseStream) -> Result<ConstraintSpec> {
		use syn::Token;
		use syn::punctuated::Punctuated;

		// Define custom keyword for "unique"
		mod kw {
			syn::custom_keyword!(unique);
		}

		// Parse constraint type using custom keyword
		let _unique_keyword = input.parse::<kw::unique>()?;

		// Parse parentheses with parameters
		let content;
		parenthesized!(content in input);

		let mut fields = None;
		let mut name = None;
		let mut condition = None;

		// Parse named parameters (fields = [...], name = "...", condition = "...")
		loop {
			if content.is_empty() {
				break;
			}

			let param_name: Ident = content.parse()?;
			content.parse::<Token![=]>()?;

			if param_name == "fields" {
				// Parse array using Punctuated for proper comma handling
				let array_content;
				bracketed!(array_content in content);

				// Use Punctuated::parse_terminated for robust comma-separated parsing
				let field_literals: Punctuated<LitStr, Token![,]> =
					array_content.call(Punctuated::parse_terminated)?;

				fields = Some(field_literals.iter().map(|lit| lit.value()).collect());
			} else if param_name == "name" {
				// Parse string: "constraint_name"
				let value: LitStr = content.parse()?;
				name = Some(value.value());
			} else if param_name == "condition" {
				// Parse string: "WHERE clause"
				let value: LitStr = content.parse()?;
				let condition_str = value.value();
				validate_sql_expression(&condition_str, "condition")?;
				condition = Some(condition_str);
			} else {
				return Err(syn::Error::new_spanned(
					param_name,
					"Unknown parameter. Supported: fields, name, condition",
				));
			}

			// Parse optional comma between parameters
			if content.peek(Token![,]) {
				content.parse::<Token![,]>()?;
			} else {
				break;
			}
		}

		// fields is required
		let fields = fields.ok_or_else(|| {
			syn::Error::new(
				proc_macro2::Span::call_site(),
				"unique constraint requires 'fields' parameter",
			)
		})?;

		Ok(ConstraintSpec::Unique {
			fields,
			name,
			condition,
		})
	}
}

/// Foreign key specification
#[derive(Debug, Clone)]
enum ForeignKeySpec {
	/// Type directly: `#[field(foreign_key = User)]`
	Type(syn::Type),
	/// app_label.model_name format: `#[field(foreign_key = "users.User")]`
	AppModel {
		app_label: String,
		model_name: String,
	},
}

/// Storage strategy for PostgreSQL columns
#[cfg(feature = "db-postgres")]
#[derive(Debug, Clone)]
enum StorageStrategy {
	Plain,
	Extended,
	External,
	Main,
}

/// Compression method for PostgreSQL columns
#[cfg(feature = "db-postgres")]
#[derive(Debug, Clone)]
enum CompressionMethod {
	Pglz,
	Lz4,
}

/// Field configuration from `#[field(...)]` attribute
#[derive(Debug, Clone, Default)]
struct FieldConfig {
	primary_key: bool,
	max_length: Option<u64>,
	null: Option<bool>,
	blank: Option<bool>,
	unique: Option<bool>,
	default: Option<syn::Expr>, // Changed from String to Expr to support bool, int, etc.
	db_column: Option<String>,
	editable: Option<bool>,
	index: Option<bool>,
	check: Option<String>,
	// Validator flags
	email: Option<bool>,
	url: Option<bool>,
	min_length: Option<u64>,
	min_value: Option<i64>,
	max_value: Option<i64>,
	// Time-related fields
	auto_now_add: Option<bool>,
	auto_now: Option<bool>,
	// Relationship fields
	foreign_key: Option<ForeignKeySpec>,

	// Generated Columns (all DBMS)
	generated: Option<String>,
	generated_stored: Option<bool>,
	#[cfg(any(feature = "db-mysql", feature = "db-sqlite"))]
	generated_virtual: Option<bool>,

	// Identity/Auto-increment
	#[cfg(feature = "db-postgres")]
	identity_always: Option<bool>,
	#[cfg(feature = "db-postgres")]
	identity_by_default: Option<bool>,
	/// Auto-increment for integer primary keys.
	/// Available for all databases. When set to true on an integer primary key,
	/// the field is excluded from new() and uses 0 as default value.
	/// Integer primary keys are treated as auto_increment by default unless
	/// explicitly set to false.
	auto_increment: Option<bool>,
	#[cfg(feature = "db-sqlite")]
	autoincrement: Option<bool>,

	// Character Set & Collation
	collate: Option<String>,
	#[cfg(feature = "db-mysql")]
	character_set: Option<String>,

	// Comment
	#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
	comment: Option<String>,

	// Storage Optimization (PostgreSQL)
	#[cfg(feature = "db-postgres")]
	storage: Option<StorageStrategy>,
	#[cfg(feature = "db-postgres")]
	compression: Option<CompressionMethod>,

	// ON UPDATE Trigger (MySQL)
	#[cfg(feature = "db-mysql")]
	on_update_current_timestamp: Option<bool>,

	// Invisible Columns (MySQL)
	#[cfg(feature = "db-mysql")]
	invisible: Option<bool>,

	// Full-Text Index (PostgreSQL, MySQL)
	#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
	fulltext: Option<bool>,

	// Numeric Attributes (MySQL, deprecated)
	#[cfg(feature = "db-mysql")]
	unsigned: Option<bool>,
	#[cfg(feature = "db-mysql")]
	zerofill: Option<bool>,

	// Getter/setter generation control
	/// Skip getter and setter generation for this field.
	/// Used by `#[user]` macro to avoid conflicts with trait method signatures.
	skip_getter: bool,

	/// Completely skip this field from model processing.
	/// Excluded from type validation, getter/setter, constructor, metadata, and registration.
	/// Initialized with `Default::default()` in constructor. Implies `skip_getter = true`.
	/// Used by `#[user]` macro for non-DB cache fields (e.g., `Vec<String>` permissions).
	skip: bool,

	// Constructor generation control
	/// Whether to include this field in the new() function arguments
	/// When true, field is included even if it would normally be auto-generated
	/// When false, field is excluded and uses default value
	include_in_new: Option<bool>,

	// PostgreSQL-specific type attributes
	/// Explicit field type specification (e.g., "jsonb", "hstore", "citext")
	/// Takes priority over automatic type inference
	#[cfg(feature = "db-postgres")]
	field_type: Option<String>,
	/// Base type for array elements (e.g., "VARCHAR(50)", "INTEGER")
	/// Used when the Rust type is `Vec<T>` but the element type cannot be inferred
	#[cfg(feature = "db-postgres")]
	array_base_type: Option<String>,
}

impl FieldConfig {
	/// Parse `#[field(...)]` attribute
	fn from_attrs(attrs: &[syn::Attribute]) -> Result<Self> {
		let mut config = Self::default();

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

			// Support empty #[field] attribute
			if matches!(attr.meta, syn::Meta::Path(_)) {
				continue;
			}

			attr.parse_nested_meta(|meta| {
				if meta.path.is_ident("primary_key") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.primary_key = value.value;
					Ok(())
				} else if meta.path.is_ident("max_length") {
					let value: syn::LitInt = meta.value()?.parse()?;
					config.max_length = Some(value.base10_parse()?);
					Ok(())
				} else if meta.path.is_ident("null") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.null = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("blank") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.blank = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("unique") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.unique = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("default") {
					// Parse as Expr to support bool, int, string, etc.
					let value: syn::Expr = meta.value()?.parse()?;
					config.default = Some(value);
					Ok(())
				} else if meta.path.is_ident("db_column") {
					let value: syn::LitStr = meta.value()?.parse()?;
					config.db_column = Some(value.value());
					Ok(())
				} else if meta.path.is_ident("editable") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.editable = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("index") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.index = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("check") {
					let value: syn::LitStr = meta.value()?.parse()?;
					let check_str = value.value();
					validate_sql_expression(&check_str, "check")?;
					config.check = Some(check_str);
					Ok(())
				} else if meta.path.is_ident("email") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.email = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("url") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.url = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("min_length") {
					let value: syn::LitInt = meta.value()?.parse()?;
					config.min_length = Some(value.base10_parse()?);
					Ok(())
				} else if meta.path.is_ident("min_value") {
					let value: syn::LitInt = meta.value()?.parse()?;
					config.min_value = Some(value.base10_parse()?);
					Ok(())
				} else if meta.path.is_ident("max_value") {
					let value: syn::LitInt = meta.value()?.parse()?;
					config.max_value = Some(value.base10_parse()?);
					Ok(())
				} else if meta.path.is_ident("auto_now_add") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.auto_now_add = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("auto_now") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.auto_now = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("foreign_key") {
					// Try parsing as Type first (direct type specification)
					if let Ok(ty) = meta.value()?.parse::<syn::Type>() {
						config.foreign_key = Some(ForeignKeySpec::Type(ty));
						return Ok(());
					}

					// Fall back to string specification
					if let Ok(value) = meta.value()?.parse::<syn::LitStr>() {
						let spec_str = value.value();

						if spec_str.contains('.') {
							// app_label.model_name format
							let parts: Vec<&str> = spec_str.split('.').collect();
							if parts.len() == 2 {
								config.foreign_key = Some(ForeignKeySpec::AppModel {
									app_label: parts[0].to_string(),
									model_name: parts[1].to_string(),
								});
								return Ok(());
							} else {
								return Err(meta.error(
									"foreign_key must be in 'app_label.model_name' format",
								));
							}
						} else {
							// Type name only (for backward compatibility)
							if let Ok(ty) = syn::parse_str::<syn::Type>(&spec_str) {
								config.foreign_key = Some(ForeignKeySpec::Type(ty));
								return Ok(());
							} else {
								return Err(meta.error("Invalid foreign_key specification"));
							}
						}
					}

					Err(meta.error("foreign_key must be a type (User) or string (\"users.User\")"))
				}
				// Generated Columns
				else if meta.path.is_ident("generated") {
					let value: syn::LitStr = meta.value()?.parse()?;
					let gen_str = value.value();
					validate_sql_expression(&gen_str, "generated")?;
					config.generated = Some(gen_str);
					Ok(())
				} else if meta.path.is_ident("generated_stored") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.generated_stored = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("generated_virtual") {
					#[cfg(any(feature = "db-mysql", feature = "db-sqlite"))]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.generated_virtual = Some(value.value);
						Ok(())
					}
					#[cfg(not(any(feature = "db-mysql", feature = "db-sqlite")))]
					{
						Err(meta.error(
							"generated_virtual is only available with db-mysql or db-sqlite features",
						))
					}
				}
				// Identity/Auto-increment
				else if meta.path.is_ident("identity_always") {
					#[cfg(feature = "db-postgres")]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.identity_always = Some(value.value);
						Ok(())
					}
					#[cfg(not(feature = "db-postgres"))]
					{
						Err(meta
							.error("identity_always is only available with db-postgres feature"))
					}
				} else if meta.path.is_ident("identity_by_default") {
					#[cfg(feature = "db-postgres")]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.identity_by_default = Some(value.value);
						Ok(())
					}
					#[cfg(not(feature = "db-postgres"))]
					{
						Err(meta.error(
							"identity_by_default is only available with db-postgres feature",
						))
					}
				} else if meta.path.is_ident("auto_increment") {
					// auto_increment is available for all databases
					// Integer primary keys are treated as auto_increment by default
					let value: syn::LitBool = meta.value()?.parse()?;
					config.auto_increment = Some(value.value);
					Ok(())
				} else if meta.path.is_ident("autoincrement") {
					#[cfg(feature = "db-sqlite")]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.autoincrement = Some(value.value);
						Ok(())
					}
					#[cfg(not(feature = "db-sqlite"))]
					{
						Err(meta.error("autoincrement is only available with db-sqlite feature"))
					}
				}
				// Character Set & Collation
				else if meta.path.is_ident("collate") {
					let value: syn::LitStr = meta.value()?.parse()?;
					config.collate = Some(value.value());
					Ok(())
				} else if meta.path.is_ident("character_set") {
					#[cfg(feature = "db-mysql")]
					{
						let value: syn::LitStr = meta.value()?.parse()?;
						config.character_set = Some(value.value());
						Ok(())
					}
					#[cfg(not(feature = "db-mysql"))]
					{
						Err(meta.error("character_set is only available with db-mysql feature"))
					}
				}
				// Comment
				else if meta.path.is_ident("comment") {
					#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
					{
						let value: syn::LitStr = meta.value()?.parse()?;
						config.comment = Some(value.value());
						Ok(())
					}
					#[cfg(not(any(feature = "db-postgres", feature = "db-mysql")))]
					{
						Err(meta.error(
							"comment is only available with db-postgres or db-mysql features",
						))
					}
				}
				// Storage Optimization
				else if meta.path.is_ident("storage") {
					#[cfg(feature = "db-postgres")]
					{
						let value: syn::LitStr = meta.value()?.parse()?;
						let storage_str = value.value();
						let storage = match storage_str.to_lowercase().as_str() {
							"plain" => StorageStrategy::Plain,
							"extended" => StorageStrategy::Extended,
							"external" => StorageStrategy::External,
							"main" => StorageStrategy::Main,
							_ => {
								return Err(meta.error(
									"storage must be one of: plain, extended, external, main",
								));
							}
						};
						config.storage = Some(storage);
						Ok(())
					}
					#[cfg(not(feature = "db-postgres"))]
					{
						Err(meta.error("storage is only available with db-postgres feature"))
					}
				} else if meta.path.is_ident("compression") {
					#[cfg(feature = "db-postgres")]
					{
						let value: syn::LitStr = meta.value()?.parse()?;
						let compression_str = value.value();
						let compression = match compression_str.to_lowercase().as_str() {
							"pglz" => CompressionMethod::Pglz,
							"lz4" => CompressionMethod::Lz4,
							_ => return Err(meta.error("compression must be one of: pglz, lz4")),
						};
						config.compression = Some(compression);
						Ok(())
					}
					#[cfg(not(feature = "db-postgres"))]
					{
						Err(meta.error("compression is only available with db-postgres feature"))
					}
				}
				// ON UPDATE Trigger
				else if meta.path.is_ident("on_update_current_timestamp") {
					#[cfg(feature = "db-mysql")]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.on_update_current_timestamp = Some(value.value);
						Ok(())
					}
					#[cfg(not(feature = "db-mysql"))]
					{
						Err(meta.error(
							"on_update_current_timestamp is only available with db-mysql feature",
						))
					}
				}
				// Invisible Columns
				else if meta.path.is_ident("invisible") {
					#[cfg(feature = "db-mysql")]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.invisible = Some(value.value);
						Ok(())
					}
					#[cfg(not(feature = "db-mysql"))]
					{
						Err(meta.error("invisible is only available with db-mysql feature"))
					}
				}
				// Full-Text Index
				else if meta.path.is_ident("fulltext") {
					#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.fulltext = Some(value.value);
						Ok(())
					}
					#[cfg(not(any(feature = "db-postgres", feature = "db-mysql")))]
					{
						Err(meta.error(
							"fulltext is only available with db-postgres or db-mysql features",
						))
					}
				}
				// Numeric Attributes (MySQL, deprecated)
				else if meta.path.is_ident("unsigned") {
					#[cfg(feature = "db-mysql")]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.unsigned = Some(value.value);
						Ok(())
					}
					#[cfg(not(feature = "db-mysql"))]
					{
						Err(meta.error("unsigned is only available with db-mysql feature"))
					}
				} else if meta.path.is_ident("zerofill") {
					#[cfg(feature = "db-mysql")]
					{
						let value: syn::LitBool = meta.value()?.parse()?;
						config.zerofill = Some(value.value);
						Ok(())
					}
					#[cfg(not(feature = "db-mysql"))]
					{
						Err(meta.error("zerofill is only available with db-mysql feature"))
					}
				}
				// Constructor generation control
				else if meta.path.is_ident("include_in_new") {
					let value: syn::LitBool = meta.value()?.parse()?;
					config.include_in_new = Some(value.value);
					Ok(())
				}
				// PostgreSQL-specific type attributes
				else if meta.path.is_ident("field_type") {
					#[cfg(feature = "db-postgres")]
					{
						let value: syn::LitStr = meta.value()?.parse()?;
						config.field_type = Some(value.value());
						Ok(())
					}
					#[cfg(not(feature = "db-postgres"))]
					{
						Err(meta.error("field_type is only available with db-postgres feature"))
					}
				} else if meta.path.is_ident("array_base_type") {
					#[cfg(feature = "db-postgres")]
					{
						let value: syn::LitStr = meta.value()?.parse()?;
						config.array_base_type = Some(value.value());
						Ok(())
					}
					#[cfg(not(feature = "db-postgres"))]
					{
						Err(meta
							.error("array_base_type is only available with db-postgres feature"))
					}
				} else if meta.path.is_ident("skip_getter") {
					config.skip_getter = meta.value()?.parse::<syn::LitBool>()?.value();
					Ok(())
				} else if meta.path.is_ident("skip") {
					config.skip = meta.value()?.parse::<syn::LitBool>()?.value();
					Ok(())
				} else {
					Err(meta.error("unsupported field attribute"))
				}
			})?;
		}

		// skip implies skip_getter
		if config.skip {
			config.skip_getter = true;
		}

		Ok(config)
	}

	/// Validate field configuration for mutual exclusivity and logical consistency
	fn validate(&self) -> Result<()> {
		// Check mutual exclusivity of auto-increment attributes
		#[allow(unused_mut)]
		let mut auto_increment_count = 0;

		#[cfg(feature = "db-postgres")]
		{
			if self.identity_always.is_some() {
				auto_increment_count += 1;
			}
			if self.identity_by_default.is_some() {
				auto_increment_count += 1;
			}
		}

		#[cfg(feature = "db-mysql")]
		{
			if self.auto_increment.is_some() {
				auto_increment_count += 1;
			}
		}

		#[cfg(feature = "db-sqlite")]
		{
			if self.autoincrement.is_some() {
				auto_increment_count += 1;
			}
		}

		if auto_increment_count > 1 {
			return Err(syn::Error::new(
				proc_macro2::Span::call_site(),
				"Only one auto-increment attribute (identity_always, identity_by_default, auto_increment, autoincrement) can be specified per field",
			));
		}

		// Generated columns cannot have default values
		if self.generated.is_some() && self.default.is_some() {
			return Err(syn::Error::new(
				proc_macro2::Span::call_site(),
				"Generated columns cannot have default values",
			));
		}

		// Generated columns should have either generated_stored or generated_virtual
		if self.generated.is_some() {
			let has_stored = self.generated_stored.unwrap_or(false);

			#[cfg(any(feature = "db-mysql", feature = "db-sqlite"))]
			let has_virtual = self.generated_virtual.unwrap_or(false);
			#[cfg(not(any(feature = "db-mysql", feature = "db-sqlite")))]
			let has_virtual = false;

			if !has_stored && !has_virtual {
				return Err(syn::Error::new(
					proc_macro2::Span::call_site(),
					"Generated columns must specify either generated_stored=true or generated_virtual=true",
				));
			}

			if has_stored && has_virtual {
				return Err(syn::Error::new(
					proc_macro2::Span::call_site(),
					"Generated columns cannot be both STORED and VIRTUAL",
				));
			}
		}

		Ok(())
	}
}

/// Field information for processing
#[derive(Debug, Clone)]
struct FieldInfo {
	name: syn::Ident,
	ty: Type,
	config: FieldConfig,
	/// Optional relationship attribute from `#[rel(...)]`
	///
	/// This field is reserved for future accessor generation support.
	/// Currently, relationship fields (ForeignKeyField, ManyToManyField) are processed
	/// at runtime through their types, but this field will enable compile-time accessor
	/// generation for relationship traversal methods.
	///
	/// Planned usage:
	/// - Generate type-safe accessor methods (e.g., user.get_profile(), user.get_posts())
	/// - Enable eager loading optimization hints
	/// - Support relationship-specific query methods
	///
	/// Implementation requires architectural decisions on:
	/// - Accessor naming conventions
	/// - Async/sync accessor variants
	/// - Relationship traversal API design
	#[allow(dead_code)]
	rel: Option<RelAttribute>,
	/// Whether this is an auto-generated FK _id field (marked with `#[fk_id_field]`)
	/// These fields should have getters but not setters
	is_fk_id_field: bool,
}

/// Foreign key / One-to-one field information for automatic ID field generation
#[derive(Debug, Clone)]
#[allow(dead_code)] // Fields will be used for accessor generation in future
struct ForeignKeyFieldInfo {
	/// Original field name (e.g., "author")
	field_name: syn::Ident,
	/// Target model type (e.g., User)
	target_type: Type,
	/// Generated ID column name (e.g., "author_id" or custom via db_column)
	id_column_name: String,
	/// Related name for reverse accessor
	related_name: Option<String>,
	/// Whether this is a OneToOne field (requires UNIQUE constraint)
	is_one_to_one: bool,
	/// The full RelAttribute for additional options
	rel_attr: RelAttribute,
}

/// Generate field metadata string from Rust type
fn field_type_to_metadata_string(ty: &Type, _config: &FieldConfig) -> Result<String> {
	let (_is_option, inner_ty) = extract_option_type(ty);

	match inner_ty {
		Type::Path(type_path) => {
			let last_segment = type_path
				.path
				.segments
				.last()
				.ok_or_else(|| syn::Error::new_spanned(ty, "Invalid type path"))?;

			let type_name = match last_segment.ident.to_string().as_str() {
				"i32" => "IntegerField",
				"i64" => "BigIntegerField",
				"String" => "CharField",
				"bool" => "BooleanField",
				"f32" | "f64" => "FloatField",
				"DateTime" => "DateTimeField",
				"Date" => "DateField",
				"Time" => "TimeField",
				"Decimal" => "DecimalField",
				"Uuid" => "UuidField",
				// Extended types (SQL generation is gated per-DB in map_type_to_field_type)
				"Vec" => "ArrayField",
				"Value" => "JsonField",
				"HashMap" => "HStoreField",
				other => {
					return Err(syn::Error::new_spanned(
						ty,
						format!("Unsupported field type: {}", other),
					));
				}
			};

			Ok(format!("reinhardt.orm.models.{}", type_name))
		}
		_ => Err(syn::Error::new_spanned(ty, "Unsupported field type")),
	}
}

/// Serialize a `#[field(default = ...)]` expression into the dialect-neutral
/// SQL fragment stored in `FieldState.params["default"]`.
///
/// The autodetector reads this string verbatim into the generated migration's
/// `ColumnDefinition.default`, and the runner interpolates it as
/// `DEFAULT <fragment>` inside the generated DDL. The serialization therefore
/// has to:
///
/// * Produce SQL the three supported dialects (Postgres, MySQL, SQLite) all
///   accept. For booleans we emit lowercase `true` / `false`; Postgres and
///   MySQL accept these as literals and SQLite (≥ 3.23) treats them as
///   integer 1 / 0.
/// * Quote string literals so that `default = "active"` lands as `'active'`.
///   We use SQL single-quote escaping (double the inner quote) rather than
///   Rust escaping.
/// * Stay opt-in for anything we cannot prove is safe — unrecognised forms
///   (function calls, paths, complex expressions) return `None` so that the
///   macro keeps today's behaviour of silently omitting the default rather
///   than emitting something that would break parsing downstream. The runner
///   surfaces a clearer "missing default" failure when this matters; see
///   reinhardt-web#4447.
fn serialize_field_default(expr: &syn::Expr) -> Option<String> {
	// Allow a leading unary `-` so `default = -1` works.
	if let syn::Expr::Unary(unary) = expr
		&& matches!(unary.op, syn::UnOp::Neg(_))
		&& let Some(inner) = serialize_field_default(&unary.expr)
	{
		return Some(format!("-{}", inner));
	}

	let lit = match expr {
		syn::Expr::Lit(l) => &l.lit,
		_ => return None,
	};
	match lit {
		syn::Lit::Bool(b) => Some(if b.value {
			"true".into()
		} else {
			"false".into()
		}),
		syn::Lit::Int(i) => Some(i.base10_digits().to_string()),
		syn::Lit::Float(f) => Some(f.base10_digits().to_string()),
		syn::Lit::Str(s) => Some(format!("'{}'", s.value().replace('\'', "''"))),
		_ => None,
	}
}

/// Map Rust type to ORM field type
fn map_type_to_field_type(ty: &Type, config: &FieldConfig) -> Result<TokenStream> {
	let migrations_crate = get_reinhardt_migrations_crate();

	// PostgreSQL: Check for explicit field_type attribute first
	#[cfg(feature = "db-postgres")]
	if let Some(explicit_type) = &config.field_type {
		return map_explicit_field_type(explicit_type, &migrations_crate);
	}

	// Extract the inner type if it's Option<T>
	let (_is_option, inner_ty) = extract_option_type(ty);

	let field_type = match inner_ty {
		Type::Path(type_path) => {
			let last_segment = type_path
				.path
				.segments
				.last()
				.ok_or_else(|| syn::Error::new_spanned(ty, "Invalid type path"))?;

			match last_segment.ident.to_string().as_str() {
				"i32" => {
					quote! { #migrations_crate::FieldType::Integer }
				}
				"i64" => {
					quote! { #migrations_crate::FieldType::BigInteger }
				}
				"String" => {
					let max_length = config.max_length.ok_or_else(|| {
						syn::Error::new_spanned(ty, "String fields require max_length attribute")
					})? as u32;
					quote! { #migrations_crate::FieldType::VarChar(#max_length) }
				}
				"bool" => {
					quote! { #migrations_crate::FieldType::Boolean }
				}
				"DateTime" => {
					quote! { #migrations_crate::FieldType::TimestampTz }
				}
				"Date" => {
					quote! { #migrations_crate::FieldType::Date }
				}
				"Time" => {
					quote! { #migrations_crate::FieldType::Time }
				}
				"f32" => {
					quote! { #migrations_crate::FieldType::Float }
				}
				"f64" => {
					quote! { #migrations_crate::FieldType::Double }
				}
				"Uuid" => {
					quote! { #migrations_crate::FieldType::Uuid }
				}
				// PostgreSQL: Vec<T> -> Array type
				#[cfg(feature = "db-postgres")]
				"Vec" => {
					return map_vec_to_array_type(ty, last_segment, config, &migrations_crate);
				}
				// PostgreSQL: serde_json::Value -> JSONB
				#[cfg(feature = "db-postgres")]
				"Value" => {
					// Assume serde_json::Value for JSONB
					quote! { #migrations_crate::FieldType::Jsonb }
				}
				// PostgreSQL: HashMap<String, String> -> HStore
				#[cfg(feature = "db-postgres")]
				"HashMap" => {
					quote! { #migrations_crate::FieldType::HStore }
				}
				_ => {
					return Err(syn::Error::new_spanned(
						ty,
						format!("Unsupported field type: {}", last_segment.ident),
					));
				}
			}
		}
		_ => {
			return Err(syn::Error::new_spanned(ty, "Unsupported field type"));
		}
	};

	Ok(field_type)
}

/// Map explicit PostgreSQL field type string to FieldType
#[cfg(feature = "db-postgres")]
fn map_explicit_field_type(
	field_type_str: &str,
	migrations_crate: &proc_macro2::TokenStream,
) -> Result<TokenStream> {
	let field_type = match field_type_str.to_lowercase().as_str() {
		"jsonb" => quote! { #migrations_crate::FieldType::Jsonb },
		"json" => quote! { #migrations_crate::FieldType::Json },
		"hstore" => quote! { #migrations_crate::FieldType::HStore },
		"citext" => quote! { #migrations_crate::FieldType::CIText },
		"int4range" | "integer_range" => quote! { #migrations_crate::FieldType::Int4Range },
		"int8range" | "bigint_range" => quote! { #migrations_crate::FieldType::Int8Range },
		"numrange" | "decimal_range" => quote! { #migrations_crate::FieldType::NumRange },
		"daterange" | "date_range" => quote! { #migrations_crate::FieldType::DateRange },
		"tsrange" | "timestamp_range" => quote! { #migrations_crate::FieldType::TsRange },
		"tstzrange" | "timestamptz_range" => quote! { #migrations_crate::FieldType::TsTzRange },
		"tsvector" => quote! { #migrations_crate::FieldType::TsVector },
		"tsquery" => quote! { #migrations_crate::FieldType::TsQuery },
		"uuid" => quote! { #migrations_crate::FieldType::Uuid },
		"text" => quote! { #migrations_crate::FieldType::Text },
		other => {
			return Err(syn::Error::new(
				proc_macro2::Span::call_site(),
				format!(
					"Unknown PostgreSQL field type: '{}'. Supported types: jsonb, json, hstore, \
					 citext, int4range, int8range, numrange, daterange, tsrange, tstzrange, \
					 tsvector, tsquery, uuid, text",
					other
				),
			));
		}
	};
	Ok(field_type)
}

/// Map `Vec<T>` to PostgreSQL Array type
#[cfg(feature = "db-postgres")]
fn map_vec_to_array_type(
	ty: &Type,
	segment: &syn::PathSegment,
	config: &FieldConfig,
	migrations_crate: &proc_macro2::TokenStream,
) -> Result<TokenStream> {
	// First check if array_base_type is explicitly specified
	if let Some(base_type) = &config.array_base_type {
		// Parse the base type string to FieldType
		let inner_field_type = parse_base_type_string(base_type, migrations_crate)?;
		return Ok(quote! {
			#migrations_crate::FieldType::Array(Box::new(#inner_field_type))
		});
	}

	// Try to infer the element type from Vec<T>
	if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
		&& let Some(syn::GenericArgument::Type(Type::Path(inner_path))) = args.args.first()
		&& let Some(inner_segment) = inner_path.path.segments.last()
	{
		let inner_type_name = inner_segment.ident.to_string();
		let inner_field_type = match inner_type_name.as_str() {
			"String" => {
				// For String arrays, check if max_length is provided
				if let Some(max_length) = config.max_length {
					let ml = max_length as u32;
					quote! { #migrations_crate::FieldType::VarChar(#ml) }
				} else {
					// Default to TEXT for string arrays without max_length
					quote! { #migrations_crate::FieldType::Text }
				}
			}
			"i32" => quote! { #migrations_crate::FieldType::Integer },
			"i64" => quote! { #migrations_crate::FieldType::BigInteger },
			"f32" => quote! { #migrations_crate::FieldType::Float },
			"f64" => quote! { #migrations_crate::FieldType::Double },
			"bool" => quote! { #migrations_crate::FieldType::Boolean },
			"Uuid" => quote! { #migrations_crate::FieldType::Uuid },
			_ => {
				return Err(syn::Error::new_spanned(
					ty,
					format!(
						"Cannot infer array element type for Vec<{}>. \
						 Use #[field(array_base_type = \"...\")] to specify explicitly.",
						inner_type_name
					),
				));
			}
		};

		return Ok(quote! {
			#migrations_crate::FieldType::Array(Box::new(#inner_field_type))
		});
	}

	Err(syn::Error::new_spanned(
		ty,
		"Cannot infer Vec element type. Use #[field(array_base_type = \"...\")] to specify explicitly.",
	))
}

/// Parse a base type string (e.g., "VARCHAR(50)", "INTEGER") to FieldType tokens
#[cfg(feature = "db-postgres")]
fn parse_base_type_string(
	base_type: &str,
	migrations_crate: &proc_macro2::TokenStream,
) -> Result<TokenStream> {
	let upper = base_type.to_uppercase();

	// Check for VARCHAR(n) pattern
	if upper.starts_with("VARCHAR(") && upper.ends_with(')') {
		let len_str = &upper[8..upper.len() - 1];
		if let Ok(length) = len_str.parse::<u32>() {
			return Ok(quote! { #migrations_crate::FieldType::VarChar(#length) });
		}
	}

	// Check for CHAR(n) pattern
	if upper.starts_with("CHAR(") && upper.ends_with(')') {
		let len_str = &upper[5..upper.len() - 1];
		if let Ok(length) = len_str.parse::<u32>() {
			return Ok(quote! { #migrations_crate::FieldType::Char(#length) });
		}
	}

	// Simple type mapping
	let field_type = match upper.as_str() {
		"INTEGER" | "INT" | "INT4" => quote! { #migrations_crate::FieldType::Integer },
		"BIGINT" | "INT8" => quote! { #migrations_crate::FieldType::BigInteger },
		"SMALLINT" | "INT2" => quote! { #migrations_crate::FieldType::SmallInteger },
		"TEXT" => quote! { #migrations_crate::FieldType::Text },
		"BOOLEAN" | "BOOL" => quote! { #migrations_crate::FieldType::Boolean },
		"REAL" | "FLOAT4" => quote! { #migrations_crate::FieldType::Float },
		"DOUBLE PRECISION" | "FLOAT8" => quote! { #migrations_crate::FieldType::Double },
		"UUID" => quote! { #migrations_crate::FieldType::Uuid },
		"DATE" => quote! { #migrations_crate::FieldType::Date },
		"TIME" => quote! { #migrations_crate::FieldType::Time },
		"TIMESTAMP" => quote! { #migrations_crate::FieldType::DateTime },
		"JSONB" => quote! { #migrations_crate::FieldType::Jsonb },
		"JSON" => quote! { #migrations_crate::FieldType::Json },
		_ => {
			return Err(syn::Error::new(
				proc_macro2::Span::call_site(),
				format!(
					"Unknown base type for array: '{}'. Use standard SQL types like \
					 INTEGER, BIGINT, VARCHAR(n), TEXT, BOOLEAN, etc.",
					base_type
				),
			));
		}
	};

	Ok(field_type)
}

/// Extract `Option<T>` and return (is_option, inner_type)
fn extract_option_type(ty: &Type) -> (bool, &Type) {
	if let Type::Path(type_path) = ty
		&& let Some(last_segment) = type_path.path.segments.last()
		&& last_segment.ident == "Option"
		&& let syn::PathArguments::AngleBracketed(args) = &last_segment.arguments
		&& let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first()
	{
		return (true, inner_ty);
	}
	(false, ty)
}

/// Generate field accessor methods that return FieldRef<M, T>
///
/// Generates const methods like:
/// ```rust,ignore
/// use reinhardt_db::orm::expressions::FieldRef;
/// use reinhardt_macros::model;
///
/// #[model(app_label = "users", table_name = "users")]
/// struct User {
///     #[field(primary_key = true)]
///     id: i64,
///     name: String,
/// }
///
/// // The #[model] attribute macro automatically generates:
/// impl User {
///     pub const fn field_id() -> FieldRef<User, i64> { FieldRef::new("id") }
///     pub const fn field_name() -> FieldRef<User, String> { FieldRef::new("name") }
/// }
/// ```
fn generate_field_accessors(struct_name: &syn::Ident, field_infos: &[FieldInfo]) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();

	let accessor_methods: Vec<_> = field_infos
		.iter()
		.filter(|field| !field.config.skip)
		.map(|field| {
			let field_name = &field.name;
			let field_type = &field.ty;
			let method_name = syn::Ident::new(&format!("field_{}", field_name), field_name.span());
			let field_name_str = field_name.to_string();

			quote! {
				/// Field accessor for type-safe field references
				///
				/// Returns a `FieldRef<#struct_name, #field_type>` that provides compile-time
				/// type safety for field operations.
				pub const fn #method_name() -> #orm_crate::expressions::FieldRef<#struct_name, #field_type> {
					#orm_crate::expressions::FieldRef::new(#field_name_str)
				}
			}
		})
		.collect();

	quote! {
		impl #struct_name {
			#(#accessor_methods)*
		}
	}
}

/// Generate accessor methods for ManyToMany relationships.
///
/// The generated accessor method internally calls `ManyToManyAccessor::new()`
/// with the field name, providing compile-time field name validation and
/// improved IDE support.
///
///
/// # Generated Code Characteristics
///
/// - **Method naming**: `{field_name}_accessor()`
/// - **Visibility**: `pub` (same as model)
/// - **Type parameters**: Inferred from `ManyToManyField<Source, Target>`
/// - **Documentation**: Auto-generated with field name
fn generate_m2m_accessor_methods(
	struct_name: &syn::Ident,
	field_infos: &[FieldInfo],
) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();

	let accessor_methods: Vec<_> = field_infos
		.iter()
		// Filter only ManyToManyField types
		.filter(|field| is_many_to_many_field_type(&field.ty))
		.filter_map(|field| {
			let field_name = &field.name;
			let field_name_str = field_name.to_string();

			// Method name: {field_name}_accessor
			let method_name = syn::Ident::new(
				&format!("{}_accessor", field_name),
				field_name.span()
			);

			// Extract Target from ManyToManyField<Source, Target>
			let target_ty = extract_m2m_target_type(&field.ty)?;

			let doc_comment = format!(
				"Create a ManyToManyAccessor for the '{}' relationship",
				field_name_str
			);

			Some(quote! {
				#[doc = #doc_comment]
				pub fn #method_name(
					&self,
					db: #orm_crate::connection::DatabaseConnection
				) -> #orm_crate::ManyToManyAccessor<#struct_name, #target_ty> {
					#orm_crate::ManyToManyAccessor::new(
						self,
						#field_name_str,
						db
					)
				}
			})
		})
		.collect();

	if accessor_methods.is_empty() {
		quote! {}
	} else {
		quote! {
			impl #struct_name {
				#(#accessor_methods)*
			}
		}
	}
}

/// Generate accessor methods for ForeignKey and OneToOne relationships.
///
/// The generated accessor method loads the related instance from the database
/// using the FK _id field value.
///
/// # Generated Code Characteristics
///
/// - **Method naming**: `{field_name}()`
/// - **Visibility**: `pub` (same as model)
/// - **Return type**: `Option<Target>`
/// - **Documentation**: Auto-generated with field name
fn generate_fk_accessor_methods(
	struct_name: &syn::Ident,
	field_infos: &[FieldInfo],
) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();
	let core_crate = get_reinhardt_core_crate();

	let accessor_methods: Vec<_> = field_infos
		.iter()
		// Filter only ForeignKeyField and OneToOneField
		.filter(|field| {
			is_foreign_key_field_type(&field.ty) || is_one_to_one_field_type(&field.ty)
		})
		.map(|field| {
			let field_name = &field.name;
			let field_name_str = field_name.to_string();

			// FK _id field name (e.g., user → user_id)
			let fk_id_field_name = syn::Ident::new(
				&format!("{}_id", field_name),
				field_name.span()
			);

			// Method name: {field_name}
			let method_name = field_name;

			// Extract Target from ForeignKeyField<Target> or OneToOneField<Target>
			let target_ty = extract_foreign_key_target_type(&field.ty);

			let doc_comment = format!(
				"Load the related '{}' instance from the database",
				field_name_str
			);

			quote! {
				#[doc = #doc_comment]
				pub async fn #method_name(
					&self,
					db: &#orm_crate::connection::DatabaseConnection
				) -> #core_crate::exception::Result<Option<#target_ty>> {
					use #orm_crate::Model;
					use #orm_crate::{FilterOperator, FilterValue};

					// Get FK _id value (getter returns &PrimaryKey)
					let fk_id = self.#fk_id_field_name();

					// Query the target model using the FK _id
					#target_ty::objects()
						.filter(
							#target_ty::field_id(),
							FilterOperator::Eq,
							FilterValue::String(fk_id.to_string())
						)
						.first_with_db(db)
						.await
				}
			}
		})
		.collect();

	if accessor_methods.is_empty() {
		quote! {}
	} else {
		quote! {
			impl #struct_name {
				#(#accessor_methods)*
			}
		}
	}
}

/// Generate static accessor methods for ForeignKey relationships.
///
/// The generated accessor method returns a `ForeignKeyAccessor` that can be used
/// to access reverse relationships in a type-safe manner.
///
/// # Generated Code Characteristics
///
/// - **Method naming**: `{field_name}_accessor()`
/// - **Visibility**: `pub` (same as model)
/// - **Return type**: `ForeignKeyAccessor<Self, Target>`
/// - **Static method**: No `&self` parameter required
///
/// # Generated Method
///
/// ```ignore
/// impl Tweet {
///     /// Get the ForeignKey accessor for the 'user' relationship
///     pub fn user_accessor() -> ForeignKeyAccessor<Tweet, User> {
///         ForeignKeyAccessor::new("user_id")
///     }
/// }
/// ```
///
/// # Usage
///
/// ```ignore
/// // Get reverse accessor for User → Tweets relationship
/// let tweets_accessor = Tweet::user_accessor().reverse(&user, db);
/// let tweets = tweets_accessor.all().await?;
/// ```
fn generate_fk_static_accessor_methods(
	struct_name: &syn::Ident,
	field_infos: &[FieldInfo],
) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();

	let accessor_methods: Vec<_> = field_infos
		.iter()
		// Filter only ForeignKeyField and OneToOneField
		.filter(|field| {
			is_foreign_key_field_type(&field.ty) || is_one_to_one_field_type(&field.ty)
		})
		.map(|field| {
			let field_name = &field.name;
			let field_name_str = field_name.to_string();

			// FK _id field name (e.g., user → user_id)
			let db_column = format!("{}_id", field_name_str);

			// Method name: {field_name}_accessor
			let method_name =
				syn::Ident::new(&format!("{}_accessor", field_name), field_name.span());

			// Extract Target from ForeignKeyField<Target> or OneToOneField<Target>
			let target_ty = extract_foreign_key_target_type(&field.ty);

			let doc_comment = format!(
				"Get the ForeignKey accessor for the '{}' relationship",
				field_name_str
			);

			quote! {
				#[doc = #doc_comment]
				pub fn #method_name() -> #orm_crate::ForeignKeyAccessor<#struct_name, #target_ty> {
					#orm_crate::ForeignKeyAccessor::new(#db_column)
				}
			}
		})
		.collect();

	if accessor_methods.is_empty() {
		quote! {}
	} else {
		quote! {
			impl #struct_name {
				#(#accessor_methods)*
			}
		}
	}
}

/// Make all fields module-local (non-pub) in the struct definition
fn make_fields_private(input: &mut DeriveInput) {
	if let Data::Struct(data) = &mut input.data
		&& let Fields::Named(fields) = &mut data.fields
	{
		for field in fields.named.iter_mut() {
			field.vis = syn::Visibility::Inherited;
		}
	}
}

/// Check if a type is Copy (returns value instead of reference)
fn is_copy_type(ty: &Type) -> bool {
	// Determine if type is primitive or Copy-derivable
	matches!(
		ty,
		Type::Path(path) if matches!(
			path.path.segments.last().map(|s| s.ident.to_string()).as_deref(),
			Some("i8" | "i16" | "i32" | "i64" | "i128" |
				 "u8" | "u16" | "u32" | "u64" | "u128" |
				 "f32" | "f64" | "bool" | "char" | "Uuid")
		)
	) || matches!(
		ty,
		Type::Path(path) if path.path.segments.iter().any(|seg|
			seg.ident == "DateTime"
		)
	)
}

/// Generate getter methods for all fields
fn generate_getter_methods(struct_name: &syn::Ident, field_infos: &[FieldInfo]) -> TokenStream {
	let getter_methods: Vec<_> = field_infos
		.iter()
		// Exclude ForeignKey, OneToOne, and skip_getter fields
		.filter(|field| {
			!is_foreign_key_field_type(&field.ty)
				&& !is_one_to_one_field_type(&field.ty)
				&& !field.config.skip_getter
		})
		.map(|field| {
			let field_name = &field.name;
			let field_type = &field.ty;
			let method_name = field_name;

			// Copy types return value, others return reference
			if is_copy_type(field_type) {
				quote! {
					#[doc = concat!("Get ", stringify!(#field_name))]
					pub fn #method_name(&self) -> #field_type {
						self.#field_name
					}
				}
			} else {
				quote! {
					#[doc = concat!("Get reference to ", stringify!(#field_name))]
					pub fn #method_name(&self) -> &#field_type {
						&self.#field_name
					}
				}
			}
		})
		.collect();

	quote! {
		impl #struct_name {
			#(#getter_methods)*
		}
	}
}

/// Generate setter methods for user-defined fields (excluding auto-generated)
fn generate_setter_methods(struct_name: &syn::Ident, field_infos: &[FieldInfo]) -> TokenStream {
	let setter_methods: Vec<_> = field_infos
		.iter()
		.filter(|f| !is_auto_generated_field(f) && !f.config.skip_getter)
		.map(|field| {
			let field_name = &field.name;
			let field_type = &field.ty;
			let setter_name = syn::Ident::new(&format!("set_{}", field_name), field_name.span());

			quote! {
				#[doc = concat!("Set ", stringify!(#field_name))]
				pub fn #setter_name(&mut self, value: #field_type) {
					self.#field_name = value;
				}
			}
		})
		.collect();

	quote! {
		impl #struct_name {
			#(#setter_methods)*
		}
	}
}

/// Implementation of the `Model` derive macro
pub(crate) fn model_derive_impl(mut input: DeriveInput) -> Result<TokenStream> {
	// Get the dynamically resolved crate paths
	let _reinhardt = get_reinhardt_crate();
	let orm_crate = get_reinhardt_orm_crate();

	// Make all fields module-local (non-pub)
	make_fields_private(&mut input);

	let struct_name = &input.ident;
	let generics = &input.generics;
	let where_clause = &generics.where_clause;

	// Parse model configuration
	let model_config = ModelConfig::from_attrs(&input.attrs, struct_name)?;
	let app_label = &model_config.app_label;
	let table_name = &model_config.table_name;

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

	// Process all fields
	let mut field_infos = Vec::new();
	let mut rel_fields = Vec::new();
	// Collect auto-generated FK _id field names for new() constructor
	let mut fk_id_field_names: Vec<syn::Ident> = Vec::new();

	for field in fields {
		// Check if this is auto-generated FK _id field
		// These are generated by #[model] attribute macro
		// Identified by: field name ends with "_id" AND type matches <T as Model>::PrimaryKey pattern
		let is_fk_id_field = if let Some(field_name) = &field.ident {
			let name_str = field_name.to_string();
			let field_ty = &field.ty;
			let type_str = quote!(#field_ty).to_string();

			// Check if field name ends with "_id" and type contains "Model :: PrimaryKey"
			// This pattern identifies auto-generated FK _id fields created by #[model(...)] macro
			name_str.ends_with("_id")
				&& type_str.contains("Model")
				&& type_str.contains("PrimaryKey")
		} else {
			false
		};

		if is_fk_id_field {
			// Collect the field name for new() constructor generation
			if let Some(field_name) = &field.ident {
				fk_id_field_names.push(field_name.clone());
			}
			// FK _id fields need getters but not setters, so add them to field_infos
			// with a flag to indicate they are auto-generated
		}

		let name = field
			.ident
			.clone()
			.ok_or_else(|| syn::Error::new_spanned(field, "Field must have a name"))?;
		let ty = field.ty.clone();
		let config = FieldConfig::from_attrs(&field.attrs)?;
		config.validate()?;

		// Parse #[rel(...)] attribute if present
		let rel = field
			.attrs
			.iter()
			.find(|attr| attr.path().is_ident("rel"))
			.map(RelAttribute::from_attribute)
			.transpose()?;

		// Collect relationship fields for later processing
		if let Some(ref rel_attr) = rel {
			rel_fields.push((name.clone(), rel_attr.clone()));
		}

		field_infos.push(FieldInfo {
			name,
			ty,
			config,
			rel,
			is_fk_id_field,
		});
	}

	// Extract ForeignKeyField and OneToOneField information
	let mut fk_field_infos: Vec<ForeignKeyFieldInfo> = Vec::new();
	for field_info in &field_infos {
		if let Some(ref rel_attr) = field_info.rel {
			// Check if this is a ForeignKeyField or OneToOneField type
			if let Some(target_type) = extract_fk_target_type(&field_info.ty) {
				let is_one_to_one = is_one_to_one_field_type(&field_info.ty);

				// Validate relationship type matches field type
				if is_one_to_one && rel_attr.rel_type != crate::rel::RelationType::OneToOne {
					return Err(syn::Error::new(
						rel_attr.span,
						"OneToOneField must use #[rel(one_to_one, ...)]",
					));
				}
				if is_foreign_key_field_type(&field_info.ty)
					&& rel_attr.rel_type != crate::rel::RelationType::ForeignKey
				{
					return Err(syn::Error::new(
						rel_attr.span,
						"ForeignKeyField must use #[rel(foreign_key, ...)]",
					));
				}

				// Generate ID column name: db_column or {field_name}_id
				let id_column_name = rel_attr
					.db_column
					.clone()
					.unwrap_or_else(|| format!("{}_id", field_info.name));

				fk_field_infos.push(ForeignKeyFieldInfo {
					field_name: field_info.name.clone(),
					target_type: target_type.clone(),
					id_column_name,
					related_name: rel_attr.related_name.clone(),
					is_one_to_one,
					rel_attr: rel_attr.clone(),
				});
			}
		}
	}

	// Find all primary key fields
	let pk_fields: Vec<_> = field_infos
		.iter()
		.filter(|f| f.config.primary_key)
		.collect();

	if pk_fields.is_empty() {
		return Err(syn::Error::new_spanned(
			struct_name,
			"Model must have at least one primary key field",
		));
	}

	// Determine if this is a composite primary key
	let is_composite_pk = pk_fields.len() > 1;

	// Find all indexed fields
	let indexed_fields: Vec<_> = field_infos
		.iter()
		.filter(|f| f.config.index.unwrap_or(false))
		.map(|f| f.name.to_string())
		.collect();

	// Find all check constraint fields
	let check_constraints: Vec<(String, String)> = field_infos
		.iter()
		.filter_map(|f| {
			f.config
				.check
				.as_ref()
				.map(|expr| (f.name.to_string(), expr.clone()))
		})
		.collect();

	// Extract check constraint names and expressions for code generation
	let check_constraint_names: Vec<String> = check_constraints
		.iter()
		.map(|(field_name, _)| format!("{}_check", field_name))
		.collect();
	let check_constraint_expressions: Vec<String> = check_constraints
		.iter()
		.map(|(_, expr)| expr.clone())
		.collect();

	// Process unique constraints from model config
	let unique_constraints: Vec<(Vec<String>, Option<String>, Option<String>)> = model_config
		.constraints
		.iter()
		.map(|c| match c {
			ConstraintSpec::Unique {
				fields,
				name,
				condition,
			} => (fields.clone(), name.clone(), condition.clone()),
		})
		.collect();

	// Generate unique constraint names and definitions for code generation
	let unique_constraint_names: Vec<String> = unique_constraints
		.iter()
		.map(|(fields, name, _)| {
			if let Some(n) = name {
				n.clone()
			} else {
				// Auto-generate name: {table_name}_{field1}_{field2}_uniq
				format!("{}_{}_uniq", table_name, fields.join("_"))
			}
		})
		.collect();

	let unique_constraint_definitions: Vec<String> = unique_constraints
		.iter()
		.map(|(fields, _, condition)| {
			let fields_str = fields.join(", ");
			if let Some(cond) = condition {
				format!("UNIQUE ({}) WHERE {}", fields_str, cond)
			} else {
				format!("UNIQUE ({})", fields_str)
			}
		})
		.collect();

	// Token streams that register each model-level UNIQUE constraint
	// (e.g., from `unique_together`) into ModelMetadata.constraints so the
	// migration autodetector can emit AddConstraint operations.
	// See reinhardt-web#4022.
	let unique_constraint_field_lists: Vec<Vec<String>> = unique_constraints
		.iter()
		.map(|(fields, _, _)| fields.clone())
		.collect();

	// Define composite_pk_type_def and holder for code generation
	let composite_pk_type_def: Option<TokenStream>;
	// Note: composite_pk_type_holder is only assigned in the composite PK branch,
	// but must be declared here to extend its lifetime beyond the if-else scope
	#[allow(unused_assignments)]
	let mut composite_pk_type_holder: Option<Type> = None;

	// For single PK, extract field info
	let (pk_name, _pk_ty, pk_is_option, pk_type) = if !is_composite_pk {
		composite_pk_type_def = None;
		let pk_field = pk_fields[0];
		let pk_name = &pk_field.name;
		let pk_ty = &pk_field.ty;
		let (pk_is_option, pk_inner_ty) = extract_option_type(pk_ty);
		let pk_type = if pk_is_option { pk_inner_ty } else { pk_ty };
		(pk_name, pk_ty, pk_is_option, pk_type)
	} else {
		// Composite primary key: generate dedicated composite PK type
		let composite_pk_name =
			syn::Ident::new(&format!("{}CompositePk", struct_name), struct_name.span());

		// Generate the composite PK type definition
		composite_pk_type_def = Some(generate_composite_pk_type(struct_name, &pk_fields));

		// Use the generated composite PK type and store in holder (avoid temporary variable)
		composite_pk_type_holder = Some(parse_quote! { #composite_pk_name });
		let composite_pk_type_ref = composite_pk_type_holder.as_ref().unwrap();

		// Use first field name for primary_key_field() (legacy API compatibility)
		let first_pk_name = &pk_fields[0].name;
		(
			first_pk_name,
			composite_pk_type_ref,
			false,
			composite_pk_type_ref,
		)
	};

	// Generate field_metadata implementation
	let field_metadata_items = generate_field_metadata(&field_infos, &fk_field_infos)?;

	// Generate auto-registration code
	let registration_code = generate_registration_code(
		struct_name,
		app_label,
		table_name,
		&field_infos,
		&fk_field_infos,
		&unique_constraint_names,
		&unique_constraint_field_lists,
	)?;

	// Generate relationship registration code for RELATIONSHIPS registry
	let relationship_registrations =
		generate_relationship_registrations(struct_name, app_label, &field_infos, &fk_field_infos);

	// Generate primary_key() and set_primary_key() implementations
	let (pk_impl, set_pk_impl, composite_pk_impl) = if is_composite_pk {
		// Composite primary key implementation
		let composite_impl = generate_composite_pk_impl(&pk_fields);

		// For composite PK, use the generated composite PK type
		let pk_field_names: Vec<_> = pk_fields.iter().map(|f| &f.name).collect();

		// Check if any field is Option
		let has_option_fields = pk_fields.iter().any(|f| {
			let (is_option, _) = extract_option_type(&f.ty);
			is_option
		});

		let pk_getter = if has_option_fields {
			// If any field is Option, check all fields have values
			quote! {
				fn primary_key(&self) -> Option<Self::PrimaryKey> {
					// Check if all fields have values
					if #(self.#pk_field_names.is_some())&&* {
						Some(Self::PrimaryKey::new(
							#(self.#pk_field_names.clone().unwrap()),*
						))
					} else {
						None
					}
				}
			}
		} else {
			// All fields are non-Option, construct composite PK directly
			quote! {
				fn primary_key(&self) -> Option<Self::PrimaryKey> {
					Some(Self::PrimaryKey::new(
						#(self.#pk_field_names.clone()),*
					))
				}
			}
		};

		let pk_setter = if has_option_fields {
			quote! {
				fn set_primary_key(&mut self, value: Self::PrimaryKey) {
					#(
						self.#pk_field_names = Some(value.#pk_field_names);
					)*
				}
			}
		} else {
			quote! {
				fn set_primary_key(&mut self, value: Self::PrimaryKey) {
					#(
						self.#pk_field_names = value.#pk_field_names;
					)*
				}
			}
		};

		(pk_getter, pk_setter, composite_impl)
	} else {
		// Single primary key implementation
		let (pk_getter, pk_setter) = if pk_is_option {
			// If primary key is Option<T>, extract the inner value
			(
				quote! {
					fn primary_key(&self) -> Option<Self::PrimaryKey> {
						self.#pk_name.clone()
					}
				},
				quote! {
					fn set_primary_key(&mut self, value: Self::PrimaryKey) {
						self.#pk_name = Some(value);
					}
				},
			)
		} else {
			// If primary key is not Option, wrap in Some
			(
				quote! {
					fn primary_key(&self) -> Option<Self::PrimaryKey> {
						Some(self.#pk_name.clone())
					}
				},
				quote! {
					fn set_primary_key(&mut self, value: Self::PrimaryKey) {
						self.#pk_name = value;
					}
				},
			)
		};

		(pk_getter, pk_setter, quote! {})
	};

	// Generate field accessor methods
	let field_accessors = generate_field_accessors(struct_name, &field_infos);

	// Generate ManyToMany accessor methods
	let m2m_accessor_methods = generate_m2m_accessor_methods(struct_name, &field_infos);

	// Generate ForeignKey and OneToOne accessor methods
	let fk_accessor_methods = generate_fk_accessor_methods(struct_name, &field_infos);

	// Generate relationship metadata
	let relationship_metadata = generate_relationship_metadata(&rel_fields, app_label, struct_name);

	// Generate new() constructor function
	let new_fn_impl = generate_new_function(struct_name, &field_infos, &fk_id_field_names);

	// Generate typestate build() builder (non-breaking addition alongside new()).
	// See issue #4400.
	let build_fn_impl = generate_build_function(struct_name, &field_infos, &fk_id_field_names);

	// Generate getter/setter methods
	let getters = generate_getter_methods(struct_name, &field_infos);
	let setters = generate_setter_methods(struct_name, &field_infos);

	// Generate static FK accessor methods for type-safe reverse relationship access
	let fk_static_accessor_methods = generate_fk_static_accessor_methods(struct_name, &field_infos);

	// Generate field selector struct for type-safe JOIN/GROUP BY/HAVING operations
	let field_selector_name =
		syn::Ident::new(&format!("{}Fields", struct_name), struct_name.span());
	let field_selector_struct = generate_field_selector_struct(struct_name, &field_infos);

	// Conditionally emit `impl HasCustomManager for ...` when the model
	// requested a custom manager via `#[model(manager = ...)]` (Issue #3980).
	// Without this attribute we emit nothing, preserving complete backward
	// compatibility with existing models.
	let custom_manager_impl = match &model_config.manager {
		Some(path) => quote! {
			impl #generics #orm_crate::HasCustomManager for #struct_name #generics #where_clause {
				type Manager = #path;
			}
		},
		None => quote! {},
	};

	// Generate the Model implementation
	let expanded = quote! {
		// Generate composite PK type definition if needed
		#composite_pk_type_def

		// Generate new() constructor function
		#new_fn_impl

		// Generate typestate build() builder (non-breaking addition, see #4400)
		#build_fn_impl

		// Generate getter methods for all fields
		#getters

		// Generate setter methods for user-defined fields
		#setters

		// Generate field accessor methods for type-safe field references
		#field_accessors

		// Generate ManyToMany accessor methods
		#m2m_accessor_methods

		// Generate ForeignKey and OneToOne accessor methods
		#fk_accessor_methods

		// Generate static FK accessor methods for type-safe reverse relationship access
		#fk_static_accessor_methods

		impl #generics #orm_crate::Model for #struct_name #generics #where_clause {
			type PrimaryKey = #pk_type;
			type Fields = #field_selector_name;

			fn table_name() -> &'static str {
				#table_name
			}

			fn new_fields() -> Self::Fields {
				#field_selector_name::new()
			}

			fn app_label() -> &'static str {
				#app_label
			}

			fn primary_key_field() -> &'static str {
				stringify!(#pk_name)
			}

			#pk_impl

			#set_pk_impl

			#composite_pk_impl

			fn field_metadata() -> Vec<#orm_crate::inspection::FieldInfo> {
				vec![
					#(#field_metadata_items),*
				]
			}

			fn index_metadata() -> Vec<#orm_crate::inspection::IndexInfo> {
				vec![
					#(
						#orm_crate::inspection::IndexInfo {
							name: format!("{}_{}_idx", <Self as #orm_crate::Model>::table_name(), #indexed_fields),
							fields: vec![#indexed_fields.to_string()],
							unique: false,
							condition: None,
						}
					),*
				]
			}

			fn constraint_metadata() -> Vec<#orm_crate::inspection::ConstraintInfo> {
				let mut constraints = Vec::new();
				// Check constraints
				#(
					constraints.push(#orm_crate::inspection::ConstraintInfo {
						name: #check_constraint_names.to_string(),
						constraint_type: #orm_crate::inspection::ConstraintType::Check,
						definition: #check_constraint_expressions.to_string(),
					});
				)*
				// Unique constraints
				#(
					constraints.push(#orm_crate::inspection::ConstraintInfo {
						name: #unique_constraint_names.to_string(),
						constraint_type: #orm_crate::inspection::ConstraintType::Unique,
						definition: #unique_constraint_definitions.to_string(),
					});
				)*
				constraints
			}

			#relationship_metadata
		}

		// Conditional `impl HasCustomManager` (Issue #3980) — empty when the
		// model did not opt in to a custom manager.
		#custom_manager_impl

		#registration_code

		// Register relationships in RELATIONSHIPS distributed slice
		#relationship_registrations

		// Generate field selector struct for type-safe JOIN/GROUP BY/HAVING operations
		#field_selector_struct
	};

	Ok(expanded)
}

/// Generate FieldInfo construction for field_metadata()
fn generate_field_metadata(
	field_infos: &[FieldInfo],
	fk_field_infos: &[ForeignKeyFieldInfo],
) -> Result<Vec<TokenStream>> {
	let mut items = Vec::new();

	// Filter out skipped, ManyToMany, ForeignKeyField, OneToOneField, and FK _id fields
	let regular_fields: Vec<_> = field_infos
		.iter()
		.filter(|f| {
			// Exclude fields marked with #[field(skip = true)]
			if f.config.skip {
				return false;
			}
			// Exclude FK _id fields (auto-generated by #[model] attribute macro)
			if f.is_fk_id_field {
				return false;
			}
			// Exclude ManyToMany
			if f.rel
				.as_ref()
				.map(|r| matches!(r.rel_type, crate::rel::RelationType::ManyToMany))
				.unwrap_or(false)
			{
				return false;
			}
			// Exclude ForeignKeyField and OneToOneField (we generate _id fields instead)
			if is_relationship_field_type(&f.ty) {
				return false;
			}
			true
		})
		.collect();

	let orm_crate = get_reinhardt_orm_crate();

	// If there are no regular fields, return empty vec
	if regular_fields.is_empty() {
		let _ = &orm_crate; // Suppress unused warning
	}

	for field_info in regular_fields {
		let name = field_info.name.to_string();
		let field_type_path = field_type_to_metadata_string(&field_info.ty, &field_info.config)?;
		let _field_type = map_type_to_field_type(&field_info.ty, &field_info.config)?;
		let config = &field_info.config;

		let (is_option, _) = extract_option_type(&field_info.ty);
		let nullable = config.null.unwrap_or(is_option);
		let primary_key = config.primary_key;
		let unique = config.unique.unwrap_or(false);
		let blank = config.blank.unwrap_or(false);
		let editable = config.editable.unwrap_or(true);

		// Build attributes map
		let mut attrs = Vec::new();
		if let Some(max_length) = config.max_length {
			attrs.push(quote! {
				attributes.insert(
					"max_length".to_string(),
					#orm_crate::fields::FieldKwarg::Uint(#max_length)
				);
			});
		}

		// Add validator attributes
		if let Some(email) = config.email
			&& email
		{
			attrs.push(quote! {
				attributes.insert(
					"email".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(true)
				);
			});
		}
		if let Some(url) = config.url
			&& url
		{
			attrs.push(quote! {
				attributes.insert(
					"url".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(true)
				);
			});
		}
		if let Some(min_length) = config.min_length {
			attrs.push(quote! {
				attributes.insert(
					"min_length".to_string(),
					#orm_crate::fields::FieldKwarg::Uint(#min_length)
				);
			});
		}
		if let Some(min_value) = config.min_value {
			attrs.push(quote! {
				attributes.insert(
					"min_value".to_string(),
					#orm_crate::fields::FieldKwarg::Int(#min_value)
				);
			});
		}
		if let Some(max_value) = config.max_value {
			attrs.push(quote! {
				attributes.insert(
					"max_value".to_string(),
					#orm_crate::fields::FieldKwarg::Int(#max_value)
				);
			});
		}

		// Generated Columns
		if let Some(ref generated_expr) = config.generated {
			attrs.push(quote! {
				attributes.insert(
					"generated".to_string(),
					#orm_crate::fields::FieldKwarg::String(#generated_expr.to_string())
				);
			});
		}
		if let Some(generated_stored) = config.generated_stored {
			attrs.push(quote! {
				attributes.insert(
					"generated_stored".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#generated_stored)
				);
			});
		}
		#[cfg(any(feature = "db-mysql", feature = "db-sqlite"))]
		if let Some(generated_virtual) = config.generated_virtual {
			attrs.push(quote! {
				attributes.insert(
					"generated_virtual".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#generated_virtual)
				);
			});
		}

		// Identity/Auto-increment
		#[cfg(feature = "db-postgres")]
		if let Some(identity_always) = config.identity_always {
			attrs.push(quote! {
				attributes.insert(
					"identity_always".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#identity_always)
				);
			});
		}
		#[cfg(feature = "db-postgres")]
		if let Some(identity_by_default) = config.identity_by_default {
			attrs.push(quote! {
				attributes.insert(
					"identity_by_default".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#identity_by_default)
				);
			});
		}
		#[cfg(feature = "db-mysql")]
		if let Some(auto_increment) = config.auto_increment {
			attrs.push(quote! {
				attributes.insert(
					"auto_increment".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#auto_increment)
				);
			});
		}
		#[cfg(feature = "db-sqlite")]
		if let Some(autoincrement) = config.autoincrement {
			attrs.push(quote! {
				attributes.insert(
					"autoincrement".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#autoincrement)
				);
			});
		}

		// Character Set & Collation
		if let Some(ref collate) = config.collate {
			attrs.push(quote! {
				attributes.insert(
					"collate".to_string(),
					#orm_crate::fields::FieldKwarg::String(#collate.to_string())
				);
			});
		}
		#[cfg(feature = "db-mysql")]
		if let Some(ref character_set) = config.character_set {
			attrs.push(quote! {
				attributes.insert(
					"character_set".to_string(),
					#orm_crate::fields::FieldKwarg::String(#character_set.to_string())
				);
			});
		}

		// Comment
		#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
		if let Some(ref comment) = config.comment {
			attrs.push(quote! {
				attributes.insert(
					"comment".to_string(),
					#orm_crate::fields::FieldKwarg::String(#comment.to_string())
				);
			});
		}

		// Storage Optimization (PostgreSQL)
		#[cfg(feature = "db-postgres")]
		if let Some(ref storage) = config.storage {
			let storage_str = match storage {
				StorageStrategy::Plain => "plain",
				StorageStrategy::Extended => "extended",
				StorageStrategy::External => "external",
				StorageStrategy::Main => "main",
			};
			attrs.push(quote! {
				attributes.insert(
					"storage".to_string(),
					#orm_crate::fields::FieldKwarg::String(#storage_str.to_string())
				);
			});
		}
		#[cfg(feature = "db-postgres")]
		if let Some(ref compression) = config.compression {
			let compression_str = match compression {
				CompressionMethod::Pglz => "pglz",
				CompressionMethod::Lz4 => "lz4",
			};
			attrs.push(quote! {
				attributes.insert(
					"compression".to_string(),
					#orm_crate::fields::FieldKwarg::String(#compression_str.to_string())
				);
			});
		}

		// ON UPDATE Trigger (MySQL)
		#[cfg(feature = "db-mysql")]
		if let Some(on_update_current_timestamp) = config.on_update_current_timestamp {
			attrs.push(quote! {
				attributes.insert(
					"on_update_current_timestamp".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#on_update_current_timestamp)
				);
			});
		}

		// Invisible Columns (MySQL)
		#[cfg(feature = "db-mysql")]
		if let Some(invisible) = config.invisible {
			attrs.push(quote! {
				attributes.insert(
					"invisible".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#invisible)
				);
			});
		}

		// Full-Text Index (PostgreSQL, MySQL)
		#[cfg(any(feature = "db-postgres", feature = "db-mysql"))]
		if let Some(fulltext) = config.fulltext {
			attrs.push(quote! {
				attributes.insert(
					"fulltext".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#fulltext)
				);
			});
		}

		// Numeric Attributes (MySQL, deprecated)
		#[cfg(feature = "db-mysql")]
		if let Some(unsigned) = config.unsigned {
			attrs.push(quote! {
				attributes.insert(
					"unsigned".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#unsigned)
				);
			});
		}
		#[cfg(feature = "db-mysql")]
		if let Some(zerofill) = config.zerofill {
			attrs.push(quote! {
				attributes.insert(
					"zerofill".to_string(),
					#orm_crate::fields::FieldKwarg::Bool(#zerofill)
				);
			});
		}

		let db_column_value = match &config.db_column {
			Some(col) => quote! { Some(#col.to_string()) },
			None => quote! { None },
		};

		let item = quote! {
			{
				let mut attributes = ::std::collections::HashMap::new();
				#(#attrs)*

				#orm_crate::inspection::FieldInfo {
					name: #name.to_string(),
					field_type: #field_type_path.to_string(),
					nullable: #nullable,
					primary_key: #primary_key,
					unique: #unique,
					blank: #blank,
					editable: #editable,
					default: None,
					db_default: None,
					db_column: #db_column_value,
					choices: None,
					attributes,
				}
			}
		};

		items.push(item);
	}

	// Generate _id field metadata for ForeignKeyField and OneToOneField
	for fk_info in fk_field_infos {
		let name = &fk_info.id_column_name;
		let nullable = fk_info.rel_attr.null.unwrap_or(false);
		let unique = fk_info.is_one_to_one; // OneToOne fields have UNIQUE constraint
		let db_index = fk_info.rel_attr.db_index.unwrap_or(true); // FK fields are indexed by default

		// Generate the field type based on target model's primary key
		// We use IntegerField as a safe default; runtime will resolve the actual type
		let field_type_path = "IntegerField";

		let item = quote! {
			{
				let mut attributes = ::std::collections::HashMap::new();
				if #db_index {
					attributes.insert(
						"db_index".to_string(),
						#orm_crate::fields::FieldKwarg::Bool(true)
					);
				}

				#orm_crate::inspection::FieldInfo {
					name: #name.to_string(),
					field_type: #field_type_path.to_string(),
					nullable: #nullable,
					primary_key: false,
					unique: #unique,
					blank: false,
					editable: true,
					default: None,
					db_default: None,
					db_column: None,
					choices: None,
					attributes,
				}
			}
		};

		items.push(item);
	}

	Ok(items)
}

/// Generate automatic registration code using ctor
fn generate_registration_code(
	struct_name: &syn::Ident,
	app_label: &str,
	table_name: &str,
	field_infos: &[FieldInfo],
	fk_field_infos: &[ForeignKeyFieldInfo],
	unique_constraint_names: &[String],
	unique_constraint_field_lists: &[Vec<String>],
) -> Result<TokenStream> {
	let migrations_crate = get_reinhardt_migrations_crate();
	let orm_crate = get_reinhardt_orm_crate();
	let model_name = struct_name.to_string();
	let register_fn_name = syn::Ident::new(
		&format!(
			"__register_{}_model",
			struct_name.to_string().to_lowercase()
		),
		struct_name.span(),
	);

	// Separate ManyToMany fields from regular fields (also exclude ForeignKeyField/OneToOneField and FK _id fields)
	let (m2m_fields, regular_fields_with_fk_id): (Vec<_>, Vec<_>) =
		field_infos.iter().partition(|f| {
			// Exclude ManyToMany
			if f.rel
				.as_ref()
				.map(|r| matches!(r.rel_type, crate::rel::RelationType::ManyToMany))
				.unwrap_or(false)
			{
				return true;
			}
			// Exclude ForeignKeyField and OneToOneField (they are virtual, we generate _id fields instead)
			if is_relationship_field_type(&f.ty) {
				return true;
			}
			false
		});

	// Filter out FK _id fields and skip fields from regular_fields
	let regular_fields: Vec<_> = regular_fields_with_fk_id
		.into_iter()
		.filter(|f| !f.is_fk_id_field && !f.config.skip)
		.collect();

	// Generate field registration code for regular fields
	let mut field_registrations = Vec::new();
	for field_info in &regular_fields {
		let field_name = field_info.name.to_string();
		let field_type = map_type_to_field_type(&field_info.ty, &field_info.config)?;
		let config = &field_info.config;

		let mut params = Vec::new();
		if config.primary_key {
			params.push(quote! { .with_param("primary_key", "true") });
		}

		// auto_increment emission for PK and non-PK fields is handled below,
		// gated on `is_integer_primary_key_type` so non-integer PKs (Uuid,
		// String, custom types) do not accidentally inherit
		// `auto_increment = "true"`. See reinhardt-web#4378.

		// not_null: infer from Rust Option type
		let (is_option, _) = extract_option_type(&field_info.ty);
		let is_not_null = if let Some(null) = config.null {
			!null
		} else if config.primary_key {
			true
		} else {
			!is_option
		};
		if is_not_null {
			params.push(quote! { .with_param("not_null", "true") });
		}

		if let Some(max_length) = config.max_length {
			let ml_str = max_length.to_string();
			params.push(quote! { .with_param("max_length", #ml_str) });
		}
		if let Some(null) = config.null {
			let null_str = null.to_string();
			params.push(quote! { .with_param("null", #null_str) });
		}
		if let Some(unique) = config.unique
			&& unique
		{
			params.push(quote! { .with_param("unique", "true") });
		}
		// Infer nullable from Rust type when not explicitly set.
		//
		// PK columns are always NOT NULL at the DB level. The Option<T>
		// wrapper for PKs is a Rust-side convention to allow `id = None`
		// before the DB assigns the auto-increment value, not a DB-level
		// nullability statement. Emitting `null = "true"` for `Option<T>`
		// PKs would diverge from `column_def_to_field_state`'s migration-
		// replay output (which derives nullability from `not_null`) and
		// surface as a spurious `AlterColumn` for the unchanged PK under
		// offline state reconstruction.
		//
		// See reinhardt-web#4052 for the residual regression.
		if config.null.is_none() {
			let (is_option, _) = extract_option_type(&field_info.ty);
			let nullable = !config.primary_key && is_option;
			let null_str = nullable.to_string();
			params.push(quote! { .with_param("null", #null_str) });
		}
		// auto_increment: explicit value or default true for integer PKs
		if config.primary_key && is_integer_primary_key_type(&field_info.ty) {
			let auto_inc = config.auto_increment.unwrap_or(true);
			let auto_inc_str = auto_inc.to_string();
			params.push(quote! { .with_param("auto_increment", #auto_inc_str) });
		} else if let Some(auto_increment) = config.auto_increment {
			let auto_inc_str = auto_increment.to_string();
			params.push(quote! { .with_param("auto_increment", #auto_inc_str) });
		}
		// auto_now / auto_now_add params
		if config.auto_now == Some(true) {
			params.push(quote! { .with_param("auto_now", "true") });
		}
		if config.auto_now_add == Some(true) {
			params.push(quote! { .with_param("auto_now_add", "true") });
		}

		// Propagate `#[field(default = ...)]` into FieldState.params so the
		// autodetector emits `ColumnDefinition.default = Some(<sql>)`. Without
		// this, makemigrations dropped the default on the floor and the
		// runner produced `ADD COLUMN ... NOT NULL` with no DEFAULT — see
		// reinhardt-web#4447. Unrecognised expression forms are intentionally
		// skipped (today's behaviour) rather than emitted as garbage.
		if let Some(ref default_expr) = config.default
			&& let Some(serialized) = serialize_field_default(default_expr)
		{
			params.push(quote! { .with_param("default", #serialized) });
		}

		// Generate ForeignKey information if present
		let fk_registration = if let Some(fk_spec) = &config.foreign_key {
			match fk_spec {
				ForeignKeySpec::Type(ty) => {
					// For direct type reference, extract type name and convert to snake_case
					let type_name_str = quote! { #ty }.to_string();
					quote! {
						.with_foreign_key({
							// Extract last segment of type path and convert to snake_case
							let type_name = #type_name_str;
							let last_segment = type_name.split("::").last().unwrap_or(&type_name);
							let referenced_table = #migrations_crate::to_snake_case(last_segment);

							#migrations_crate::ForeignKeyInfo {
								referenced_table,
								referenced_column: "id".to_string(),
								on_delete: #migrations_crate::ForeignKeyAction::Cascade,
								on_update: #migrations_crate::ForeignKeyAction::Cascade,
							}
						})
					}
				}
				ForeignKeySpec::AppModel {
					app_label,
					model_name,
				} => {
					let table_name_str = format!("{}_{}", app_label, model_name.to_lowercase());
					quote! {
						.with_foreign_key(#migrations_crate::ForeignKeyInfo {
							referenced_table: #table_name_str.to_string(),
							referenced_column: "id".to_string(),
							on_delete: #migrations_crate::ForeignKeyAction::Cascade,
							on_update: #migrations_crate::ForeignKeyAction::Cascade,
						})
					}
				}
			}
		} else {
			quote! {}
		};

		field_registrations.push(quote! {
			metadata.add_field(
				#field_name.to_string(),
				#migrations_crate::model_registry::FieldMetadata::new(#field_type)
					#(#params)*
					#fk_registration
			);
		});
	}

	// Generate ManyToMany field registration code
	let mut m2m_registrations = Vec::new();
	for field_info in &m2m_fields {
		let field_name = field_info.name.to_string();

		// Get target model name: from #[rel(to = "...")] or infer from ManyToManyField<Source, Target>
		let to_model = if let Some(rel) = &field_info.rel
			&& let Some(to_type) = &rel.to
		{
			// Explicit 'to' parameter in #[rel(...)]
			quote! { #to_type }.to_string()
		} else if let Some(target_ty) = extract_m2m_target_type(&field_info.ty) {
			// Infer from ManyToManyField<Source, Target> - extract Target type name
			if let Type::Path(type_path) = target_ty
				&& let Some(last_segment) = type_path.path.segments.last()
			{
				last_segment.ident.to_string()
			} else {
				continue; // Skip if cannot extract target type
			}
		} else {
			continue; // Skip if no 'to' parameter and cannot infer from type
		};

		// Get relationship attributes (may be None if no #[rel(...)] attribute)
		let related_name = field_info
			.rel
			.as_ref()
			.and_then(|r| r.related_name.as_ref())
			.map(|r| quote! { Some(#r.to_string()) })
			.unwrap_or(quote! { None });
		let through = field_info
			.rel
			.as_ref()
			.and_then(|r| r.through.as_ref())
			.map(|t| quote! { Some(#t.to_string()) })
			.unwrap_or(quote! { None });
		let source_field = field_info
			.rel
			.as_ref()
			.and_then(|r| r.source_field.as_ref())
			.map(|s| quote! { Some(#s.to_string()) })
			.unwrap_or(quote! { None });
		let target_field = field_info
			.rel
			.as_ref()
			.and_then(|r| r.target_field.as_ref())
			.map(|t| quote! { Some(#t.to_string()) })
			.unwrap_or(quote! { None });

		m2m_registrations.push(quote! {
			metadata.add_many_to_many(
				#migrations_crate::model_registry::ManyToManyMetadata {
					field_name: #field_name.to_string(),
					to_model: #to_model.to_string(),
					related_name: #related_name,
					through: #through,
					source_field: #source_field,
					target_field: #target_field,
					db_constraint_prefix: None,
				}
			);
		});
	}

	// Generate FK _id field registration code
	let mut fk_id_registrations = Vec::new();
	for fk_info in fk_field_infos {
		let id_column_name = &fk_info.id_column_name;
		let nullable = fk_info.rel_attr.null.unwrap_or(false);
		let unique = fk_info.is_one_to_one; // OneToOne fields have UNIQUE constraint
		let db_index = fk_info.rel_attr.db_index.unwrap_or(true); // FK fields are indexed by default
		let not_null_str = (!nullable).to_string();
		let unique_str = unique.to_string();
		let db_index_str = db_index.to_string();

		// Extract "User" from ForeignKeyField<User>
		let target_model_name = if let Type::Path(type_path) = &fk_info.target_type {
			type_path
				.path
				.segments
				.last()
				.map(|seg| seg.ident.to_string())
				.unwrap_or_else(|| "Unknown".to_string())
		} else {
			"Unknown".to_string()
		};

		// `fk_target_app` is sourced from the FK target type itself via
		// `<TargetType as Model>::app_label()` — the model's
		// authoritative app label, which respects `#[app_label = "..."]`
		// overrides and any future remapping. The macro deliberately
		// does NOT try to guess the app label from the syntactic path
		// the user wrote: a path like `reinhardt_auth::User` is just a
		// crate / module name and can diverge from the registered app
		// label (e.g. crate `reinhardt_auth` registering its app as
		// `"auth"` via `#[app_label("auth")]`), and a bare ident
		// `User` can come from a `use`-import out of another crate.
		// Reading `app_label()` off the type sidesteps both pitfalls.
		//
		// The qualified lookup at FK resolution time uses this value,
		// so the qualifier always matches the registry key regardless
		// of whether the target is referenced by a bare ident, a
		// `use`-imported ident, or an absolute path. The user can
		// disambiguate same-name models across apps by writing a
		// path-typed FK target (`ForeignKeyField<reinhardt_auth::User>`)
		// or by relying on Rust's normal scoping — Rust resolves the
		// type and the macro reads the type's own app label.
		//
		// We only emit `fk_target_app` for `Type::Path` target types
		// (the common case for `ForeignKeyField<T>`). Other shapes
		// (`fn` types, trait objects, etc.) cannot be FK targets and
		// don't reach this branch in practice.
		//
		// See issue #4436 and PR #4440 review threads on
		// `model_derive.rs` line 2863 and `operations.rs` line 2836.
		let fk_target_app_chain = if let Type::Path(_) = &fk_info.target_type {
			let target_ty = &fk_info.target_type;
			quote! {
				.with_param(
					"fk_target_app",
					<#target_ty as #orm_crate::Model>::app_label(),
				)
			}
		} else {
			quote! {}
		};

		// The `FieldType::Uuid` value here is a placeholder. The real column
		// type is resolved at migration-generation time by looking up the
		// target model's primary key in the global `ModelRegistry`
		// (see `ColumnDefinition::from_field_state`). The placeholder is
		// required because the target model's PK type is not knowable at
		// macro-expansion time (the registry is populated at runtime via
		// `#[ctor::ctor]`).
		//
		// `nullable` is set on the structured `FieldMetadata.nullable`
		// field (single source of truth — `FieldMetadata::to_model_state`
		// reads it directly when constructing `FieldState`). `not_null`
		// is still emitted as a parameter because `ColumnDefinition::from_field_state`
		// reads `params["not_null"]` to set its boolean. Reflects the
		// non-`Option<_>` nullability of `ForeignKeyField<T>` (issue #4431).
		// Follow-up tracked in #4436 to migrate `from_field_state` to
		// derive `not_null` from `FieldState.nullable` and drop this param.
		fk_id_registrations.push(quote! {
			metadata.add_field(
				#id_column_name.to_string(),
				#migrations_crate::model_registry::FieldMetadata::new(
					#migrations_crate::FieldType::Uuid
				)
					.with_nullable(#nullable)
					.with_param("not_null", #not_null_str)
					.with_param("unique", #unique_str)
					.with_param("db_index", #db_index_str)
					.with_param("fk_target", #target_model_name)
					#fk_target_app_chain
			);
		});
	}

	// Generate type path for global model registry
	let type_path = quote! { #struct_name }.to_string();

	// Build per-constraint registration blocks for ModelMetadata.
	// We walk three parallel vectors (names + field lists) and emit one
	// `metadata.add_constraint(...)` call per declared `unique_together`.
	// See reinhardt-web#4022.
	let constraint_registrations: Vec<TokenStream> = unique_constraint_names
		.iter()
		.zip(unique_constraint_field_lists.iter())
		.map(|(name, fields)| {
			let field_lits = fields.iter().map(|f| quote! { #f.to_string() });
			quote! {
				metadata.add_constraint(
					#migrations_crate::ConstraintDefinition {
						name: #name.to_string(),
						constraint_type: "unique".to_string(),
						fields: vec![ #(#field_lits),* ],
						expression: None,
						foreign_key_info: None,
					}
				);
			}
		})
		.collect();

	let code = quote! {
		#[::ctor::ctor]
		fn #register_fn_name() {
			use #migrations_crate::model_registry::ModelMetadata;

			// Register in migration registry
			let mut metadata = ModelMetadata::new(
				#app_label,
				#model_name,
				#table_name,
			);

			#(#field_registrations)*
			#(#fk_id_registrations)*
			#(#m2m_registrations)*
			#(#constraint_registrations)*

			#migrations_crate::model_registry::global_registry().register_model(metadata);

			// Register in global model registry for foreign_key resolution
			#orm_crate::registry::global_model_registry().register(
				#orm_crate::registry::ModelInfo {
					app_label: #app_label.to_string(),
					model_name: #model_name.to_string(),
					type_path: #type_path.to_string(),
					table_name: #table_name.to_string(),
				}
			);
		}
	};

	Ok(code)
}

/// Generate relationship registration code for RELATIONSHIPS registry
///
/// This function scans all fields in the model and detects relationship fields
/// (ForeignKeyField, OneToOneField, ManyToManyField) automatically, then generates
/// linkme distributed_slice registration code for each relationship.
///
/// For ForeignKey and OneToOne fields with `related_name`, this also generates
/// reverse relationship registrations for building reverse accessors at runtime.
///
/// # Arguments
///
/// * `struct_name` - The name of the model struct
/// * `app_label` - The app label for the model
/// * `field_infos` - All field information including relationship fields
/// * `fk_field_infos` - Extracted ForeignKey field information
///
/// # Returns
///
/// TokenStream containing linkme distributed_slice registrations for all relationships
fn generate_relationship_registrations(
	struct_name: &syn::Ident,
	app_label: &str,
	field_infos: &[FieldInfo],
	fk_field_infos: &[ForeignKeyFieldInfo],
) -> TokenStream {
	let reinhardt = get_reinhardt_crate();
	let _orm_crate = get_reinhardt_orm_crate();
	// Fixes #793: Use dynamic crate path resolution instead of hardcoded ::linkme
	let linkme = get_linkme_crate();
	let mut registrations = Vec::new();
	let model_name = struct_name.to_string();

	// Process ForeignKey and OneToOne fields
	for fk_info in fk_field_infos {
		let field_name = &fk_info.field_name;
		let field_name_str = field_name.to_string();
		let is_one_to_one = fk_info.is_one_to_one;

		// Extract target model name from Type
		let target_model_name = if let Type::Path(type_path) = &fk_info.target_type {
			type_path
				.path
				.segments
				.last()
				.map(|seg| seg.ident.to_string())
				.unwrap_or_else(|| "Unknown".to_string())
		} else {
			"Unknown".to_string()
		};

		// Get related_name from RelAttribute if present
		let related_name_opt = fk_info.rel_attr.related_name.as_ref();
		let related_name = related_name_opt
			.map(|r| quote! { Some(#r) })
			.unwrap_or(quote! { None });

		// Get db_column from RelAttribute if present, otherwise use "{field_name}_id"
		let db_column = fk_info
			.rel_attr
			.db_column
			.as_ref()
			.map(|c| quote! { Some(#c) })
			.unwrap_or_else(|| {
				let default_db_column = format!("{}_id", field_name_str);
				quote! { Some(#default_db_column) }
			});

		// Determine relationship type
		let relationship_type = if is_one_to_one {
			quote! { #reinhardt::apps::registry::RelationshipType::OneToOne }
		} else {
			quote! { #reinhardt::apps::registry::RelationshipType::ForeignKey }
		};

		// Generate unique static variable name for forward relationship
		let static_var_name = syn::Ident::new(
			&format!(
				"__REL_{}_{}_TO_{}",
				model_name.to_uppercase(),
				field_name_str.to_uppercase(),
				target_model_name.to_uppercase()
			),
			struct_name.span(),
		);

		// Generate registration code for forward relationship
		registrations.push(quote! {
			#[#linkme::distributed_slice(#reinhardt::apps::registry::RELATIONSHIPS)]
			static #static_var_name: #reinhardt::apps::registry::RelationshipMetadata =
				#reinhardt::apps::registry::RelationshipMetadata {
					from_model: concat!(#app_label, ".", #model_name),
					to_model: #target_model_name,
					relationship_type: #relationship_type,
					field_name: #field_name_str,
					related_name: #related_name,
					db_column: #db_column,
					through_table: None,
				};
		});

		// Generate reverse relationship registration if related_name is present
		if let Some(related_name_str) = related_name_opt {
			// Determine reverse relationship type
			let reverse_relationship_type = if is_one_to_one {
				quote! { #reinhardt::apps::registry::RelationshipType::OneToOne }
			} else {
				// ForeignKey reverse is also ForeignKey (direction determined by from_model/to_model)
				quote! { #reinhardt::apps::registry::RelationshipType::ForeignKey }
			};

			// Generate unique static variable name for reverse relationship
			let reverse_static_var_name = syn::Ident::new(
				&format!(
					"__REL_REVERSE_{}_{}_TO_{}",
					target_model_name.to_uppercase(),
					related_name_str.to_uppercase(),
					model_name.to_uppercase()
				),
				struct_name.span(),
			);

			// Generate registration code for reverse relationship
			registrations.push(quote! {
				#[#linkme::distributed_slice(#reinhardt::apps::registry::RELATIONSHIPS)]
				static #reverse_static_var_name: #reinhardt::apps::registry::RelationshipMetadata =
					#reinhardt::apps::registry::RelationshipMetadata {
						from_model: #target_model_name,
						to_model: concat!(#app_label, ".", #model_name),
						relationship_type: #reverse_relationship_type,
						field_name: #related_name_str,
						related_name: Some(#field_name_str),
						db_column: None,
						through_table: None,
					};
			});
		}
	}

	// Process ManyToMany fields
	for field_info in field_infos {
		// Check if this is a ManyToMany field
		if !is_many_to_many_field_type(&field_info.ty) {
			continue;
		}

		let field_name = &field_info.name;
		let field_name_str = field_name.to_string();

		// Extract target model name from ManyToManyField<Source, Target>
		let target_model_name = if let Some(target_ty) = extract_m2m_target_type(&field_info.ty) {
			if let Type::Path(type_path) = target_ty {
				type_path
					.path
					.segments
					.last()
					.map(|seg| seg.ident.to_string())
					.unwrap_or_else(|| "Unknown".to_string())
			} else {
				continue; // Skip if cannot extract target type
			}
		} else {
			continue; // Skip if no target type
		};

		// Get relationship attributes from RelAttribute if present
		let (related_name, through_table, related_name_opt) = if let Some(rel) = &field_info.rel {
			let related_name_str = rel.related_name.as_ref();
			let related_name = related_name_str
				.map(|r| quote! { Some(#r) })
				.unwrap_or(quote! { None });

			let through_table = rel
				.through
				.as_ref()
				.map(|t| {
					let through_str = quote! { #t }.to_string();
					quote! { Some(#through_str) }
				})
				.unwrap_or(quote! { None });

			(related_name, through_table, related_name_str)
		} else {
			(quote! { None }, quote! { None }, None)
		};

		// Generate unique static variable name for forward M2M relationship
		let static_var_name = syn::Ident::new(
			&format!(
				"__REL_M2M_{}_{}_TO_{}",
				model_name.to_uppercase(),
				field_name_str.to_uppercase(),
				target_model_name.to_uppercase()
			),
			struct_name.span(),
		);

		// Generate registration code for forward M2M relationship
		registrations.push(quote! {
			#[#linkme::distributed_slice(#reinhardt::apps::registry::RELATIONSHIPS)]
			static #static_var_name: #reinhardt::apps::registry::RelationshipMetadata =
				#reinhardt::apps::registry::RelationshipMetadata {
					from_model: concat!(#app_label, ".", #model_name),
					to_model: #target_model_name,
					relationship_type: #reinhardt::apps::registry::RelationshipType::ManyToMany,
					field_name: #field_name_str,
					related_name: #related_name,
					db_column: None,
					through_table: #through_table,
				};
		});

		// Generate reverse M2M relationship registration if related_name is present
		if let Some(related_name_str) = related_name_opt {
			// Generate unique static variable name for reverse M2M relationship
			let reverse_static_var_name = syn::Ident::new(
				&format!(
					"__REL_M2M_REVERSE_{}_{}_TO_{}",
					target_model_name.to_uppercase(),
					related_name_str.to_uppercase(),
					model_name.to_uppercase()
				),
				struct_name.span(),
			);

			// Generate registration code for reverse M2M relationship
			registrations.push(quote! {
				#[#linkme::distributed_slice(#reinhardt::apps::registry::RELATIONSHIPS)]
				static #reverse_static_var_name: #reinhardt::apps::registry::RelationshipMetadata =
					#reinhardt::apps::registry::RelationshipMetadata {
						from_model: #target_model_name,
						to_model: concat!(#app_label, ".", #model_name),
						relationship_type: #reinhardt::apps::registry::RelationshipType::ManyToMany,
						field_name: #related_name_str,
						related_name: Some(#field_name_str),
						db_column: None,
						through_table: #through_table,
					};
			});
		}
	}

	// Combine all registrations
	quote! {
		#(#registrations)*
	}
}

/// Generate composite primary key implementation
fn generate_composite_pk_impl(pk_fields: &[&FieldInfo]) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();

	let field_name_strings: Vec<String> = pk_fields.iter().map(|f| f.name.to_string()).collect();

	quote! {
		fn composite_primary_key() -> Option<#orm_crate::composite_pk::CompositePrimaryKey> {
			Some(
				#orm_crate::composite_pk::CompositePrimaryKey::new(
					vec![#(#field_name_strings.to_string()),*]
				)
				.expect("Invalid composite primary key")
			)
		}

		fn get_composite_pk_values(&self) -> ::std::collections::HashMap<String, #orm_crate::composite_pk::PkValue> {
			// Use the generated composite PK type's to_pk_values() method
			if let Some(pk) = self.primary_key() {
				pk.to_pk_values()
			} else {
				::std::collections::HashMap::new()
			}
		}
	}
}

/// Generate composite primary key type definition
///
/// Creates a dedicated struct type for composite primary keys with:
/// - Named fields matching the model's PK fields
/// - Derived traits: Debug, Clone, PartialEq, Eq, Hash
/// - From/Into conversions for tuple types
/// - Individual PkValue conversions for each field
fn generate_composite_pk_type(struct_name: &syn::Ident, pk_fields: &[&FieldInfo]) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();

	// Generate composite PK struct name: {ModelName}CompositePk
	let composite_pk_name =
		syn::Ident::new(&format!("{}CompositePk", struct_name), struct_name.span());

	// Extract field names and types
	let field_names: Vec<_> = pk_fields.iter().map(|f| &f.name).collect();
	let field_types: Vec<_> = pk_fields
		.iter()
		.map(|f| {
			let ty = &f.ty;
			let (is_option, inner_ty) = extract_option_type(ty);
			if is_option { inner_ty } else { ty }
		})
		.collect();

	// Generate From<tuple> implementation for easy construction
	let tuple_type = if field_types.len() == 1 {
		quote! { #(#field_types),* }
	} else {
		quote! { (#(#field_types),*) }
	};

	// Generate individual field conversions for PkValue
	let pk_value_conversions: Vec<_> = field_names
		.iter()
		.map(|name| {
			quote! {
				values.insert(
					stringify!(#name).to_string(),
					#orm_crate::composite_pk::PkValue::from(&self.#name)
				);
			}
		})
		.collect();

	quote! {
		/// Composite primary key type for #struct_name
		#[derive(Debug, Clone, PartialEq, Eq, Hash)]
		pub struct #composite_pk_name {
			#(pub #field_names: #field_types),*
		}

		impl #composite_pk_name {
			/// Create a new composite primary key
			pub fn new(#(#field_names: #field_types),*) -> Self {
				Self {
					#(#field_names),*
				}
			}

			/// Convert to a HashMap of PkValues for database operations
			pub fn to_pk_values(&self) -> ::std::collections::HashMap<String, #orm_crate::composite_pk::PkValue> {
				let mut values = ::std::collections::HashMap::new();
				#(#pk_value_conversions)*
				values
			}
		}

		// Conversion from tuple type
		impl ::std::convert::From<#tuple_type> for #composite_pk_name {
			fn from(tuple: #tuple_type) -> Self {
				let (#(#field_names),*) = tuple;
				Self {
					#(#field_names),*
				}
			}
		}

		// Conversion to tuple type
		impl ::std::convert::From<#composite_pk_name> for #tuple_type {
			fn from(pk: #composite_pk_name) -> Self {
				(#(pk.#field_names),*)
			}
		}

		// Display implementation for composite primary key
		impl ::std::fmt::Display for #composite_pk_name {
			fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
				write!(f, "(")?;
				let mut first = true;
				#(
					if !first {
						write!(f, ", ")?;
					}
					write!(f, "{}={}", stringify!(#field_names), self.#field_names)?;
					first = false;
				)*
				write!(f, ")")
			}
		}
	}
}

/// Generate relationship metadata code for `#[rel]` attributes
///
/// Generates two methods:
/// - `relationship_metadata()` for Model trait (returns `Vec<RelationInfo>`)
/// - `__migration_relationships()` for migration system (returns `Vec<RelationshipMetadata>`)
fn generate_relationship_metadata(
	rel_fields: &[(Ident, RelAttribute)],
	_app_label: &str,
	_struct_name: &Ident,
) -> TokenStream {
	use crate::rel::RelationType;
	let orm_crate = get_reinhardt_orm_crate();

	if rel_fields.is_empty() {
		return quote! {
			fn relationship_metadata() -> Vec<#orm_crate::inspection::RelationInfo> {
				Vec::new()
			}
		};
	}

	let relation_info_items: Vec<TokenStream> = rel_fields
		.iter()
		.map(|(field_name, rel)| {
			let field_name_str = field_name.to_string();

			// Map RelationType to RelationshipType
			let relationship_type = match rel.rel_type {
				RelationType::ForeignKey => {
					quote! { #orm_crate::relationship::RelationshipType::ManyToOne }
				}
				RelationType::OneToOne => {
					quote! { #orm_crate::relationship::RelationshipType::OneToOne }
				}
				RelationType::OneToMany => {
					quote! { #orm_crate::relationship::RelationshipType::OneToMany }
				}
				RelationType::ManyToMany | RelationType::PolymorphicManyToMany => {
					quote! { #orm_crate::relationship::RelationshipType::ManyToMany }
				}
				RelationType::Polymorphic | RelationType::GenericForeignKey => {
					// Current design: Polymorphic and GenericForeignKey are treated as ManyToOne
					quote! { #orm_crate::relationship::RelationshipType::ManyToOne }
				}
				RelationType::GenericRelation => {
					// GenericRelation is a reverse lookup, similar to OneToMany
					quote! { #orm_crate::relationship::RelationshipType::OneToMany }
				}
			};

			let related_model = rel.to.as_ref().map_or_else(
				|| quote! { "" },
				|path| {
					let path_str = quote! { #path }.to_string();
					quote! { #path_str }
				},
			);

			let back_populates = rel.related_name.as_ref().map_or_else(
				|| quote! { None },
				|name| quote! { Some(#name.to_string()) },
			);

			// For ForeignKey, the foreign key field is the field itself
			let foreign_key = match rel.rel_type {
				RelationType::ForeignKey | RelationType::OneToOne => {
					quote! { Some(#field_name_str.to_string()) }
				}
				RelationType::OneToMany => rel
					.foreign_key
					.as_ref()
					.map_or_else(|| quote! { None }, |fk| quote! { Some(#fk.to_string()) }),
				_ => quote! { None },
			};

			// ManyToMany relationship fields
			let through_table = rel
				.through
				.as_ref()
				.map_or_else(|| quote! { None }, |t| quote! { Some(#t.to_string()) });
			let source_field = rel
				.source_field
				.as_ref()
				.map_or_else(|| quote! { None }, |s| quote! { Some(#s.to_string()) });
			let target_field = rel
				.target_field
				.as_ref()
				.map_or_else(|| quote! { None }, |t| quote! { Some(#t.to_string()) });

			quote! {
				#orm_crate::inspection::RelationInfo {
					name: #field_name_str.to_string(),
					relationship_type: #relationship_type,
					foreign_key: #foreign_key,
					related_model: #related_model.to_string(),
					back_populates: #back_populates,
					through_table: #through_table,
					source_field: #source_field,
					target_field: #target_field,
				}
			}
		})
		.collect();

	quote! {
		fn relationship_metadata() -> Vec<#orm_crate::inspection::RelationInfo> {
			vec![
				#(#relation_info_items),*
			]
		}
	}
}

/// Check if a type is Uuid or `Option<Uuid>`.
///
/// Thin projection of the shared `crate::pk_shape::pk_uuid_shape`
/// helper — see issue #4246 for why the underlying detection lives in
/// one place.
fn is_uuid_type(ty: &Type) -> bool {
	crate::pk_shape::pk_uuid_shape(ty).0
}

/// Check if a type is String or `Option<String>`
fn is_string_type(ty: &Type) -> bool {
	let (_, inner_ty) = extract_option_type(ty);
	if let Type::Path(type_path) = inner_ty
		&& let Some(last_segment) = type_path.path.segments.last()
	{
		return last_segment.ident == "String";
	}
	false
}

/// Check if a type is an integer type suitable for auto-increment primary key
/// Supports i8, i16, i32, i64, isize, u8, u16, u32, u64, usize and their Option<> variants
fn is_integer_primary_key_type(ty: &Type) -> bool {
	let (_, inner_ty) = extract_option_type(ty);
	if let Type::Path(type_path) = inner_ty
		&& let Some(last_segment) = type_path.path.segments.last()
	{
		let ident_str = last_segment.ident.to_string();
		return matches!(
			ident_str.as_str(),
			"i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64" | "usize"
		);
	}
	false
}

/// Check if a type is DateTime<Utc> or `Option<DateTime<Utc>>`
fn is_datetime_utc_type(ty: &Type) -> bool {
	let (_, inner_ty) = extract_option_type(ty);
	if let Type::Path(type_path) = inner_ty
		&& let Some(last_segment) = type_path.path.segments.last()
	{
		// Check if the type is DateTime
		if last_segment.ident != "DateTime" {
			return false;
		}

		// Check if it has generic argument <Utc>
		if let PathArguments::AngleBracketed(args) = &last_segment.arguments
			&& let Some(GenericArgument::Type(Type::Path(arg_path))) = args.args.first()
			&& let Some(arg_segment) = arg_path.path.segments.last()
		{
			return arg_segment.ident == "Utc";
		}

		// DateTime without generic argument might still be DateTime<Utc> if imported
		// For safety, we treat it as DateTime<Utc>
		return true;
	}
	false
}

/// Check if a type is a ManyToManyField
fn is_many_to_many_field_type(ty: &Type) -> bool {
	if let Type::Path(type_path) = ty
		&& let Some(last_segment) = type_path.path.segments.last()
	{
		return last_segment.ident == "ManyToManyField";
	}
	false
}

/// Check if a type is a ForeignKeyField
fn is_foreign_key_field_type(ty: &Type) -> bool {
	if let Type::Path(type_path) = ty
		&& let Some(last_segment) = type_path.path.segments.last()
	{
		return last_segment.ident == "ForeignKeyField";
	}
	false
}

/// Check if a type is a OneToOneField
fn is_one_to_one_field_type(ty: &Type) -> bool {
	if let Type::Path(type_path) = ty
		&& let Some(last_segment) = type_path.path.segments.last()
	{
		return last_segment.ident == "OneToOneField";
	}
	false
}

/// Extract target type from ForeignKeyField<T> or OneToOneField<T>
fn extract_fk_target_type(ty: &Type) -> Option<&Type> {
	if let Type::Path(type_path) = ty
		&& let Some(last_segment) = type_path.path.segments.last()
		&& (last_segment.ident == "ForeignKeyField" || last_segment.ident == "OneToOneField")
		&& let syn::PathArguments::AngleBracketed(args) = &last_segment.arguments
		&& let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first()
	{
		return Some(inner_ty);
	}
	None
}

/// Extract target type from ManyToManyField<Source, Target>
/// Returns the second generic argument (Target model)
fn extract_m2m_target_type(ty: &Type) -> Option<&Type> {
	if let Type::Path(type_path) = ty
		&& let Some(last_segment) = type_path.path.segments.last()
		&& last_segment.ident == "ManyToManyField"
		&& let syn::PathArguments::AngleBracketed(args) = &last_segment.arguments
		&& args.args.len() >= 2
		&& let Some(syn::GenericArgument::Type(target_ty)) = args.args.iter().nth(1)
	{
		return Some(target_ty);
	}
	None
}

/// Check if a type is a relationship field type (ForeignKeyField or OneToOneField)
fn is_relationship_field_type(ty: &Type) -> bool {
	is_foreign_key_field_type(ty) || is_one_to_one_field_type(ty)
}

/// Check if a field is a timestamp field that should be auto-set to Utc::now()
///
/// A field is considered a timestamp field only when explicitly annotated with:
/// - `#[field(auto_now_add = true)]` - auto-set on record creation
/// - `#[field(auto_now = true)]` - auto-set on every save
/// - `#[field(on_update_current_timestamp = true)]` - auto-set on record update (MySQL only)
fn is_timestamp_field(field: &FieldInfo) -> bool {
	let config = &field.config;

	// Check auto_now_add and auto_now (available on all DB backends)
	let auto_timestamp = config.auto_now_add == Some(true) || config.auto_now == Some(true);

	// Check on_update_current_timestamp (MySQL only)
	#[cfg(feature = "db-mysql")]
	let mysql_timestamp = config.on_update_current_timestamp == Some(true);
	#[cfg(not(feature = "db-mysql"))]
	let mysql_timestamp = false;

	auto_timestamp || mysql_timestamp
}

/// Extract the target model type from ForeignKeyField<T> or OneToOneField<T>
fn extract_foreign_key_target_type(ty: &Type) -> Type {
	// ForeignKeyField<User> -> User
	if let Type::Path(type_path) = ty
		&& let Some(segment) = type_path.path.segments.last()
		&& let PathArguments::AngleBracketed(args) = &segment.arguments
		&& let Some(GenericArgument::Type(inner_ty)) = args.args.first()
	{
		return inner_ty.clone();
	}
	// Fallback: return the entire type
	ty.clone()
}

/// Check if a type is `Option<T>`
fn is_option_type(ty: &syn::Type) -> bool {
	if let syn::Type::Path(type_path) = ty
		&& let Some(segment) = type_path.path.segments.last()
	{
		return segment.ident == "Option";
	}
	false
}

/// Determine if a field should be auto-generated (excluded from new() function arguments)
fn is_auto_generated_field(field: &FieldInfo) -> bool {
	// Fields with skip = true are always excluded from new() constructor
	if field.config.skip {
		return true;
	}
	// FK _id fields are auto-generated (excluded from new() and setters)
	if field.is_fk_id_field {
		return true;
	}

	let config = &field.config;

	// If include_in_new is explicitly set to false, exclude from new()
	if config.include_in_new == Some(false) {
		return true;
	}

	// If include_in_new is explicitly set to true, always include in new()
	if config.include_in_new == Some(true) {
		return false;
	}

	// Auto-detect timestamp fields
	if is_timestamp_field(field) {
		return true;
	}

	// Generated columns
	if config.generated.is_some() {
		return true;
	}

	// Database-specific ID auto-generation (PostgreSQL)
	#[cfg(feature = "db-postgres")]
	{
		if config.identity_always == Some(true) || config.identity_by_default == Some(true) {
			return true;
		}
	}

	// Database-specific ID auto-generation (MySQL)
	#[cfg(feature = "db-mysql")]
	{
		if config.auto_increment == Some(true) {
			return true;
		}
	}

	// Database-specific ID auto-generation (SQLite)
	#[cfg(feature = "db-sqlite")]
	{
		if config.autoincrement == Some(true) {
			return true;
		}
	}

	// ManyToManyField - always auto-generated with Default::default()
	if is_many_to_many_field_type(&field.ty) {
		return true;
	}

	// ForeignKeyField/OneToOneField - always auto-generated with Default::default()
	if is_relationship_field_type(&field.ty) {
		return true;
	}

	// ManyToMany relationship via #[rel(many_to_many, ...)]
	if let Some(rel) = &field.rel
		&& matches!(rel.rel_type, crate::rel::RelationType::ManyToMany)
	{
		return true;
	}

	// UUID primary key is auto-generated with Uuid::now_v7()
	if config.primary_key && is_uuid_type(&field.ty) {
		return true;
	}

	// Integer primary key is auto-generated by default (auto_increment behavior)
	// Unless explicitly disabled with auto_increment = false
	if config.primary_key && is_integer_primary_key_type(&field.ty) {
		// If auto_increment is explicitly set to false, include in new()
		if config.auto_increment == Some(false) {
			return false;
		}
		// Otherwise, treat as auto-generated (default auto_increment behavior)
		return true;
	}

	false
}

/// Get the default value expression for an auto-generated field
fn get_auto_field_default_value(field: &FieldInfo) -> TokenStream {
	let config = &field.config;

	// Fields with skip = true use Default::default()
	if config.skip {
		return quote! { ::std::default::Default::default() };
	}

	// ManyToManyField or ManyToMany relationship
	if is_many_to_many_field_type(&field.ty) {
		return quote! { ::std::default::Default::default() };
	}
	if let Some(rel) = &field.rel
		&& matches!(rel.rel_type, crate::rel::RelationType::ManyToMany)
	{
		return quote! { ::std::default::Default::default() };
	}

	// ForeignKeyField or OneToOneField - use Default::default()
	if is_relationship_field_type(&field.ty) {
		return quote! { ::std::default::Default::default() };
	}

	// Timestamp fields - use Utc::now() ONLY if the field type is DateTime<Utc>
	// This prevents type mismatches when fields named 'created_at' are of type i64
	if is_timestamp_field(field) && is_datetime_utc_type(&field.ty) {
		// Wrap with Some() for Option<DateTime<Utc>>
		if is_option_type(&field.ty) {
			return quote! { ::std::option::Option::Some(::chrono::Utc::now()) };
		}
		// Return as-is for DateTime<Utc>
		return quote! { ::chrono::Utc::now() };
	}

	// UUID primary key - generate new UUID
	if config.primary_key && is_uuid_type(&field.ty) {
		let (is_option, _) = extract_option_type(&field.ty);
		if is_option {
			return quote! { Some(::uuid::Uuid::now_v7()) };
		} else {
			return quote! { ::uuid::Uuid::now_v7() };
		}
	}

	// Integer primary key with auto-increment behavior - use 0 as placeholder
	// The actual value will be set by the database on INSERT
	if config.primary_key && is_integer_primary_key_type(&field.ty) {
		let (is_option, inner_ty) = extract_option_type(&field.ty);
		if is_option {
			return quote! { ::std::option::Option::None };
		} else {
			// Use 0 as the default value for integer primary keys
			// This will be replaced by the database-generated value on INSERT
			return quote! { 0 as #inner_ty };
		}
	}

	// Generated columns, IDENTITY, or auto-increment fields
	// These are set by the database, so use Default::default() (typically None for Option types)
	quote! { ::std::default::Default::default() }
}

/// Generate the new() constructor function for the model
fn generate_new_function(
	struct_name: &syn::Ident,
	field_infos: &[FieldInfo],
	fk_id_field_names: &[syn::Ident],
) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();
	// Separate user-specified fields from auto-generated fields
	let user_fields: Vec<_> = field_infos
		.iter()
		.filter(|f| !is_auto_generated_field(f))
		.collect();

	let auto_fields: Vec<_> = field_infos
		.iter()
		.filter(|f| is_auto_generated_field(f))
		.collect();

	// Create a map of FK _id fields (e.g., room_id -> room)
	let fk_id_to_fk_field: HashMap<String, String> = fk_id_field_names
		.iter()
		.filter_map(|id_name| {
			let id_str = id_name.to_string();
			if id_str.ends_with("_id") {
				let fk_name = id_str.trim_end_matches("_id").to_string();
				Some((id_str, fk_name))
			} else {
				None
			}
		})
		.collect();

	// Generate parameter list
	let mut params = Vec::new();
	let mut where_clauses = Vec::new();
	let mut generic_params = Vec::new();
	let mut fk_field_assignments = Vec::new();
	let mut fk_id_assignments = Vec::new();

	// Generic type parameter counter (F0, F1, F2, ...)
	let mut generic_counter = 0;

	// Track String type fields (field_name -> Option info)
	// Need to call .into() during field assignment to use Into<String>
	let mut string_fields: HashMap<String, bool> = HashMap::new(); // value: is_option

	for f in user_fields.iter() {
		let field_name = &f.name;
		let field_name_str = field_name.to_string();

		// Check if this field is a FK _id field
		if let Some(fk_field_name) = fk_id_to_fk_field.get(&field_name_str) {
			// This is a FK _id field (e.g., room_id)
			// Use generic type parameter
			let generic_param =
				syn::Ident::new(&format!("F{}", generic_counter), field_name.span());
			generic_counter += 1;

			// Find the corresponding FK field
			let fk_field_info = field_infos.iter().find(|fi| fi.name == fk_field_name);

			if let Some(fk_info) = fk_field_info {
				// Extract T from ForeignKeyField<T>
				let related_model_type = extract_foreign_key_target_type(&fk_info.ty);

				// Parameter: fk_field_name: GenericParam
				let fk_field_ident = syn::Ident::new(fk_field_name, field_name.span());
				params.push(quote! { #fk_field_ident: #generic_param });

				// Where clause: GenericParam: IntoPrimaryKey<RelatedModel>
				where_clauses.push(quote! {
					#generic_param: #orm_crate::IntoPrimaryKey<#related_model_type>
				});

				// Generic parameter list
				generic_params.push(quote! { #generic_param });

				// Field assignment: room_id: fk_field_name.into_primary_key()
				fk_id_assignments.push(quote! {
					#field_name: #fk_field_ident.into_primary_key()
				});
			}
		} else {
			// Regular user field
			let ty = &f.ty;

			// Use generic type parameter for String fields
			// However, keep Option<String> as-is because type inference fails when passing None
			let (is_option, _) = extract_option_type(ty);
			if is_string_type(ty) && !is_option {
				// String -> S where S: Into<String>
				let generic_param =
					syn::Ident::new(&format!("S{}", generic_counter), field_name.span());
				generic_counter += 1;

				params.push(quote! { #field_name: #generic_param });
				where_clauses
					.push(quote! { #generic_param: ::std::convert::Into<::std::string::String> });
				generic_params.push(quote! { #generic_param });
				string_fields.insert(field_name_str.clone(), false);
			} else {
				params.push(quote! { #field_name: #ty });
			}
		}
	}

	// ForeignKeyField field assignment (ForeignKeyField::new())
	for (_fk_id_str, fk_name_str) in fk_id_to_fk_field.iter() {
		let fk_name = syn::Ident::new(fk_name_str, proc_macro2::Span::call_site());
		fk_field_assignments.push(quote! {
			#fk_name: ::std::default::Default::default()
		});
	}

	// Initialize FK _id fields (fields marked with #[fk_id_field])
	// These are fields added by the attribute macro and not included in field_infos
	for fk_id_name in fk_id_field_names.iter() {
		let fk_id_str = fk_id_name.to_string();
		if let Some(fk_field_name) = fk_id_to_fk_field.get(&fk_id_str) {
			// Find the corresponding FK field
			let fk_field_info = field_infos.iter().find(|fi| fi.name == fk_field_name);

			if let Some(fk_info) = fk_field_info {
				// Extract T from ForeignKeyField<T>
				let related_model_type = extract_foreign_key_target_type(&fk_info.ty);

				// Generic type parameter
				let generic_param =
					syn::Ident::new(&format!("F{}", generic_counter), fk_id_name.span());
				generic_counter += 1;

				// Parameter: user: GenericParam
				let fk_field_ident = syn::Ident::new(fk_field_name, fk_id_name.span());
				params.push(quote! { #fk_field_ident: #generic_param });

				// Where clause: GenericParam: IntoPrimaryKey<RelatedModel>
				where_clauses.push(quote! {
					#generic_param: #orm_crate::IntoPrimaryKey<#related_model_type>
				});

				// Generic parameter list
				generic_params.push(quote! { #generic_param });

				// Field assignment: user_id: user.into_primary_key()
				fk_id_assignments.push(quote! {
					#fk_id_name: #fk_field_ident.into_primary_key()
				});
			} else {
				// If FK field info not found, use Default::default()
				fk_id_assignments.push(quote! {
					#fk_id_name: ::std::default::Default::default()
				});
			}
		} else {
			// If not in map, use Default::default()
			fk_id_assignments.push(quote! {
				#fk_id_name: ::std::default::Default::default()
			});
		}
	}

	// Create a set of FK field names (fix: use values, not keys)
	let fk_field_names: std::collections::HashSet<String> =
		fk_id_to_fk_field.values().cloned().collect();

	// Create a set of FK _id field names (e.g., user_id, room_id, etc.)
	let fk_id_field_names_set: std::collections::HashSet<String> =
		fk_id_to_fk_field.keys().cloned().collect();

	// Assign regular user fields (excluding FK-related fields)
	let user_field_assignments: Vec<_> = user_fields
		.iter()
		.filter(|f| {
			!fk_field_names.contains(&f.name.to_string())
				&& !fk_id_field_names_set.contains(&f.name.to_string())
		})
		.map(|f| {
			let name = &f.name;
			let name_str = name.to_string();

			// Call .into() for String type fields
			// (Option<String> is not generified, so it's not in string_fields)
			if string_fields.contains_key(&name_str) {
				quote! { #name: #name.into() }
			} else {
				quote! { #name }
			}
		})
		.collect();

	// Assign auto-generated fields (excluding FK fields and FK _id fields)
	let auto_field_assignments: Vec<_> = auto_fields
		.iter()
		.filter(|f| {
			!fk_field_names.contains(&f.name.to_string())
				&& !fk_id_field_names_set.contains(&f.name.to_string())
		})
		.map(|f| {
			let name = &f.name;
			let default_value = get_auto_field_default_value(f);
			quote! { #name: #default_value }
		})
		.collect();

	// Generate generic function signature
	let generic_signature = if generic_params.is_empty() {
		quote! {}
	} else {
		quote! { <#(#generic_params),*> }
	};

	let where_clause = if where_clauses.is_empty() {
		quote! {}
	} else {
		quote! { where #(#where_clauses),* }
	};

	quote! {
		impl #struct_name {
			/// Create a new instance with user-specified fields.
			///
			/// Auto-generated fields are initialized automatically:
			/// - UUID primary keys: Generated with `Uuid::now_v7()`
			/// - Timestamp fields (created_at, updated_at, etc.): Set to `Utc::now()`
			/// - Fields with `#[field(auto_now_add)]` or `#[field(auto_now)]`: Set to `Utc::now()`
			/// - ManyToManyField: Initialized with `Default::default()`
			/// - ForeignKeyField: Initialized with `Default::default()`
			/// - Identity/AutoIncrement fields: Set to `Default::default()` (DB assigns value)
			///
			/// # Foreign Key Parameters
			///
			/// Foreign key fields accept either:
			/// - The related model instance (e.g., `User { ... }`)
			/// - A reference to the related model (e.g., `&user`)
			/// - The primary key value directly (e.g., `user_id: Uuid`)
			#[allow(clippy::too_many_arguments)]
			pub fn new #generic_signature(#(#params),*) -> Self
			#where_clause
			{
				Self {
					#(#user_field_assignments,)*
					#(#fk_id_assignments,)*
					#(#fk_field_assignments,)*
					#(#auto_field_assignments,)*
				}
			}
		}
	}
}

/// Generate the typestate `build()` builder for the model.
///
/// This is a non-breaking addition that lives **alongside** the positional
/// `new()` constructor. Adding a new required field to a model only adds a
/// new builder setter — every existing `build().setter().finish()` call site
/// keeps compiling. See issue #4400 for the full motivation.
///
/// # Generated API
///
/// For a model with required fields `f1: T1`, `f2: T2`, …, `fN: TN` this
/// function emits:
///
/// - A marker pair `<StructName>BuilderSet` / `<StructName>BuilderUnset` to
///   track per-field set/unset state at the type level.
/// - A struct `<StructName>Builder<S1, …, SN>` that stores the so-far-supplied
///   values in `Option<Ti>` slots and carries `PhantomData<(S1, …, SN)>`.
/// - One `impl` block per required field that provides the setter, transitioning
///   that field's state from `Unset` to `Set` in the type parameter list.
/// - A single `impl <StructName>Builder<Set, …, Set>` block with `finish()` that
///   constructs `Self` exactly like the positional `new()` does.
/// - A `pub fn build() -> <StructName>Builder<Unset, …, Unset>` entry point on
///   the model.
///
/// FK setters accept any `IntoPrimaryKey<Related>` value — the same flexibility
/// the positional `new()` already offered — so callers can pass `&user`
/// (the FK shortcut from #4398) or a raw primary-key value.
///
/// Auto-generated fields (`auto_now_add`, integer/UUID primary keys, FK relation
/// fields, etc.) and fields with `include_in_new = false` are filled in by
/// `finish()` using the same defaults as `new()` — they require no setter.
fn generate_build_function(
	struct_name: &syn::Ident,
	field_infos: &[FieldInfo],
	fk_id_field_names: &[syn::Ident],
) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();

	// Partition fields exactly as generate_new_function does so the builder's
	// finish() body mirrors new()'s body.
	let user_fields: Vec<_> = field_infos
		.iter()
		.filter(|f| !is_auto_generated_field(f))
		.collect();

	let auto_fields: Vec<_> = field_infos
		.iter()
		.filter(|f| is_auto_generated_field(f))
		.collect();

	// Map of `*_id` (in field_infos / fk_id_field_names) -> related FK field name
	// (the model-typed field, e.g. `room_id` -> `room`). Mirrors new()'s logic.
	let fk_id_to_fk_field: HashMap<String, String> = fk_id_field_names
		.iter()
		.filter_map(|id_name| {
			let id_str = id_name.to_string();
			if id_str.ends_with("_id") {
				let fk_name = id_str.trim_end_matches("_id").to_string();
				Some((id_str, fk_name))
			} else {
				None
			}
		})
		.collect();

	// Classify each required (user-facing) field into one of three setter shapes.
	// `Type` is large (~240 bytes via `syn`), so the FK variant boxes it to keep
	// `SetterKind` compact and satisfy `clippy::large_enum_variant`.
	enum SetterKind {
		/// FK `*_id` field. Setter name is the related FK field (e.g. `author`)
		/// and accepts `impl IntoPrimaryKey<Related>` to mirror new().
		ForeignKey {
			related_type: Box<Type>,
			setter_name: syn::Ident,
		},
		/// `String` field. Setter accepts `impl Into<String>` for ergonomics.
		String,
		/// Plain field. Setter accepts the exact declared type.
		Plain,
	}

	struct Required<'a> {
		/// The struct field name as stored in the model itself (e.g. `author_id`
		/// for FKs, `question_text` otherwise).
		storage_name: syn::Ident,
		/// The struct field type as stored in the model itself.
		storage_ty: &'a Type,
		/// Setter shape — controls the setter signature and finish() expression.
		kind: SetterKind,
	}

	let mut required: Vec<Required> =
		Vec::with_capacity(user_fields.len() + fk_id_field_names.len());
	for f in user_fields.iter() {
		let name_str = f.name.to_string();
		if let Some(fk_field_name) = fk_id_to_fk_field.get(&name_str) {
			// FK `*_id` field. Look up the related model type from the FK field.
			let fk_field_info = field_infos.iter().find(|fi| fi.name == *fk_field_name);
			let related_type = match fk_field_info {
				Some(info) => extract_foreign_key_target_type(&info.ty),
				// Defensive fallback: keep the stored type. This branch is not
				// expected because new() establishes the same mapping.
				None => f.ty.clone(),
			};
			let setter_name = syn::Ident::new(fk_field_name, f.name.span());
			required.push(Required {
				storage_name: f.name.clone(),
				storage_ty: &f.ty,
				kind: SetterKind::ForeignKey {
					related_type: Box::new(related_type),
					setter_name,
				},
			});
		} else if is_string_type(&f.ty) && !extract_option_type(&f.ty).0 {
			required.push(Required {
				storage_name: f.name.clone(),
				storage_ty: &f.ty,
				kind: SetterKind::String,
			});
		} else {
			required.push(Required {
				storage_name: f.name.clone(),
				storage_ty: &f.ty,
				kind: SetterKind::Plain,
			});
		}
	}

	// FK `*_id` fields (e.g. `user_id`) are flagged as auto-generated by
	// `is_auto_generated_field` and therefore excluded from `user_fields`,
	// but they still need a user-facing setter on the builder so that callers
	// can supply the related model / primary key — mirroring the dedicated
	// FK parameter loop in `generate_new_function`.
	for fk_id_name in fk_id_field_names.iter() {
		let fk_id_str = fk_id_name.to_string();
		// `fk_id_to_fk_field` only retains `*_id`-suffixed names (see its
		// construction above); names that don't follow the convention have no
		// implicit related-field name and are intentionally skipped, mirroring
		// the filter in `generate_new_function`.
		let Some(fk_field_name) = fk_id_to_fk_field.get(&fk_id_str) else {
			continue;
		};
		// `fk_id_field_names` is built from `field_infos`, so the lookup MUST
		// succeed; failure indicates an internal data-structure desync.
		let id_field_info = field_infos
			.iter()
			.find(|fi| fi.name == *fk_id_name)
			.unwrap_or_else(|| {
				panic!(
					"internal macro invariant: `{}` is in fk_id_field_names but missing from field_infos",
					fk_id_str
				)
			});
		let fk_field_info = field_infos.iter().find(|fi| fi.name == *fk_field_name);
		let related_type = match fk_field_info {
			Some(info) => extract_foreign_key_target_type(&info.ty),
			// Defensive fallback: use the `*_id` storage type itself.
			None => id_field_info.ty.clone(),
		};
		// Prefer reusing the existing FK field identifier (preserves raw-ident
		// spelling, hygiene, and span). Fall back to `Ident::new_raw` so the
		// proc-macro never panics if `fk_field_name` happens to be a Rust
		// keyword (e.g. `type`, `match`). Strip a leading `r#` defensively in
		// case the source identifier was a raw ident (`Ident::new_raw`
		// expects the bare name without the prefix). Reserved identifiers
		// that even `new_raw` rejects (`self`, `Self`, `super`, `crate`)
		// are surfaced as a clear macro error rather than the underlying
		// panic from `proc_macro2`. Note: `extern` is a keyword but IS
		// permitted as a raw identifier (`r#extern`), so it is excluded
		// from this set.
		let setter_name = match fk_field_info {
			Some(info) => info.name.clone(),
			None => {
				let bare = fk_field_name
					.strip_prefix("r#")
					.unwrap_or(fk_field_name.as_str());
				if matches!(bare, "self" | "Self" | "super" | "crate") {
					return syn::Error::new(
						fk_id_name.span(),
						format!(
							"cannot derive builder setter for FK field `{fk_id_str}`: \
							 the implied setter name `{bare}` is a reserved identifier; \
							 rename the related model-typed field or the `*_id` field"
						),
					)
					.to_compile_error();
				}
				syn::Ident::new_raw(bare, fk_id_name.span())
			}
		};
		required.push(Required {
			storage_name: id_field_info.name.clone(),
			storage_ty: &id_field_info.ty,
			kind: SetterKind::ForeignKey {
				related_type: Box::new(related_type),
				setter_name,
			},
		});
	}

	// Type names for the per-model builder + markers.
	let builder_name = syn::Ident::new(&format!("{}Builder", struct_name), struct_name.span());
	let set_marker = syn::Ident::new(&format!("{}BuilderSet", struct_name), struct_name.span());
	let unset_marker = syn::Ident::new(&format!("{}BuilderUnset", struct_name), struct_name.span());

	// Per-field type parameter idents `B0, B1, …` used in the builder's signature.
	let state_params: Vec<syn::Ident> = (0..required.len())
		.map(|i| syn::Ident::new(&format!("B{}", i), struct_name.span()))
		.collect();

	// Builder struct fields: one Option<StorageTy> per required field, plus the
	// PhantomData state marker.
	let builder_struct_fields: Vec<TokenStream> = required
		.iter()
		.map(|r| {
			let name = &r.storage_name;
			let ty = r.storage_ty;
			quote! { #name: ::std::option::Option<#ty> }
		})
		.collect();

	// `build()` initializer: every slot starts as `None`, every state slot as `Unset`.
	let init_struct_field_assignments: Vec<TokenStream> = required
		.iter()
		.map(|r| {
			let name = &r.storage_name;
			quote! { #name: ::std::option::Option::None }
		})
		.collect();

	// Per-field setter impl blocks. Each one transitions exactly one type slot
	// from `Unset` to `Set` while leaving the others polymorphic.
	let mut setter_impls: Vec<TokenStream> = Vec::with_capacity(required.len());
	for (idx, r) in required.iter().enumerate() {
		// Generic state parameters EXCLUDING the one being transitioned. The
		// transitioned slot is concretely `Unset` on the input and `Set` on the
		// output.
		let other_params: Vec<&syn::Ident> = state_params
			.iter()
			.enumerate()
			.filter_map(|(i, p)| if i == idx { None } else { Some(p) })
			.collect();

		// Input state list (this slot = Unset, others = generic).
		let input_states: Vec<TokenStream> = state_params
			.iter()
			.enumerate()
			.map(|(i, p)| {
				if i == idx {
					quote! { #unset_marker }
				} else {
					quote! { #p }
				}
			})
			.collect();

		// Output state list (this slot = Set, others = generic).
		let output_states: Vec<TokenStream> = state_params
			.iter()
			.enumerate()
			.map(|(i, p)| {
				if i == idx {
					quote! { #set_marker }
				} else {
					quote! { #p }
				}
			})
			.collect();

		// Field copy expressions for moving non-transitioned slots into the new
		// builder. The transitioned slot is replaced by the supplied value.
		let copy_fields: Vec<TokenStream> = required
			.iter()
			.enumerate()
			.map(|(i, other)| {
				let n = &other.storage_name;
				if i == idx {
					quote! {}
				} else {
					quote! { #n: self.#n, }
				}
			})
			.collect();

		let storage_name = &r.storage_name;
		let storage_ty = r.storage_ty;

		// Setter signature + body depend on the field kind.
		let (setter_sig, value_expr): (TokenStream, TokenStream) = match &r.kind {
			SetterKind::ForeignKey {
				related_type,
				setter_name,
			} => {
				// Setter named after the related FK field, accepting any
				// IntoPrimaryKey<Related>. This composes with #4398 — callers
				// can pass `&user` directly without manually extracting the PK.
				let sig = quote! {
					/// Set the foreign-key reference for this required field.
					///
					/// Accepts any `IntoPrimaryKey<Related>` — pass either the
					/// related model (e.g. `&user`) or a raw primary-key value.
					/// Transitions this slot from `Unset` to `Set` in the
					/// builder's type-state.
					pub fn #setter_name<__FkArg>(self, value: __FkArg)
						-> #builder_name<#(#output_states),*>
					where
						__FkArg: #orm_crate::IntoPrimaryKey<#related_type>,
				};
				let expr = quote! { value.into_primary_key() };
				(sig, expr)
			}
			SetterKind::String => {
				// Setter for `String` field, accepting `impl Into<String>`.
				let sig = quote! {
					/// Set this required `String` field.
					///
					/// Accepts any `impl Into<String>` (e.g. `&str`, `String`,
					/// `Cow<'_, str>`). Transitions this slot from `Unset` to
					/// `Set` in the builder's type-state.
					pub fn #storage_name<__StrArg>(self, value: __StrArg)
						-> #builder_name<#(#output_states),*>
					where
						__StrArg: ::std::convert::Into<::std::string::String>,
				};
				let expr = quote! { value.into() };
				(sig, expr)
			}
			SetterKind::Plain => {
				// Plain setter using the declared field type.
				let sig = quote! {
					/// Set this required field.
					///
					/// Transitions this slot from `Unset` to `Set` in the
					/// builder's type-state.
					pub fn #storage_name(self, value: #storage_ty)
						-> #builder_name<#(#output_states),*>
				};
				let expr = quote! { value };
				(sig, expr)
			}
		};

		let other_param_list = if other_params.is_empty() {
			quote! {}
		} else {
			quote! { <#(#other_params),*> }
		};

		setter_impls.push(quote! {
			impl #other_param_list #builder_name<#(#input_states),*> {
				#setter_sig
				{
					#builder_name {
						#(#copy_fields)*
						#storage_name: ::std::option::Option::Some(#value_expr),
						__state: ::std::marker::PhantomData,
					}
				}
			}
		});
	}

	// finish() body. Mirrors the assignment layout used by generate_new_function:
	// user fields → FK `*_id` fields → FK relation defaults → auto-generated fields.

	// FK id field names by raw string (matches new()).
	let fk_id_field_names_set: std::collections::HashSet<String> =
		fk_id_to_fk_field.keys().cloned().collect();
	let fk_field_names: std::collections::HashSet<String> =
		fk_id_to_fk_field.values().cloned().collect();

	// User field assignments (non-FK regular fields). Pull from the builder's
	// `Option` slot — type-state guarantees `Some`.
	let user_field_assignments: Vec<TokenStream> = user_fields
		.iter()
		.filter(|f| {
			!fk_field_names.contains(&f.name.to_string())
				&& !fk_id_field_names_set.contains(&f.name.to_string())
		})
		.map(|f| {
			let name = &f.name;
			quote! {
				#name: self
					.#name
					.expect(concat!(
						"build() typestate guarantees ",
						stringify!(#name),
						" is set before finish() is callable"
					))
			}
		})
		.collect();

	// FK `*_id` assignments. The value was stored under the `*_id` name when
	// the user called the related-field setter.
	let fk_id_assignments: Vec<TokenStream> = fk_id_field_names
		.iter()
		.map(|fk_id_name| {
			let name = fk_id_name.clone();
			quote! {
				#name: self
					.#name
					.expect(concat!(
						"build() typestate guarantees ",
						stringify!(#name),
						" is set before finish() is callable"
					))
			}
		})
		.collect();

	// FK relation fields (the `ForeignKeyField<T>` themselves) — default-init,
	// same as new().
	let fk_field_assignments: Vec<TokenStream> = fk_id_to_fk_field
		.values()
		.map(|fk_name_str| {
			let fk_name = syn::Ident::new(fk_name_str, proc_macro2::Span::call_site());
			quote! { #fk_name: ::std::default::Default::default() }
		})
		.collect();

	// Auto-generated fields (timestamps, UUID/integer PKs, identity, generated,
	// skipped, etc.) — use the exact same default expressions as new().
	let auto_field_assignments: Vec<TokenStream> = auto_fields
		.iter()
		.filter(|f| {
			!fk_field_names.contains(&f.name.to_string())
				&& !fk_id_field_names_set.contains(&f.name.to_string())
		})
		.map(|f| {
			let name = &f.name;
			let default_value = get_auto_field_default_value(f);
			quote! { #name: #default_value }
		})
		.collect();

	// All-Set state list for the finish() impl bound.
	let all_set_states: Vec<TokenStream> = state_params
		.iter()
		.map(|_| quote! { #set_marker })
		.collect();

	// State parameter list for the builder struct + the initial-Unset list for
	// build().
	let state_param_list = if state_params.is_empty() {
		quote! {}
	} else {
		quote! { <#(#state_params),*> }
	};
	let initial_unset_states: Vec<TokenStream> = state_params
		.iter()
		.map(|_| quote! { #unset_marker })
		.collect();

	// The PhantomData tuple type and field expression. Unit tuple (`()`) when
	// there are no required fields, so the model still gets a usable builder.
	let phantom_tuple_ty = if state_params.is_empty() {
		quote! { () }
	} else {
		quote! { ( #(#state_params,)* ) }
	};

	// Suppress dead_code warnings for builders generated for models that never
	// gain a required field — the markers and Option slots exist for type-state
	// shape consistency.
	let allow_dead = quote! { #[allow(dead_code)] };

	quote! {
		/// Type-state marker: the corresponding builder slot has been provided.
		#allow_dead
		pub struct #set_marker;

		/// Type-state marker: the corresponding builder slot is still missing.
		///
		/// `finish()` is only implemented when every slot is `#set_marker`, so
		/// calling `finish()` with any remaining `#unset_marker` slot is a
		/// compile error.
		#allow_dead
		pub struct #unset_marker;

		/// Typestate builder for [`#struct_name`] (issue #4400).
		///
		/// Construct via [`#struct_name::build`]; each required-field setter
		/// transitions exactly one `Unset` slot to `Set`. `finish()` is only
		/// available when every required slot is `Set`, so omitting a required
		/// field is a compile-time error.
		#allow_dead
		pub struct #builder_name #state_param_list {
			#(#builder_struct_fields,)*
			__state: ::std::marker::PhantomData<#phantom_tuple_ty>,
		}

		impl #struct_name {
			/// Begin constructing a [`#struct_name`] via the typestate builder.
			///
			/// Adding a new required field to this model becomes a non-breaking
			/// change for every caller that uses `build()` — the new field is
			/// surfaced as a new setter rather than a new positional parameter.
			///
			/// The positional [`Self::new`] constructor remains available and
			/// unchanged for callers that want the compact form.
			pub fn build() -> #builder_name<#(#initial_unset_states),*> {
				#builder_name {
					#(#init_struct_field_assignments,)*
					__state: ::std::marker::PhantomData,
				}
			}
		}

		#(#setter_impls)*

		impl #builder_name<#(#all_set_states),*> {
			/// Finalize the builder and construct the model instance.
			///
			/// Auto-generated fields (`auto_now_add` timestamps, UUID / integer
			/// primary keys, identity columns, FK relation fields, etc.) are
			/// initialized exactly the same way as [`#struct_name::new`].
			pub fn finish(self) -> #struct_name {
				#struct_name {
					#(#user_field_assignments,)*
					#(#fk_id_assignments,)*
					#(#fk_field_assignments,)*
					#(#auto_field_assignments,)*
				}
			}
		}
	}
}

/// Generate field selector struct
///
/// For type-safe JOIN/GROUP BY/HAVING operations, generates a field selector
/// struct (e.g., `UserFields`) corresponding to each model.
///
/// # Example
///
/// Generate `UserFields` struct for `User` model, enabling usage like:
///
/// ```ignore
/// QuerySet::<User>::new()
///     .inner_join_as::<User, _>("u1", "u2", |u1, u2| u1.id.lt(u2.id))
///     .group_by(|f| vec![f.user_id, f.category])
/// ```
fn generate_field_selector_struct(
	struct_name: &syn::Ident,
	field_infos: &[FieldInfo],
) -> TokenStream {
	let orm_crate = get_reinhardt_orm_crate();

	// Exclude skip/FK/M2M/O2O fields (only normal DB columns)
	let regular_fields: Vec<_> = field_infos
		.iter()
		.filter(|f| {
			// Exclude fields marked with #[field(skip = true)]
			if f.config.skip {
				return false;
			}
			// FK _id fields are included (they are actual DB columns)
			// But exclude ForeignKeyField, OneToOneField, ManyToManyField (virtual fields)
			!is_foreign_key_field_type(&f.ty)
				&& !is_one_to_one_field_type(&f.ty)
				&& !is_many_to_many_field_type(&f.ty)
		})
		.collect();

	let field_selector_name =
		syn::Ident::new(&format!("{}Fields", struct_name), struct_name.span());

	// Generate field declarations
	let field_declarations: Vec<_> = regular_fields
		.iter()
		.map(|field| {
			let field_name = &field.name;
			let field_type = &field.ty;
			quote! {
				#field_name: #orm_crate::query_fields::Field<#struct_name, #field_type>
			}
		})
		.collect();

	// Generate field initialization
	let field_initializers: Vec<_> = regular_fields
		.iter()
		.map(|field| {
			let field_name = &field.name;
			let field_name_str = field_name.to_string();
			quote! {
				#field_name: #orm_crate::query_fields::Field::new(vec![#field_name_str])
			}
		})
		.collect();

	// List of field names (used in with_alias method)
	let regular_field_names: Vec<_> = regular_fields.iter().map(|field| &field.name).collect();

	quote! {
		/// Type-safe field selector for #struct_name
		///
		/// Provides type-safe field references in JOIN, GROUP BY, and HAVING clauses.
		#[derive(Debug, Clone)]
		pub struct #field_selector_name {
			#(#field_declarations),*
		}

		impl #field_selector_name {
			/// Create a new field selector instance
			pub fn new() -> Self {
				Self {
					#(#field_initializers),*
				}
			}
		}

		impl #orm_crate::FieldSelector for #field_selector_name {
			/// Set table alias for all fields
			///
			/// Used for self-joins where the same table appears multiple times
			/// with different aliases.
			///
			/// # Examples
			///
			/// ```ignore
			/// let u1 = UserFields::new().with_alias("u1");
			/// let u2 = UserFields::new().with_alias("u2");
			/// ```
			fn with_alias(mut self, alias: &str) -> Self {
				// Set alias for all fields
				#(self.#regular_field_names = self.#regular_field_names.with_alias(alias);)*
				self
			}
		}

		impl ::std::default::Default for #field_selector_name {
			fn default() -> Self {
				Self::new()
			}
		}
	}
}

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

	#[test]
	fn test_fields_are_private() {
		let input = quote! {
			#[model(app_label = "test", table_name = "test")]
			pub struct TestModel {
				#[field(primary_key = true)]
				pub id: i64,
				#[field(max_length = 255)]
				pub name: String,
			}
		};

		let output = model_derive_impl(syn::parse2(input).unwrap()).unwrap();
		let output_str = output.to_string();

		// Verify that fields are not pub
		assert!(!output_str.contains("pub id"));
		assert!(!output_str.contains("pub name"));
	}

	#[test]
	fn test_getter_methods_generated() {
		let input = quote! {
			#[model(app_label = "test", table_name = "test")]
			pub struct TestModel {
				#[field(primary_key = true)]
				pub id: i64,
				#[field(max_length = 255)]
				pub name: String,
			}
		};

		let output = model_derive_impl(syn::parse2(input).unwrap()).unwrap();
		let output_str = output.to_string();

		// Verify that getter methods are generated
		assert!(output_str.contains("pub fn id"));
		assert!(output_str.contains("pub fn name"));
	}

	#[test]
	fn test_setter_methods_exclude_auto_fields() {
		let input = quote! {
			#[model(app_label = "test", table_name = "test")]
			pub struct TestModel {
				#[field(primary_key = true)]
				pub id: i64,
				#[field(max_length = 255)]
				pub name: String,
				#[field(auto_now_add = true)]
				pub created_at: DateTime<Utc>,
			}
		};

		let output = model_derive_impl(syn::parse2(input).unwrap()).unwrap();
		let output_str = output.to_string();

		// Setter for name is generated
		assert!(output_str.contains("pub fn set_name"));

		// Setters for id and created_at are not generated
		assert!(!output_str.contains("pub fn set_id"));
		assert!(!output_str.contains("pub fn set_created_at"));
	}
}