tree-type-proc-macro 0.4.5

Procedural macros for tree-type crate
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
//! Legacy codegen that is limited to one or two nested dynamic ids

use crate::core::Attribute;
use crate::core::Child;
use crate::core::DefaultValue;
use crate::core::TreeDef;
use quote::format_ident;
use quote::quote;
use syn::Ident;

// Generic dynamic ID information for arbitrary nesting depth
#[derive(Debug, Clone)]
#[expect(dead_code)]
struct DynamicIdInfo {
    id_type: proc_macro2::TokenStream,
}

// Collect all dynamic ancestor IDs from root to current level
#[allow(dead_code)]
fn collect_dynamic_ancestors(
    children: &[Child],
    target_name: &str,
    current_path: &mut Vec<DynamicIdInfo>,
    result: &mut Option<Vec<DynamicIdInfo>>,
) {
    for child in children {
        match child {
            Child::DynamicId {
                id_type,
                child_type,
                children,
                ..
            } => {
                // Add this dynamic ID to the path
                current_path.push(DynamicIdInfo {
                    id_type: quote! { #id_type },
                });

                // Check if this is our target
                if *child_type == target_name {
                    *result = Some(current_path.clone());
                    current_path.pop();
                    return;
                }

                // Recurse into children
                collect_dynamic_ancestors(children, target_name, current_path, result);

                // Remove this ID from path when backtracking
                current_path.pop();
            }
            Child::Directory { children, .. } => {
                // For non-dynamic children, recurse without adding to path
                collect_dynamic_ancestors(children, target_name, current_path, result);
            }
            Child::File { .. } => {
                // Files don't have children, nothing to recurse into
            }
        }
    }
}

/// Get parameter type and conversion for dynamic ID methods
fn get_param_type_and_conversion(
    id_type: &syn::Type,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    // Use impl Display for ergonomic API that accepts both &str and String
    (
        quote! { impl std::fmt::Display },
        quote! { id.to_string().parse::<#id_type>().expect("Failed to parse ID") },
    )
}

/// Generate serde derives - uses cfg!() at proc-macro compile time
pub fn get_serde_derives() -> proc_macro2::TokenStream {
    if cfg!(feature = "serde") {
        quote! {
            #[derive(serde::Serialize, serde::Deserialize)]
        }
    } else {
        quote! {}
    }
}

/// Generate serde derives for simple tuple structs (single field)
pub fn get_serde_derives_transparent() -> proc_macro2::TokenStream {
    if cfg!(feature = "serde") {
        quote! {
            #[derive(serde::Serialize, serde::Deserialize)]
            #[serde(transparent)]
        }
    } else {
        quote! {}
    }
}

/// Resolve a symlink target path by looking up identities in the tree structure
fn resolve_symlink_target_path(
    target_path: &str,
    root_children: &[Child],
    up_dirs: &str,
    _current_depth: usize,
) -> Option<proc_macro2::TokenStream> {
    // Handle absolute paths by stripping leading slash
    let path_to_resolve = target_path.strip_prefix('/').unwrap_or(target_path);

    // Split path into components
    let path_parts: Vec<&str> = path_to_resolve
        .split('/')
        .filter(|s| !s.is_empty())
        .collect();

    if path_parts.is_empty() {
        return None;
    }

    // Try to find the target identity in the root children
    if let Some(target_child) = find_child_by_identity(&path_parts, root_children) {
        // Check if the target has a custom filename
        let target_filename = match target_child {
            Child::File {
                custom_filename: Some(filename_lit),
                ..
            } => filename_lit.value(),
            Child::File {
                name,
                custom_filename: None,
                ..
            }
            | Child::Directory { name, .. } => {
                name.to_string() // Use identity name directly
            }
            Child::DynamicId { .. } => {
                // Dynamic IDs can't be resolved at compile time
                return None;
            }
        };

        // Build the relative path with the correct filename
        let path_prefix = if path_parts.len() > 1 {
            path_parts[..path_parts.len() - 1].join("/")
        } else {
            String::new()
        };

        let full_path = if path_prefix.is_empty() {
            format!("{up_dirs}{target_filename}")
        } else {
            format!("{up_dirs}{path_prefix}/{target_filename}")
        };

        return Some(quote! { #full_path });
    }

    None
}

/// Find a child by following the identity path
fn find_child_by_identity<'a>(path_parts: &[&str], children: &'a [Child]) -> Option<&'a Child> {
    if path_parts.is_empty() {
        return None;
    }

    let first_part = path_parts[0];
    let remaining_parts = &path_parts[1..];

    // Find the child with matching identity name
    for child in children {
        let child_name = match child {
            Child::File { name, .. } | Child::Directory { name, .. } => name.to_string(),
            Child::DynamicId { id_name, .. } => id_name.to_string(),
        };

        if child_name == first_part {
            if remaining_parts.is_empty() {
                // Found the target
                return Some(child);
            }
            // Continue searching in child's children
            if let Child::Directory {
                children: dir_children,
                ..
            } = child
            {
                return find_child_by_identity(remaining_parts, dir_children);
            }
        }
    }

    None
}

pub fn generate_code(tree: &TreeDef) -> proc_macro2::TokenStream {
    let root_name = &tree.name;
    let mut structs = Vec::new();

    // Generate root struct with full method set
    structs.push(generate_root_struct(root_name, &tree.children));

    // Generate child structs recursively
    generate_child_structs(root_name, &tree.children, &mut structs, 0, &tree.children);

    quote! {
        #(#structs)*
    }
}

#[allow(clippy::too_many_lines)]
fn generate_root_struct(name: &Ident, children: &[Child]) -> proc_macro2::TokenStream {
    let nav_methods = children
        .iter()
        .map(|child| generate_nav_method(name, child));

    let children_method = generate_children_method(children, false, false);
    let parent_method = generate_parent_method(None);

    let validate_impl = generate_validate_method(children);
    let setup_impl = generate_setup_method(children, 0, children); // Pass root children
    let ensure_impl = generate_ensure_method(children);
    let sync_impl = generate_sync_method(children);

    // Skip From impl for GenericDir to avoid conflict with reflexive impl
    let from_impl = if name == "GenericDir" {
        quote! {}
    } else {
        quote! {
            pub fn from_generic(dir: ::tree_type::GenericDir) -> Self {
                Self { path: dir.as_path().to_path_buf() }
            }
        }
    };

    let from_trait = if name == "GenericDir" {
        quote! {}
    } else {
        quote! {
            impl From<#name> for ::tree_type::GenericDir {
                fn from(dir: #name) -> Self {
                    Self::new(dir.path).expect("Path validation already performed")
                }
            }
        }
    };

    let serde_derives = get_serde_derives();
    let walk_fns = build_walk_fns();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericDir {
                ::tree_type::GenericDir::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn create(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir(&self.path)
            }

            pub fn create_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir_all(&self.path)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir(&self.path)
            }

            pub fn remove_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir_all(&self.path)
            }

            pub fn read_dir(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<::tree_type::GenericPath>>> {
                ::tree_type::fs::read_dir(&self.path)
                    .map(|read_dir| read_dir.map(|result| result.and_then(::tree_type::GenericPath::try_from)))
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.path)
            }

            /// Returns the final component of the path as a String.
            /// For root paths like "/", returns an empty string.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.path.file_name()
                    .map(|name| name.to_string_lossy().to_string())
                    .unwrap_or_default()
            }

            #walk_fns

            #validate_impl
            #setup_impl
            #ensure_impl
            #sync_impl

            #from_impl

            #(#nav_methods)*

            #children_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl

        #debug_impl

        #from_trait
    }
}

pub fn build_walk_fns() -> proc_macro2::TokenStream {
    // Use cfg!() at proc-macro compile time to decide whether to generate walk methods.
    // This ensures the decision is based on tree-type's features, not the consumer's.
    if cfg!(feature = "walk") {
        quote! {
            /// Create a WalkDir iterator for the given path
            pub fn walk_dir(&self) -> ::tree_type::deps::walk::WalkDir {
                self.as_generic().walk_dir()
            }

            /// Walk directory and return iterator of paths
            pub fn walk(&self) -> impl Iterator<Item = std::io::Result<::tree_type::GenericPath>> {
                ::tree_type::deps::walk::WalkDir::new(&self.path)
                    .into_iter()
                    .map(|r| r.map_err(|e| e.into()).and_then(::tree_type::GenericPath::try_from))
            }

            /// Calculate total size in bytes of directory contents
            pub fn size_in_bytes(&self) -> std::io::Result<u64> {
                self.as_generic().size_in_bytes()
            }

            /// List directory contents with metadata
            pub fn lsl(
                &self
            ) -> std::io::Result<Vec<(std::path::PathBuf, std::fs::Metadata)>> {
                self.as_generic().lsl()
            }
        }
    } else {
        quote! {}
    }
}

fn generate_child_structs(
    parent_name: &Ident,
    children: &[Child],
    structs: &mut Vec<proc_macro2::TokenStream>,
    depth: usize,
    root_children: &[Child],
) {
    generate_child_structs_with_parent_info(
        parent_name,
        children,
        structs,
        depth,
        root_children,
        None,
        false, // Root level, no grandparent
    );
}

fn generate_child_structs_with_parent_info(
    parent_name: &Ident,
    children: &[Child],
    structs: &mut Vec<proc_macro2::TokenStream>,
    depth: usize,
    root_children: &[Child],
    parent_dynamic_id_info: Option<&syn::Type>,
    grandparent_is_dynamic: bool,
) {
    for child in children {
        match child {
            Child::File {
                name,
                custom_type,
                attributes,
                ..
            } => generate_child_file_structs_with_parent_info(
                parent_name,
                structs,
                parent_dynamic_id_info,
                grandparent_is_dynamic,
                name,
                custom_type.as_ref(),
                attributes,
            ),
            Child::Directory {
                name,
                custom_type,
                children,
                ..
            } => generate_child_directory_structs_with_parent_info(
                parent_name,
                structs,
                depth,
                root_children,
                parent_dynamic_id_info,
                grandparent_is_dynamic,
                name,
                custom_type.as_ref(),
                children,
            ),
            Child::DynamicId {
                child_type,
                children,
                attributes,
                is_directory,
                id_name,
                id_type,
                ..
            } => generate_child_dynamic_id_structs_with_parent_info(
                parent_name,
                structs,
                depth,
                root_children,
                parent_dynamic_id_info,
                grandparent_is_dynamic,
                child_type,
                children,
                attributes,
                *is_directory,
                id_name,
                id_type,
            ),
        }
    }
}

#[expect(clippy::too_many_arguments)]
fn generate_child_dynamic_id_structs_with_parent_info(
    parent_name: &Ident,
    structs: &mut Vec<proc_macro2::TokenStream>,
    depth: usize,
    root_children: &[Child],
    parent_dynamic_id_info: Option<&syn::Type>,
    grandparent_is_dynamic: bool,
    child_type: &Ident,
    children: &[Child],
    attributes: &[Attribute],
    is_directory: bool,
    id_name: &Ident,
    id_type: &syn::Type,
) {
    if is_directory {
        if let Some(parent_id_type) = parent_dynamic_id_info {
            // Parent is a dynamic ID type, generate special directory struct with 3 parameters
            structs.push(generate_dynamic_dir_struct_with_dynamic_parent(
                child_type,
                children,
                depth + 1,
                root_children,
                parent_name,
                id_name,
                id_type,
                parent_id_type,
                grandparent_is_dynamic,
            ));
        } else {
            // Regular parent type, generate normal dynamic directory struct with 2 parameters
            structs.push(generate_dynamic_dir_struct(
                child_type,
                children,
                depth + 1,
                root_children,
                Some(parent_name),
                id_name,
                id_type,
            ));
        }
        // Pass dynamic ID info to children - dynamic ID directories always pass their ID to children
        generate_child_structs_with_parent_info(
            child_type,
            children,
            structs,
            depth + 1,
            root_children,
            Some(id_type),
            parent_dynamic_id_info.is_some(), // This dynamic ID is nested if its parent is also dynamic
        );
    } else if let Some(parent_id_type) = parent_dynamic_id_info {
        // Parent is a dynamic ID type, generate special file struct
        structs.push(generate_dynamic_file_struct_with_dynamic_parent(
            child_type,
            attributes,
            parent_name,
            id_name,
            id_type,
            parent_id_type,
            grandparent_is_dynamic,
        ));
    } else {
        // Regular parent type
        structs.push(generate_dynamic_file_struct(
            child_type,
            attributes,
            Some(parent_name),
            id_name,
            id_type,
        ));
    }
}

#[expect(clippy::too_many_arguments)]
fn generate_child_directory_structs_with_parent_info(
    parent_name: &Ident,
    structs: &mut Vec<proc_macro2::TokenStream>,
    depth: usize,
    root_children: &[Child],
    parent_dynamic_id_info: Option<&syn::Type>,
    grandparent_is_dynamic: bool,
    name: &Ident,
    custom_type: Option<&Ident>,
    children: &[Child],
) {
    let struct_name = get_child_type_name(parent_name, name, custom_type);
    if let Some(parent_id_type) = parent_dynamic_id_info {
        // Parent is a dynamic ID type, generate special directory struct
        structs.push(generate_dir_struct_with_dynamic_parent(
            &struct_name,
            children,
            depth + 1,
            root_children,
            parent_name,
            parent_id_type,
        ));
        // Propagate dynamic parent info to children so they can store parent ID for their parent methods
        generate_child_structs_with_parent_info(
            &struct_name,
            children,
            structs,
            depth + 1,
            root_children,
            Some(parent_id_type),
            grandparent_is_dynamic,
        );
    } else {
        // Regular parent type
        structs.push(generate_dir_struct(
            &struct_name,
            children,
            depth + 1,
            root_children,
            Some(parent_name),
        ));
        generate_child_structs(&struct_name, children, structs, depth + 1, root_children);
    }
}

fn generate_child_file_structs_with_parent_info(
    parent_name: &Ident,
    structs: &mut Vec<proc_macro2::TokenStream>,
    parent_dynamic_id_info: Option<&syn::Type>,
    grandparent_is_dynamic: bool,
    name: &Ident,
    custom_type: Option<&Ident>,
    attributes: &[Attribute],
) {
    let struct_name = get_child_type_name(parent_name, name, custom_type);
    if let Some(parent_id_type) = parent_dynamic_id_info {
        // Parent is a dynamic ID type, generate special file struct
        structs.push(generate_file_struct_with_dynamic_parent(
            &struct_name,
            attributes,
            parent_name,
            parent_id_type,
            grandparent_is_dynamic,
        ));
    } else {
        // Regular parent type
        structs.push(generate_file_struct(
            &struct_name,
            attributes,
            Some(parent_name),
        ));
    }
}

fn generate_nav_method_for_dynamic_id_parent(
    parent_name: &Ident,
    child: &Child,
    _parent_id_name: &Ident,
) -> proc_macro2::TokenStream {
    match child {
        Child::File {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let filename = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            quote! {
                pub fn #method_name(&self) -> #return_type {
                    #return_type::new(self.path.join(#filename), self.id.clone()).expect("Path validation already performed")
                }
            }
        }
        Child::Directory {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let filename = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            quote! {
                pub fn #method_name(&self) -> #return_type {
                    #return_type::new(self.path.join(#filename), self.id.clone()).expect("Path validation already performed")
                }
            }
        }
        Child::DynamicId { .. } => {
            // Dynamic ID children are handled by the existing generate_nav_method
            generate_nav_method_with_parent_info(parent_name, child, true)
        }
    }
}

fn generate_nav_method(parent_name: &Ident, child: &Child) -> proc_macro2::TokenStream {
    match child {
        Child::File {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let filename = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            quote! {
                pub fn #method_name(&self) -> #return_type {
                    #return_type::new(self.path.join(#filename)).expect("Path validation already performed")
                }
            }
        }
        Child::Directory {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let dirname = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            quote! {
                pub fn #method_name(&self) -> #return_type {
                    #return_type::new(self.path.join(#dirname)).expect("Path validation already performed")
                }
            }
        }
        Child::DynamicId {
            id_name,
            id_type,
            child_type,
            pattern,
            ..
        } => {
            // Generate parameterized method for type-safe access
            let method_name = id_name;

            // Generate type-specific reference signature based on ID type
            let (param_type, conversion) = get_param_type_and_conversion(id_type);

            // Generate filename assembly based on pattern
            let filename_expr = if let Some(pattern_lit) = pattern {
                let pattern_str = pattern_lit.value();
                // Replace {placeholder} with {} for format!
                // First escape all braces, then unescape the placeholder
                let (prefix, suffix) = extract_prefix_suffix(&pattern_str);
                let format_str = format!("{prefix}{{}}{suffix}");
                quote! { format!(#format_str, id_value) }
            } else {
                quote! { id_value.to_string() }
            };

            quote! {
                /// Access a dynamic ID instance by reference.
                ///
                /// This method takes a reference to avoid consuming the parameter,
                /// allowing for better ergonomics and parameter reuse.
                pub fn #method_name(&self, id: #param_type) -> #child_type {
                    let id_value = #conversion;
                    #child_type::new(self.path.join(#filename_expr), id_value).expect("Path validation already performed")
                }
            }
        }
    }
}

fn generate_nav_method_with_parent_info(
    parent_name: &Ident,
    child: &Child,
    parent_is_dynamic_id: bool,
) -> proc_macro2::TokenStream {
    match child {
        Child::File {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let filename = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            if parent_is_dynamic_id {
                quote! {
                    pub fn #method_name(&self) -> #return_type {
                        #return_type::new(self.path.join(#filename), self.id.clone()).expect("Path validation already performed")
                    }
                }
            } else {
                quote! {
                    pub fn #method_name(&self) -> #return_type {
                        #return_type::new(self.path.join(#filename)).expect("Path validation already performed")
                    }
                }
            }
        }
        Child::Directory {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let dirname = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            if parent_is_dynamic_id {
                quote! {
                    pub fn #method_name(&self) -> #return_type {
                        #return_type::new(self.path.join(#dirname), self.id.clone()).expect("Path validation already performed")
                    }
                }
            } else {
                quote! {
                    pub fn #method_name(&self) -> #return_type {
                        #return_type::new(self.path.join(#dirname)).expect("Path validation already performed")
                    }
                }
            }
        }
        Child::DynamicId {
            id_name,
            id_type,
            child_type,
            pattern,
            ..
        } => {
            // Generate parameterized method for type-safe access
            let method_name = id_name;

            // Generate type-specific reference signature based on ID type
            let (param_type, conversion) = get_param_type_and_conversion(id_type);

            // Generate filename assembly based on pattern
            let filename_expr = if let Some(pattern_lit) = pattern {
                let pattern_str = pattern_lit.value();
                // Replace {placeholder} with {} for format!
                let (prefix, suffix) = extract_prefix_suffix(&pattern_str);
                let format_str = format!("{prefix}{{}}{suffix}");
                quote! { format!(#format_str, id_value) }
            } else {
                quote! { id_value.to_string() }
            };

            if parent_is_dynamic_id {
                quote! {
                    /// Access a dynamic ID instance by reference.
                    ///
                    /// This method takes a reference to avoid consuming the parameter,
                    /// allowing for better ergonomics and parameter reuse.
                    pub fn #method_name(&self, id: #param_type) -> #child_type {
                        let id_value = #conversion;
                        #child_type::new(self.path.join(#filename_expr), id_value, self.id.clone()).expect("Path validation already performed")
                    }
                }
            } else {
                quote! {
                    /// Access a dynamic ID instance by reference.
                    ///
                    /// This method takes a reference to avoid consuming the parameter,
                    /// allowing for better ergonomics and parameter reuse.
                    pub fn #method_name(&self, id: #param_type) -> #child_type {
                        let id_value = #conversion;
                        #child_type::new(self.path.join(#filename_expr), id_value).expect("Path validation already performed")
                    }
                }
            }
        }
    }
}

fn generate_nav_method_for_dynamic_parent_children(
    parent_name: &Ident,
    child: &Child,
) -> proc_macro2::TokenStream {
    match child {
        Child::File {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let filename = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            quote! {
                pub fn #method_name(&self) -> #return_type {
                    #return_type::new(self.path.join(#filename), self.parent_id.clone()).expect("Path validation already performed")
                }
            }
        }
        Child::Directory {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let dirname = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            quote! {
                pub fn #method_name(&self) -> #return_type {
                    #return_type::new(self.path.join(#dirname), self.parent_id.clone()).expect("Path validation already performed")
                }
            }
        }
        Child::DynamicId {
            id_name,
            id_type,
            child_type,
            ..
        } => {
            // Generate parameterized method for type-safe access
            let method_name = id_name;
            let param_type = quote! { impl std::fmt::Display };
            let conversion =
                quote! { id.to_string().parse::<#id_type>().expect("Failed to parse ID") };

            quote! {
                /// Access a dynamic ID instance by reference.
                ///
                /// This method takes a reference to avoid consuming the parameter,
                /// allowing for better ergonomics and parameter reuse.
                pub fn #method_name(&self, id: #param_type) -> #child_type {
                    let id_value = #conversion;
                    #child_type::new(self.path.join(id_value.to_string()), id_value, self.parent_id.clone()).expect("Path validation already performed")
                }
            }
        }
    }
}

/// Information about a dynamic ID child for children method generation
struct DynamicChildInfo<'a> {
    id_name: &'a Ident,
    child_type: &'a Ident,
    is_directory: bool,
    id_type: &'a syn::Type,
    pattern: Option<&'a syn::LitStr>,
}

fn generate_children_method(
    children: &[Child],
    parent_has_dynamic_id: bool,
    current_is_dynamic_id: bool,
) -> Option<proc_macro2::TokenStream> {
    // Find all dynamic ID children
    let dynamic_children: Vec<DynamicChildInfo> = children
        .iter()
        .filter_map(|child| {
            if let Child::DynamicId {
                id_name,
                child_type,
                is_directory,
                id_type,
                pattern,
                ..
            } = child
            {
                Some(DynamicChildInfo {
                    id_name,
                    child_type,
                    is_directory: *is_directory,
                    id_type,
                    pattern: pattern.as_ref(),
                })
            } else {
                None
            }
        })
        .collect();

    if dynamic_children.is_empty() {
        return None;
    }

    // Validate: at most one dynamic ID without pattern
    let patternless_count = dynamic_children
        .iter()
        .filter(|c| c.pattern.is_none())
        .count();
    assert!(
        patternless_count <= 1,
        "At most one dynamic ID without a pattern is allowed per directory. \
         Found {patternless_count} dynamic IDs without patterns. Use patterns like \
         `[name: Type](\"prefix-{{placeholder}}.ext\")` to distinguish them."
    );

    // Single dynamic ID: generate children() method (backward compatible)
    if dynamic_children.len() == 1 {
        let info = &dynamic_children[0];
        return Some(generate_single_children_method(
            info,
            parent_has_dynamic_id,
            current_is_dynamic_id,
        ));
    }

    // Multiple dynamic IDs: generate {name}_children() for each
    let methods: Vec<_> = dynamic_children
        .iter()
        .map(|info| {
            generate_named_children_method(
                info,
                &dynamic_children,
                parent_has_dynamic_id,
                current_is_dynamic_id,
            )
        })
        .collect();

    Some(quote! { #(#methods)* })
}

fn generate_single_children_method(
    info: &DynamicChildInfo,
    parent_has_dynamic_id: bool,
    current_is_dynamic_id: bool,
) -> proc_macro2::TokenStream {
    let dynamic_child = info.child_type;
    let id_type = info.id_type;

    // Generate the appropriate file type check
    let file_type_check = if info.is_directory {
        quote! { entry_path.is_dir() }
    } else {
        quote! { entry_path.is_file() }
    };

    // Generate constructor call
    let constructor_call = if parent_has_dynamic_id {
        quote! { #dynamic_child::new(entry_path, id, self.parent_id.clone()).map_err(std::io::Error::from) }
    } else if current_is_dynamic_id {
        quote! { #dynamic_child::new(entry_path, id, self.id.clone()).map_err(std::io::Error::from) }
    } else {
        quote! { #dynamic_child::new(entry_path, id).map_err(std::io::Error::from) }
    };

    // Generate ID extraction based on pattern
    let id_extraction = generate_id_extraction(info.pattern, id_type, &constructor_call);

    quote! {
        /// Iterate over dynamic ID children in this directory.
        pub fn children(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<#dynamic_child>>> {
            let path = self.path.clone();
            let read_dir = ::tree_type::fs::read_dir(&path)?;
            Ok(read_dir.filter_map(move |entry| {
                match entry {
                    Ok(entry) => {
                        let entry_path = entry.path();
                        if #file_type_check {
                            if let Some(filename) = entry_path.file_name() {
                                if let Some(id_str) = filename.to_str() {
                                    #id_extraction
                                } else {
                                    None
                                }
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    }
                    Err(e) => Some(Err(e))
                }
            }))
        }
    }
}

fn generate_named_children_method(
    info: &DynamicChildInfo,
    all_dynamic_children: &[DynamicChildInfo],
    parent_has_dynamic_id: bool,
    current_is_dynamic_id: bool,
) -> proc_macro2::TokenStream {
    let method_name = format_ident!("{}_children", info.id_name);
    let dynamic_child = info.child_type;
    let id_type = info.id_type;

    // Generate the appropriate file type check
    let file_type_check = if info.is_directory {
        quote! { entry_path.is_dir() }
    } else {
        quote! { entry_path.is_file() }
    };

    // Generate constructor call
    let constructor_call = if parent_has_dynamic_id {
        quote! { #dynamic_child::new(entry_path, id, self.parent_id.clone()).map_err(std::io::Error::from) }
    } else if current_is_dynamic_id {
        quote! { #dynamic_child::new(entry_path, id, self.id.clone()).map_err(std::io::Error::from) }
    } else {
        quote! { #dynamic_child::new(entry_path, id).map_err(std::io::Error::from) }
    };

    // Generate ID extraction based on pattern
    let id_extraction = generate_id_extraction(info.pattern, id_type, &constructor_call);

    // For pattern-less dynamic ID, generate exclusion filter for other patterns
    let pattern_filter = if info.pattern.is_none() {
        // Collect all sibling patterns to exclude
        let sibling_patterns: Vec<_> = all_dynamic_children
            .iter()
            .filter_map(|c| c.pattern.map(syn::LitStr::value))
            .collect();

        if sibling_patterns.is_empty() {
            quote! { true }
        } else {
            // Generate pattern matching exclusions
            let exclusions: Vec<_> = sibling_patterns
                .iter()
                .map(|p| generate_pattern_match_check(p))
                .collect();
            quote! { #(!#exclusions)&&* }
        }
    } else {
        quote! { true }
    };

    quote! {
        /// Iterate over dynamic ID children matching this pattern.
        pub fn #method_name(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<#dynamic_child>>> {
            let path = self.path.clone();
            let read_dir = ::tree_type::fs::read_dir(&path)?;
            Ok(read_dir.filter_map(move |entry| {
                match entry {
                    Ok(entry) => {
                        let entry_path = entry.path();
                        if #file_type_check {
                            if let Some(filename) = entry_path.file_name() {
                                if let Some(id_str) = filename.to_str() {
                                    if #pattern_filter {
                                        #id_extraction
                                    } else {
                                        None
                                    }
                                } else {
                                    None
                                }
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    }
                    Err(e) => Some(Err(e))
                }
            }))
        }
    }
}

/// Generate ID extraction code based on pattern
fn generate_id_extraction(
    pattern: Option<&syn::LitStr>,
    id_type: &syn::Type,
    constructor_call: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    if let Some(pattern_lit) = pattern {
        let pattern_str = pattern_lit.value();
        // Find prefix and suffix around {placeholder}
        let (prefix, suffix) = extract_prefix_suffix(&pattern_str);

        quote! {
            // Extract ID from pattern: prefix{id}suffix
            let prefix = #prefix;
            let suffix = #suffix;
            if id_str.starts_with(prefix) && id_str.ends_with(suffix) {
                let id_part = &id_str[prefix.len()..id_str.len() - suffix.len()];
                match id_part.parse::<#id_type>() {
                    Ok(id) => Some(#constructor_call),
                    Err(_) => None,
                }
            } else {
                None
            }
        }
    } else {
        quote! {
            match id_str.parse::<#id_type>() {
                Ok(id) => Some(#constructor_call),
                Err(_) => None,
            }
        }
    }
}

/// Generate pattern match check for exclusion filtering
fn generate_pattern_match_check(pattern: &str) -> proc_macro2::TokenStream {
    let (prefix, suffix) = extract_prefix_suffix(pattern);
    quote! { (id_str.starts_with(#prefix) && id_str.ends_with(#suffix)) }
}

/// Extract prefix and suffix from a pattern string
fn extract_prefix_suffix(pattern: &str) -> (String, String) {
    if let Some(start) = pattern.find('{') {
        if let Some(end) = pattern.find('}') {
            let prefix = pattern[..start].to_string();
            let suffix = pattern[end + 1..].to_string();
            return (prefix, suffix);
        }
    }
    (String::new(), String::new())
}

fn generate_parent_method(parent_type: Option<&Ident>) -> proc_macro2::TokenStream {
    match parent_type {
        Some(parent_type) => {
            // Type-safe parent method for non-root types
            quote! {
                /// Get the parent directory with type-safe return type.
                pub fn parent(&self) -> #parent_type {
                    let parent_path = self.path.parent().expect("Non-root type must have parent");
                    #parent_type::new(parent_path).expect("Parent path should be valid")
                }
            }
        }
        None => {
            // Root type returns Option<GenericDir>
            quote! {
                /// Get the parent directory as GenericDir.
                /// Returns None for root directories or if parent cannot be determined.
                pub fn parent(&self) -> Option<::tree_type::GenericDir> {
                    self.path.parent().and_then(|parent_path| {
                        ::tree_type::GenericDir::new(parent_path).ok()
                    })
                }
            }
        }
    }
}

fn get_child_type_name(
    parent_name: &Ident,
    child_name: &Ident,
    custom_type: Option<&Ident>,
) -> Ident {
    custom_type.cloned().unwrap_or_else(|| {
        Ident::new(
            &format!("{}{}", parent_name, capitalize(&child_name.to_string())),
            child_name.span(),
        )
    })
}

fn generate_create_default_method(default_val: &DefaultValue) -> proc_macro2::TokenStream {
    match default_val {
        DefaultValue::DefaultTrait => {
            quote! {
                pub fn create_default<E>(&self) -> std::result::Result<::tree_type::CreateDefaultOutcome, E>
                where
                    E: From<std::io::Error>,
                {
                    if self.exists() {
                        return Ok(tree_type::CreateDefaultOutcome::AlreadyExists);
                    }
                    self.write(&String::default())?;
                    Ok(tree_type::CreateDefaultOutcome::Created)
                }
            }
        }
        DefaultValue::Literal(lit) => {
            quote! {
                pub fn create_default<E>(&self) -> std::result::Result<::tree_type::CreateDefaultOutcome, E>
                where
                    E: From<std::io::Error>,
                {
                    if self.exists() {
                        return Ok(tree_type::CreateDefaultOutcome::AlreadyExists);
                    }
                    self.write(&#lit.to_string())?;
                    Ok(tree_type::CreateDefaultOutcome::Created)
                }
            }
        }
        DefaultValue::Function(expr) => {
            quote! {
                pub fn create_default<E>(&self) -> std::result::Result<::tree_type::CreateDefaultOutcome, E>
                where
                    E: From<std::io::Error>,
                {
                    if self.exists() {
                        return Ok(tree_type::CreateDefaultOutcome::AlreadyExists);
                    }
                    let content = (#expr)(self)?;
                    self.write(&content)?;
                    Ok(tree_type::CreateDefaultOutcome::Created)
                }
            }
        }
    }
}

fn generate_file_struct_with_dynamic_parent(
    name: &Ident,
    attributes: &[Attribute],
    parent_type: &Ident,
    parent_id_type: &syn::Type,
    parent_is_nested: bool,
) -> proc_macro2::TokenStream {
    // Find default attribute if present
    let default_method = attributes.iter().find_map(|attr| {
        if let Attribute::Default(val) = attr {
            Some(generate_create_default_method(val))
        } else {
            None
        }
    });

    let parent_method = if parent_is_nested {
        // Parent is nested inside another dynamic ID, needs 3 parameters
        quote! {
            /// Get the parent directory with type-safe return type.
            pub fn parent(&self) -> #parent_type {
                let parent_path = self.path.parent().expect("Non-root type must have parent");

                // Extract grandparent ID from path for nested dynamic IDs
                // Path structure: .../grandparent_id/parent_id/file
                let grandparent_path = parent_path.parent().expect("Parent should have a grandparent");
                let grandparent_id = grandparent_path.file_name()
                    .expect("Grandparent path should have a filename")
                    .to_string_lossy()
                    .to_string();

                #parent_type::new(parent_path, self.parent_id.clone(), grandparent_id).expect("Parent path should be valid")
            }
        }
    } else {
        // Parent is not nested, needs 2 parameters
        quote! {
            /// Get the parent directory with type-safe return type.
            pub fn parent(&self) -> #parent_type {
                let parent_path = self.path.parent().expect("Non-root type must have parent");
                #parent_type::new(parent_path, self.parent_id.clone()).expect("Parent path should be valid")
            }
        }
    };

    let serde_derives = get_serde_derives();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
            parent_id: #parent_id_type,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>, parent_id: #parent_id_type) -> std::io::Result<Self> {
                let path_buf = path.into();
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf, parent_id })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericFile {
                ::tree_type::GenericFile::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn read(&self) -> std::io::Result<Vec<u8>> {
                ::tree_type::fs::read(&self.path)
            }

            pub fn read_to_string(&self) -> std::io::Result<String> {
                ::tree_type::fs::read_to_string(&self.path)
            }

            pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
                if let Some(parent) = self.path.parent() {
                    ::tree_type::fs::create_dir_all(parent)?;
                }
                ::tree_type::fs::write(&self.path, contents)
            }

            pub fn file_name(&self) -> Option<std::ffi::OsString> {
                self.path.file_name().map(|name| name.to_os_string())
            }

            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            pub fn from_generic(file: ::tree_type::GenericFile, parent_id: #parent_id_type) -> Self {
                Self { path: file.as_path().to_path_buf(), parent_id }
            }

            #default_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl
        #debug_impl

        impl From<#name> for ::tree_type::GenericFile {
            fn from(file: #name) -> Self {
                Self::new(file.path).expect("Path validation already performed")
            }
        }
    }
}

#[expect(clippy::too_many_lines)]
fn generate_dir_struct_with_dynamic_parent(
    name: &Ident,
    children: &[Child],
    depth: usize,
    root_children: &[Child],
    parent_type: &Ident,
    parent_id_type: &syn::Type,
) -> proc_macro2::TokenStream {
    let nav_methods = children
        .iter()
        .map(|child| generate_nav_method_for_dynamic_parent_children(name, child));

    let children_method = generate_children_method(children, true, false);

    let parent_method = quote! {
        /// Get the parent directory with type-safe return type.
        pub fn parent(&self) -> #parent_type {
            let parent_path = self.path.parent().expect("Non-root type must have parent");
            #parent_type::new(parent_path, self.parent_id.clone()).expect("Parent path should be valid")
        }
    };

    let validate_impl = generate_validate_method_with_parent_info(children, true, false);
    let setup_impl = generate_setup_method(children, depth, root_children);
    let ensure_impl = generate_ensure_method(children);
    let sync_impl = generate_sync_method(children);

    let serde_derives = get_serde_derives();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
            parent_id: #parent_id_type,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>, parent_id: #parent_id_type) -> std::io::Result<Self> {
                let path_buf = path.into();
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf, parent_id })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericDir {
                ::tree_type::GenericDir::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn create(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir(&self.path)
            }

            pub fn create_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir_all(&self.path)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir(&self.path)
            }

            pub fn remove_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir_all(&self.path)
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.path)
            }

            #[cfg(feature = "walk")]
            pub fn walk_dir(&self) -> ::tree_type::deps::walk::WalkDir {
                ::tree_type::deps::walk::WalkDir::new(&self.path)
            }

            #[cfg(feature = "walk")]
            pub fn walk(&self) -> impl Iterator<Item = std::io::Result<::tree_type::GenericPath>> {
                ::tree_type::deps::walk::WalkDir::new(&self.path)
                    .into_iter()
                    .map(|r| r.map_err(|e| e.into()).and_then(::tree_type::GenericPath::try_from))
            }

            #[cfg(feature = "walk")]
            pub fn size_in_bytes(&self) -> std::io::Result<u64> {
                let mut total = 0u64;
                for entry in ::tree_type::deps::walk::WalkDir::new(&self.path) {
                    let entry = entry?;
                    if entry.file_type().is_file() {
                        total += entry.metadata()?.len();
                    }
                }
                Ok(total)
            }

            pub fn file_name(&self) -> String {
                self.path.file_name()
                    .map(|name| name.to_string_lossy().to_string())
                    .unwrap_or_default()
            }

            pub fn rename(self, new_path: impl AsRef<std::path::Path>) -> Result<Self, (std::io::Error, Self)> {
                let new_path = new_path.as_ref();
                if let Some(parent) = new_path.parent() {
                    if !parent.exists() {
                        if let Err(e) = std::fs::create_dir_all(parent) {
                            return Err((e, self));
                        }
                    }
                }
                match ::tree_type::fs::rename(&self.path, new_path) {
                    Ok(()) => Self::new(new_path, self.parent_id.clone()).map_err(|e| (e, self)),
                    Err(e) => Err((e, self)),
                }
            }

            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            pub fn from_generic(dir: ::tree_type::GenericDir, parent_id: #parent_id_type) -> Self {
                Self { path: dir.as_path().to_path_buf(), parent_id }
            }

            #(#nav_methods)*

            #children_method

            #parent_method

            #validate_impl

            #setup_impl

            #ensure_impl

            #sync_impl
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericDir {
            fn from(dir: #name) -> Self {
                Self::new(dir.path).expect("Path validation already performed")
            }
        }
    }
}

fn generate_file_struct(
    name: &Ident,
    attributes: &[Attribute],
    parent_type: Option<&Ident>,
) -> proc_macro2::TokenStream {
    // Find default attribute if present
    let default_method = attributes.iter().find_map(|attr| {
        if let Attribute::Default(val) = attr {
            Some(generate_create_default_method(val))
        } else {
            None
        }
    });

    let parent_method = generate_parent_method(parent_type);

    let serde_derives = get_serde_derives();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericFile {
                ::tree_type::GenericFile::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn read(&self) -> std::io::Result<Vec<u8>> {
                ::tree_type::fs::read(&self.path)
            }

            pub fn read_to_string(&self) -> std::io::Result<String> {
                ::tree_type::fs::read_to_string(&self.path)
            }

            pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
                if let Some(parent) = self.path.parent() {
                    if !parent.exists() {
                        ::tree_type::fs::create_dir_all(parent)?;
                    }
                }
                ::tree_type::fs::write(&self.path, contents)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_file(&self.path)
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.path)
            }

            /// Returns the final component of the path as a String.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.path.file_name()
                    .expect("validated in new")
                    .to_string_lossy()
                    .to_string()
            }

            /// Set file permissions to 0o600 (read/write for owner only).
            ///
            /// This method is only available on Unix systems.
            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            pub fn from_generic(file: ::tree_type::GenericFile) -> Self {
                Self { path: file.as_path().to_path_buf() }
            }

            #default_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericFile {
            fn from(file: #name) -> Self {
                Self::new(file.path).expect("Path validation already performed")
            }
        }
    }
}

fn generate_dir_struct(
    name: &Ident,
    children: &[Child],
    depth: usize,
    root_children: &[Child],
    parent_type: Option<&Ident>,
) -> proc_macro2::TokenStream {
    let nav_methods = children
        .iter()
        .map(|child| generate_nav_method(name, child));

    let children_method = generate_children_method(children, false, false);
    let parent_method = generate_parent_method(parent_type);

    let validate_impl = generate_validate_method(children);
    let setup_impl = generate_setup_method(children, depth, root_children);
    let ensure_impl = generate_ensure_method(children);
    let sync_impl = generate_sync_method(children);

    let serde_derives = get_serde_derives();
    let walk_fns = build_walk_fns();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericDir {
                ::tree_type::GenericDir::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn create(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir(&self.path)
            }

            pub fn create_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir_all(&self.path)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir(&self.path)
            }

            pub fn remove_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir_all(&self.path)
            }

            pub fn read_dir(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<::tree_type::GenericPath>>> {
                ::tree_type::fs::read_dir(&self.path)
                    .map(|read_dir| read_dir.map(|result| result.and_then(::tree_type::GenericPath::try_from)))
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.path)
            }

            /// Set directory permissions to 0o700 (read/write/execute for owner only).
            ///
            /// This method is only available on Unix systems.
            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            #walk_fns

            #validate_impl
            #setup_impl
            #ensure_impl
            #sync_impl

            /// Returns the final component of the path as a String.
            /// For root paths like "/", returns an empty string.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.path.file_name()
                    .map(|name| name.to_string_lossy().to_string())
                    .unwrap_or_default()
            }

            pub fn from_generic(dir: ::tree_type::GenericDir) -> Self {
                Self { path: dir.as_path().to_path_buf() }
            }

            #(#nav_methods)*

            #children_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericDir {
            fn from(dir: #name) -> Self {
                Self::new(dir.path).expect("Path validation already performed")
            }
        }
    }
}

fn capitalize(s: &str) -> String {
    // Convert snake_case to PascalCase
    s.split('_')
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
            }
        })
        .collect()
}

fn generate_validate_method(children: &[Child]) -> proc_macro2::TokenStream {
    generate_validate_method_with_parent_info(children, false, false)
}

fn generate_validate_method_with_parent_info(
    children: &[Child],
    parent_has_dynamic_id: bool,
    current_is_dynamic_id: bool,
) -> proc_macro2::TokenStream {
    let validations = children.iter().map(|child| {
        generate_child_validate_method_with_parent_info(
            parent_has_dynamic_id,
            current_is_dynamic_id,
            child,
        )
    });

    // Add recursive validation for child directories
    let recursive_validations = children.iter().filter_map(|child| match child {
        Child::Directory { name, .. } => Some(quote! {
            if self.#name().exists() {
                #[expect(deprecated)]
                let child_report = self.#name().validate();
                report.merge(child_report);
            }
        }),
        _ => None,
    });

    quote! {
        #[allow(clippy::regex_creation_in_loops)]
        #[deprecated(since = "0.2.0", note = "Use `sync()` instead. This method will be removed in v0.6.0")]
        #[expect(deprecated)]
        pub fn validate(&self) -> ::tree_type::ValidationReport {
            let mut report = ::tree_type::ValidationReport::new();

            // Validate root directory exists
            if !self.exists() {
                report.errors.push(tree_type::ValidationError {
                    path: self.path.clone(),
                    message: "Directory does not exist".to_string(),
                });
            }

            #(#validations)*
            #(#recursive_validations)*

            report
        }
    }
}

fn generate_child_validate_method_with_parent_info(
    parent_has_dynamic_id: bool,
    current_is_dynamic_id: bool,
    child: &Child,
) -> proc_macro2::TokenStream {
    if let Child::DynamicId {
        child_type,
        attributes,
        is_directory,
        id_type,
        ..
    } = child
    {
        generate_child_dynamic_id_validate_method_with_parent_info(
            parent_has_dynamic_id,
            current_is_dynamic_id,
            child_type,
            attributes,
            *is_directory,
            id_type,
        )
    } else {
        let name = child.name();

        // Check for pattern validation
        let pattern = child.attributes().iter().find_map(|attr| {
            if let Attribute::Pattern(lit) = attr {
                Some(lit)
            } else {
                None
            }
        });

        // Check for custom validator
        let custom_validator = child.attributes().iter().find_map(|attr| {
            if let Attribute::Validate(expr) = attr {
                Some(expr)
            } else {
                None
            }
        });

        if let Some(pattern_lit) = pattern {
            // Pattern validation
            quote! {
                {
                    if self.#name().exists() {
                        match self.#name().read_to_string() {
                            Ok(content) => {
                                match ::tree_type::deps::pattern_validation::Regex::new(#pattern_lit) {
                                    Ok(re) => {
                                        if !re.is_match(&content) {
                                            report.errors.push(tree_type::ValidationError {
                                                path: self.#name().as_path().to_path_buf(),
                                                message: format!("File content does not match pattern: {}", #pattern_lit),
                                            });
                                        }
                                    }
                                    Err(e) => {
                                        report.errors.push(tree_type::ValidationError {
                                            path: self.#name().as_path().to_path_buf(),
                                            message: format!("Invalid regex pattern: {}", e),
                                        });
                                    }
                                }
                            }
                            Err(e) => {
                                report.errors.push(tree_type::ValidationError {
                                    path: self.#name().as_path().to_path_buf(),
                                    message: format!("Failed to read file: {}", e),
                                });
                            }
                        }
                    }
                }
            }
        } else if let Some(validator) = custom_validator {
            // Call custom validation function
            quote! {
                let result = (#validator)(&self.#name());
                for error in result.errors {
                    report.errors.push(tree_type::ValidationError {
                        path: self.#name().as_path().to_path_buf(),
                        message: error,
                    });
                }
                for warning in result.warnings {
                    report.warnings.push(tree_type::ValidationWarning {
                        path: self.#name().as_path().to_path_buf(),
                        message: warning,
                    });
                }
            }
        } else if child.is_required() {
            // Standard required validation
            quote! {
                if !self.#name().exists() {
                    report.errors.push(tree_type::ValidationError {
                        path: self.#name().as_path().to_path_buf(),
                        message: "Required path does not exist".to_string(),
                    });
                }
            }
        } else {
            quote! {}
        }
    }
}

fn generate_child_dynamic_id_validate_method_with_parent_info(
    parent_has_dynamic_id: bool,
    current_is_dynamic_id: bool,
    child_type: &Ident,
    attributes: &[Attribute],
    is_directory: bool,
    id_type: &syn::Type,
) -> proc_macro2::TokenStream {
    // Check for pattern validation
    let pattern = attributes.iter().find_map(|attr| {
        if let Attribute::Pattern(lit) = attr {
            Some(lit)
        } else {
            None
        }
    });

    // Check for custom validator
    let custom_validator = attributes.iter().find_map(|attr| {
        if let Attribute::Validate(expr) = attr {
            Some(expr)
        } else {
            None
        }
    });

    // Generate validation for dynamic IDs - always recurse into instances

    // Generate the constructor call based on parent type information
    let constructor_call = if parent_has_dynamic_id {
        quote! { #child_type::new(entry_path.clone(), id, self.parent_id.clone()).expect("Path validation already performed") }
    } else if current_is_dynamic_id {
        quote! { #child_type::new(entry_path.clone(), id, self.id.clone()).expect("Path validation already performed") }
    } else {
        quote! { #child_type::new(entry_path.clone(), id).expect("Path validation already performed") }
    };

    let pattern_validation =
        pattern.map(generate_child_dynamic_id_pattern_validate_method_with_parent_info);

    let validator_call = custom_validator
        .map(generate_child_dynamic_id_custom_validator_validate_method_with_parent_info);

    let recursive_validation = if is_directory {
        quote! {
            #[expect(deprecated)]
            let child_report = child_instance.validate();
            report.merge(child_report);
        }
    } else {
        quote! {
            // File types don't have validate() method
        }
    };

    quote! {
        // Validate dynamic ID instances in current directory
        if self.exists() {
            let read_result = ::tree_type::fs::read_dir(&self.path);

            match read_result {
                Ok(entries) => {
                    for entry in entries {
                        match entry {
                            Ok(entry) => {
                                let entry_path = entry.path();

                                // Check if entry matches expected type (file or directory)
                                let is_expected_type = if #is_directory {
                                    entry_path.is_dir()
                                } else {
                                    entry_path.is_file()
                                };

                                if !is_expected_type {
                                    continue;
                                }

                                #pattern_validation

                                // Parse ID from filename and create child instance for validation
                                if let Some(filename) = entry_path.file_name() {
                                    if let Some(id_str) = filename.to_str() {
                                        match id_str.parse::<#id_type>() {
                                            Ok(id) => {
                                                let child_instance = #constructor_call;

                                                #validator_call

                                                // Only recursively validate if it's a directory
                                                #recursive_validation
                                            }
                                            Err(_) => {
                                                // Skip entries that can't be parsed as the expected ID type
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                            Err(e) => {
                                report.errors.push(tree_type::ValidationError {
                                    path: self.path.clone(),
                                    message: format!("Failed to read directory entry: {}", e),
                                });
                            }
                        }
                    }
                }
                Err(e) => {
                    report.errors.push(tree_type::ValidationError {
                        path: self.path.clone(),
                        message: format!("Failed to read directory: {}", e),
                    });
                }
            }
        }
    }
}

fn generate_child_dynamic_id_custom_validator_validate_method_with_parent_info(
    _validator: &syn::Expr,
) -> proc_macro2::TokenStream {
    quote! {
        let result = (#_validator)(&child_instance);
        for error in result.errors {
            report.errors.push(tree_type::ValidationError {
                path: entry_path.clone(),
                message: error,
            });
        }
        for warning in result.warnings {
            report.warnings.push(tree_type::ValidationWarning {
                path: entry_path.clone(),
                message: warning,
            });
        }
    }
}

fn generate_child_dynamic_id_pattern_validate_method_with_parent_info(
    pattern_lit: &syn::LitStr,
) -> proc_macro2::TokenStream {
    quote! {
        {
            let dir_name = entry.file_name();
            let name_str = dir_name.to_string_lossy();
            match ::tree_type::deps::pattern_validation::Regex::new(#pattern_lit) {
                Ok(re) => {
                    if !re.is_match(&name_str) {
                        report.errors.push(tree_type::ValidationError {
                            path: entry_path.clone(),
                            message: format!("Directory name '{}' does not match pattern: {}", name_str, #pattern_lit),
                        });
                        continue;
                    }
                }
                Err(e) => {
                    report.errors.push(tree_type::ValidationError {
                        path: entry_path.clone(),
                        message: format!("Invalid regex pattern: {}", e),
                    });
                    continue;
                }
            }
        }
    }
}

#[expect(clippy::too_many_lines)]
fn generate_setup_method(
    children: &[Child],
    depth: usize,
    root_children: &[Child],
) -> proc_macro2::TokenStream {
    let setups = children.iter().filter_map(|child| {
        let name = child.name();

        // Check for symlink attribute
        if let Some(target_path) = child.get_symlink_target() {
            let target_str = target_path.value();

            // Check if this is a same-directory symlink (identifier-based, no path separators)
            if !target_str.contains('/') {
                // Same-directory symlink: use self.target().as_path()
                let target_ident = syn::Ident::new(&target_str, target_path.span());
                return Some(quote! {
                    if !self.#name().as_path().exists() {
                        // Use relative filename for symlink target
                        let target_filename = self.#target_ident().as_path().file_name().unwrap().to_string_lossy().to_string();

                        #[cfg(unix)]
                        if let Err(e) = std::os::unix::fs::symlink(&target_filename, self.#name().as_path()) {
                            errors.push(tree_type::BuildError::File(
                                self.#name().as_path().to_path_buf(),
                                Box::new(e)
                            ));
                        }
                        #[cfg(windows)]
                        {
                            let result = if self.#target_ident().as_path().is_dir() {
                                std::os::windows::fs::symlink_dir(&target_filename, self.#name().as_path())
                            } else {
                                std::os::windows::fs::symlink_file(&target_filename, self.#name().as_path())
                            };
                            if let Err(e) = result {
                                errors.push(tree_type::BuildError::File(
                                    self.#name().as_path().to_path_buf(),
                                    Box::new(e)
                                ));
                            }
                        }
                    }
                });
            }
            // Cross-directory symlink: resolve identities in path
            let up_dirs_str = "../".repeat(depth);

            // Try to resolve identities in the target path
            if let Some(resolved_code) = resolve_symlink_target_path(&target_str, root_children, &up_dirs_str, depth) {
                return Some(quote! {
                    if !self.#name().as_path().exists() {
                        let relative_target = #resolved_code;

                        #[cfg(unix)]
                        if let Err(e) = std::os::unix::fs::symlink(&relative_target, self.#name().as_path()) {
                            errors.push(tree_type::BuildError::File(
                                self.#name().as_path().to_path_buf(),
                                Box::new(e)
                            ));
                        }
                        #[cfg(windows)]
                        {
                            let result = std::os::windows::fs::symlink_file(&relative_target, self.#name().as_path());
                            if let Err(e) = result {
                                errors.push(tree_type::BuildError::File(
                                    self.#name().as_path().to_path_buf(),
                                    Box::new(e)
                                ));
                            }
                        }
                    }
                });
            }
            // Fallback to original behavior for paths that can't be resolved
            return Some(quote! {
                if !self.#name().as_path().exists() {
                    let target_str = #target_str;

                    let relative_target = if let Some(path_without_slash) = target_str.strip_prefix('/') {
                        // Absolute path (like "/config/main") - convert to relative
                        let up_dirs = #up_dirs_str;
                        format!("{}{}", up_dirs, path_without_slash)
                    } else if target_str.contains('.') {
                        // File path (like "config/config.toml") - needs relative path calculation
                        let up_dirs = #up_dirs_str;
                        format!("{}{}", up_dirs, target_str)
                    } else {
                        // Identity path - use as-is
                        let up_dirs = #up_dirs_str;
                        format!("{}{}", up_dirs, target_str)
                    };

                    #[cfg(unix)]
                    if let Err(e) = std::os::unix::fs::symlink(&relative_target, self.#name().as_path()) {
                        errors.push(tree_type::BuildError::File(
                            self.#name().as_path().to_path_buf(),
                            Box::new(e)
                        ));
                    }
                    #[cfg(windows)]
                    {
                        let result = std::os::windows::fs::symlink_file(&relative_target, self.#name().as_path());
                        if let Err(e) = result {
                            errors.push(tree_type::BuildError::File(
                                self.#name().as_path().to_path_buf(),
                                Box::new(e)
                            ));
                        }
                    }
                }
            });
        }

        match child {
            Child::Directory { .. } => {
                // Recursively call setup() on child directories (matches legacy behavior)
                Some(quote! {
                    #[expect(deprecated)]
                    if let Err(child_errors) = self.#name().setup() {
                        errors.extend(child_errors);
                    }
                })
            }
            Child::File { attributes, .. } => {
                // Find default attribute if present
                let has_default = attributes.iter().any(|attr| matches!(attr, Attribute::Default(_)));

                if has_default {
                    Some(quote! {
                        if let Err(e) = self.#name().create_default::<std::io::Error>() {
                            errors.push(tree_type::BuildError::File(
                                self.#name().as_path().to_path_buf(),
                                Box::new(e)
                            ));
                        }
                    })
                } else {
                    None
                }
            }
            Child::DynamicId { .. } => None
        }
    });

    quote! {
        #[deprecated(since = "0.2.0", note = "Use `sync()` instead. This method will be removed in v0.6.0")]
        #[expect(deprecated)]
        pub fn setup(&self) -> std::result::Result<Vec<::tree_type::BuildError>, Vec<::tree_type::BuildError>> {
            let mut errors = Vec::new();

            if !self.path.exists() {
                let create_result = ::tree_type::fs::create_dir_all(&self.path);

                if let Err(e) = create_result {
                    errors.push(tree_type::BuildError::Directory(
                        self.path.clone(),
                        e
                    ));
                    return Err(errors);
                }
            }

            #(#setups)*

            if errors.is_empty() {
                Ok(Vec::new())
            } else {
                Err(errors)
            }
        }
    }
}

fn generate_ensure_method(_children: &[Child]) -> proc_macro2::TokenStream {
    quote! {
        #[deprecated(since = "0.2.0", note = "Use `sync()` instead. This method will be removed in v0.6.0")]
        #[expect(deprecated)]
        pub fn ensure(&self) -> std::result::Result<::tree_type::ValidationReport, Vec<::tree_type::BuildError>> {
            self.setup()?;
            Ok(self.validate())
        }
    }
}

fn generate_sync_method(_children: &[Child]) -> proc_macro2::TokenStream {
    quote! {
        /// Synchronizes the directory structure based on macro attributes.
        ///
        /// This method provides a unified interface for structure management by
        /// delegating to the existing setup() and validate() methods.
        ///
        /// Returns a validation report with any issues found.
        #[expect(deprecated)]
        pub fn sync(&self) -> std::result::Result<::tree_type::ValidationReport, Vec<::tree_type::BuildError>> {
            self.setup()?;
            Ok(self.validate())
        }
    }
}

/// Generates a `std::fmt::Display` implementation for a generated type.
///
/// The Display implementation outputs the path as a clean string using `Path::display()`,
/// matching the behavior of `std::path::Path` for consistent user experience.
fn generate_display_impl(name: &syn::Ident) -> proc_macro2::TokenStream {
    quote! {
        impl std::fmt::Display for #name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.path.display())
            }
        }
    }
}

/// Generates a `std::fmt::Debug` implementation for a generated type.
///
/// The Debug implementation outputs the type name followed by the path in parentheses,
/// providing type information for debugging while showing the underlying path.
fn generate_debug_impl(name: &syn::Ident) -> proc_macro2::TokenStream {
    quote! {
        impl std::fmt::Debug for #name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}({})", stringify!(#name), self.path.display())
            }
        }
    }
}

fn generate_dynamic_file_struct(
    name: &Ident,
    attributes: &[Attribute],
    parent_type: Option<&Ident>,
    id_name: &Ident,
    id_type: &syn::Type,
) -> proc_macro2::TokenStream {
    // Find default attribute if present
    let default_method = attributes.iter().find_map(|attr| {
        if let Attribute::Default(val) = attr {
            Some(generate_create_default_method(val))
        } else {
            None
        }
    });

    let parent_method = generate_parent_method(parent_type);

    let serde_derives = get_serde_derives();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    // Generate ID getter method
    let id_getter = quote! {
        pub fn #id_name(&self) -> &#id_type {
            &self.id
        }
    };

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
            id: #id_type,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>, id: #id_type) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf, id })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericFile {
                ::tree_type::GenericFile::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn read(&self) -> std::io::Result<Vec<u8>> {
                ::tree_type::fs::read(&self.path)
            }

            pub fn read_to_string(&self) -> std::io::Result<String> {
                ::tree_type::fs::read_to_string(&self.path)
            }

            pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
                if let Some(parent) = self.path.parent() {
                    if !parent.exists() {
                        ::tree_type::fs::create_dir_all(parent)?;
                    }
                }
                ::tree_type::fs::write(&self.path, contents)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_file(&self.path)
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.path)
            }

            /// Returns the final component of the path as a String.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.path.file_name()
                    .expect("validated in new")
                    .to_string_lossy()
                    .to_string()
            }

            /// Set file permissions to 0o600 (read/write for owner only).
            ///
            /// This method is only available on Unix systems.
            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            pub fn from_generic(file: ::tree_type::GenericFile, id: #id_type) -> Self {
                Self { path: file.as_path().to_path_buf(), id }
            }

            #id_getter

            #default_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericFile {
            fn from(file: #name) -> Self {
                Self::new(file.path).expect("Path validation already performed")
            }
        }
    }
}

fn generate_dynamic_file_struct_with_dynamic_parent(
    name: &Ident,
    attributes: &[Attribute],
    parent_type: &Ident,
    id_name: &Ident,
    id_type: &syn::Type,
    parent_id_type: &syn::Type,
    parent_is_nested: bool,
) -> proc_macro2::TokenStream {
    // Find default attribute if present
    let default_method = attributes.iter().find_map(|attr| {
        if let Attribute::Default(val) = attr {
            Some(generate_create_default_method(val))
        } else {
            None
        }
    });

    let serde_derives = get_serde_derives();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    // Generate ID getter method
    let id_getter = quote! {
        pub fn #id_name(&self) -> &#id_type {
            &self.id
        }
    };

    // Generate parent method that reconstructs the parent with its ID
    let parent_method = if parent_is_nested {
        generate_dynamic_file_with_nested_parent_struct_with_dynamic_parent(parent_type)
    } else {
        generate_dynamic_file_with_non_nested_parent_struct_with_dynamic_parent(parent_type)
    };

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
            id: #id_type,
            parent_id: #parent_id_type,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>, id: #id_type, parent_id: #parent_id_type) -> std::io::Result<Self> {
                let path_buf = path.into();
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf, id, parent_id })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericFile {
                ::tree_type::GenericFile::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn read(&self) -> std::io::Result<Vec<u8>> {
                ::tree_type::fs::read(&self.path)
            }

            pub fn read_to_string(&self) -> std::io::Result<String> {
                ::tree_type::fs::read_to_string(&self.path)
            }

            pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
                if let Some(parent) = self.path.parent() {
                    if !parent.exists() {
                        ::tree_type::fs::create_dir_all(parent)?;
                    }
                }
                ::tree_type::fs::write(&self.path, contents)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_file(&self.path)
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.path)
            }

            /// Returns the final component of the path as a String.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.path.file_name()
                    .expect("validated in new")
                    .to_string_lossy()
                    .to_string()
            }

            /// Set file permissions to 0o600 (read/write for owner only).
            ///
            /// This method is only available on Unix systems.
            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            pub fn from_generic(file: ::tree_type::GenericFile, id: #id_type, parent_id: #parent_id_type) -> Self {
                Self { path: file.as_path().to_path_buf(), id, parent_id }
            }

            #id_getter

            #default_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericFile {
            fn from(file: #name) -> Self {
                Self::new(file.path).expect("Path validation already performed")
            }
        }
    }
}

fn generate_dynamic_file_with_non_nested_parent_struct_with_dynamic_parent(
    parent_type: &Ident,
) -> proc_macro2::TokenStream {
    // Parent is not nested, needs 2 parameters
    quote! {
        /// Get the parent directory with type-safe return type.
        pub fn parent(&self) -> #parent_type {
            let parent_path = self.path.parent().expect("Path should have a parent");
            #parent_type::new(parent_path, self.parent_id.clone()).expect("Path validation already performed")
        }
    }
}

fn generate_dynamic_file_with_nested_parent_struct_with_dynamic_parent(
    parent_type: &Ident,
) -> proc_macro2::TokenStream {
    // Parent is nested inside another dynamic ID, needs 3 parameters
    quote! {
        /// Get the parent directory with type-safe return type.
        pub fn parent(&self) -> #parent_type {
            let parent_path = self.path.parent().expect("Path should have a parent");

            // Extract grandparent ID from path for nested dynamic IDs
            // Path structure: .../grandparent_id/parent_id/file
            let grandparent_path = parent_path.parent().expect("Parent should have a grandparent");
            let grandparent_id = grandparent_path.file_name()
                .expect("Grandparent path should have a filename")
                .to_string_lossy()
                .to_string();

            #parent_type::new(parent_path, self.parent_id.clone(), grandparent_id).expect("Path validation already performed")
        }
    }
}

fn generate_dynamic_dir_struct(
    name: &Ident,
    children: &[Child],
    depth: usize,
    root_children: &[Child],
    parent_type: Option<&Ident>,
    id_name: &Ident,
    id_type: &syn::Type,
) -> proc_macro2::TokenStream {
    let nav_methods = children
        .iter()
        .map(|child| generate_nav_method_for_dynamic_id_parent(name, child, id_name));

    let children_method = generate_children_method(children, false, true);
    let parent_method = generate_parent_method(parent_type);

    let validate_impl = generate_validate_method_with_parent_info(children, false, true);
    let setup_impl = generate_setup_method(children, depth, root_children);
    let ensure_impl = generate_ensure_method(children);
    let sync_impl = generate_sync_method(children);

    let serde_derives = get_serde_derives();
    let walk_fns = build_walk_fns();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    // Generate ID getter method
    let id_getter = quote! {
        pub fn #id_name(&self) -> &#id_type {
            &self.id
        }
    };

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
            id: #id_type,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>, id: #id_type) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf, id })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericDir {
                ::tree_type::GenericDir::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn create(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir(&self.path)
            }

            pub fn create_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir_all(&self.path)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir(&self.path)
            }

            pub fn remove_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir_all(&self.path)
            }

            pub fn read_dir(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<::tree_type::GenericPath>>> {
                ::tree_type::fs::read_dir(&self.path)
                    .map(|read_dir| read_dir.map(|result| result.and_then(::tree_type::GenericPath::try_from)))
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.path)
            }

            /// Set directory permissions to 0o700 (read/write/execute for owner only).
            ///
            /// This method is only available on Unix systems.
            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            #walk_fns

            #validate_impl
            #setup_impl
            #ensure_impl
            #sync_impl

            /// Returns the final component of the path as a String.
            /// For root paths like "/", returns an empty string.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.path.file_name()
                    .map(|name| name.to_string_lossy().to_string())
                    .unwrap_or_default()
            }

            pub fn from_generic(dir: ::tree_type::GenericDir, id: #id_type) -> Self {
                Self { path: dir.as_path().to_path_buf(), id }
            }

            #id_getter

            #(#nav_methods)*

            #children_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericDir {
            fn from(dir: #name) -> Self {
                Self::new(dir.path).expect("Path validation already performed")
            }
        }
    }
}
#[allow(clippy::too_many_arguments)]
fn generate_dynamic_dir_struct_with_dynamic_parent(
    name: &Ident,
    children: &[Child],
    depth: usize,
    root_children: &[Child],
    parent_type: &Ident,
    id_name: &Ident,
    id_type: &syn::Type,
    parent_id_type: &syn::Type,
    parent_is_nested: bool,
) -> proc_macro2::TokenStream {
    let nav_methods = children
        .iter()
        .map(|child| generate_nav_method_for_dynamic_id_parent(name, child, id_name));

    let children_method = generate_children_method(children, false, true);

    let validate_impl = generate_validate_method_with_parent_info(children, false, true);
    let setup_impl = generate_setup_method(children, depth, root_children);
    let ensure_impl = generate_ensure_method(children);
    let sync_impl = generate_sync_method(children);

    let serde_derives = get_serde_derives();
    let walk_fns = build_walk_fns();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    let id_getter = generate_id_getter_method(id_name, id_type);

    // Generate parent method that reconstructs the parent with its ID
    let parent_method =
        generate_dynamic_dir_parent_struct_with_dynamic_parent(parent_type, parent_is_nested);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name {
            path: std::path::PathBuf,
            id: #id_type,
            parent_id: #parent_id_type,
        }

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>, id: #id_type, parent_id: #parent_id_type) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self { path: path_buf, id, parent_id })
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.path
            }

            pub fn exists(&self) -> bool {
                self.path.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericDir {
                ::tree_type::GenericDir::new(self.path.clone()).expect("Path validation already performed")
            }

            pub fn create(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir(&self.path)
            }

            pub fn create_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir_all(&self.path)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir(&self.path)
            }

            pub fn remove_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir_all(&self.path)
            }

            pub fn read_dir(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<::tree_type::GenericPath>>> {
                ::tree_type::fs::read_dir(&self.path)
                    .map(|read_dir| read_dir.map(|result| result.and_then(::tree_type::GenericPath::try_from)))
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.path)
            }

            /// Set directory permissions to 0o700 (read/write/execute for owner only).
            ///
            /// This method is only available on Unix systems.
            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            #walk_fns

            #validate_impl
            #setup_impl
            #ensure_impl
            #sync_impl

            /// Returns the final component of the path as a String.
            /// For root paths like "/", returns an empty string.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.path.file_name()
                    .map(|name| name.to_string_lossy().to_string())
                    .unwrap_or_default()
            }

            pub fn from_generic(dir: ::tree_type::GenericDir, id: #id_type, parent_id: #parent_id_type) -> Self {
                Self { path: dir.as_path().to_path_buf(), id, parent_id }
            }

            #id_getter

            #(#nav_methods)*

            #children_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.path
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericDir {
            fn from(dir: #name) -> Self {
                Self::new(dir.path).expect("Path validation already performed")
            }
        }
    }
}

fn generate_dynamic_dir_parent_struct_with_dynamic_parent(
    parent_type: &Ident,
    parent_is_nested: bool,
) -> proc_macro2::TokenStream {
    if parent_is_nested {
        generate_dynamic_dir_with_nested_parent_struct_with_dynamic_parent(parent_type)
    } else {
        generate_dynamic_dir_with_non_nested_parent_struct_with_dynamic_parent(parent_type)
    }
}

fn generate_id_getter_method(id_name: &Ident, id_type: &syn::Type) -> proc_macro2::TokenStream {
    quote! {
        pub fn #id_name(&self) -> &#id_type {
            &self.id
        }
    }
}

fn generate_dynamic_dir_with_non_nested_parent_struct_with_dynamic_parent(
    parent_type: &Ident,
) -> proc_macro2::TokenStream {
    // Parent is not nested, needs 2 parameters
    quote! {
        /// Get the parent directory with type-safe return type.
        pub fn parent(&self) -> #parent_type {
            let parent_path = self.path.parent().expect("Path should have a parent");
            #parent_type::new(parent_path, self.parent_id.clone()).expect("Path validation already performed")
        }
    }
}

fn generate_dynamic_dir_with_nested_parent_struct_with_dynamic_parent(
    parent_type: &Ident,
) -> proc_macro2::TokenStream {
    // Parent is nested inside another dynamic ID, needs 3 parameters
    quote! {
        /// Get the parent directory with type-safe return type.
        pub fn parent(&self) -> #parent_type {
            let parent_path = self.path.parent().expect("Path should have a parent");

            // Extract grandparent ID from path for nested dynamic IDs
            // Path structure: .../grandparent_id/parent_id/child_id
            let grandparent_path = parent_path.parent().expect("Parent should have a grandparent");
            let grandparent_id = grandparent_path.file_name()
                .expect("Grandparent path should have a filename")
                .to_string_lossy()
                .to_string();

            #parent_type::new(parent_path, self.parent_id.clone(), grandparent_id).expect("Path validation already performed")
        }
    }
}

// New generic approach for generating child structs with path-based dynamic ID collection
#[allow(dead_code)]
fn generate_child_structs_with_path(
    parent_name: &Ident,
    children: &[Child],
    structs: &mut Vec<proc_macro2::TokenStream>,
    root_children: &[Child],
) {
    for child in children {
        match child {
            Child::File {
                name,
                custom_type,
                attributes,
                ..
            } => {
                let struct_name = get_child_type_name(parent_name, name, custom_type.as_ref());

                // Collect dynamic ancestors for this file type
                let mut path = Vec::new();
                let mut result = None;
                collect_dynamic_ancestors(
                    root_children,
                    &struct_name.to_string(),
                    &mut path,
                    &mut result,
                );
                let ancestors = result.unwrap_or_default();

                // Generate using generic approach
                structs.push(generate_file_struct_generic(
                    &struct_name,
                    attributes,
                    parent_name,
                    &ancestors,
                ));
            }
            Child::Directory {
                name,
                custom_type,
                children,
                ..
            } => {
                let struct_name = get_child_type_name(parent_name, name, custom_type.as_ref());

                // For now, just generate a basic directory struct
                structs.push(quote! {
                    #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
                    pub struct #struct_name {
                        path: std::path::PathBuf,
                    }

                    impl #struct_name {
                        pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
                            Ok(Self { path: path.into() })
                        }
                    }
                });

                // Recurse into children
                generate_child_structs_with_path(&struct_name, children, structs, root_children);
            }
            Child::DynamicId {
                child_type,
                children,
                ..
            } => {
                // Recurse into dynamic ID children
                generate_child_structs_with_path(child_type, children, structs, root_children);
            }
        }
    }
}

// Generic file struct generation using collected dynamic ancestor info
fn generate_file_struct_generic(
    struct_name: &Ident,
    #[expect(unused)] attributes: &[Attribute],
    parent_name: &Ident,
    ancestors: &[DynamicIdInfo],
) -> proc_macro2::TokenStream {
    #[expect(unused)]
    let parent_name_lower = parent_name.to_string().to_lowercase();

    // Generate constructor parameters based on ancestor depth
    let constructor_params = match ancestors.len() {
        0 => quote! { path: impl Into<std::path::PathBuf>, parent_id: impl std::fmt::Display },
        1 => quote! {
            path: impl Into<std::path::PathBuf>,
            parent_id: impl std::fmt::Display,
            grandparent_id: impl std::fmt::Display
        },
        _ => {
            let mut params = vec![
                quote! { path: impl Into<std::path::PathBuf> },
                quote! { parent_id: impl std::fmt::Display },
            ];
            for i in 0..ancestors.len() {
                let param_name = format_ident!("ancestor_{}", i);
                params.push(quote! { #param_name: impl std::fmt::Display });
            }
            quote! { #(#params),* }
        }
    };

    // Generate constructor body
    let constructor_body = quote! {
        let path = path.into();
        Ok(Self { path })
    };

    // Generate navigation method to parent
    let parent_method = generate_nav_method_generic(parent_name, ancestors);

    quote! {
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #struct_name {
            path: std::path::PathBuf,
        }

        impl #struct_name {
            pub fn new(#constructor_params) -> std::io::Result<Self> {
                #constructor_body
            }

            #parent_method
        }
    }
}

// Generic navigation method generation
fn generate_nav_method_generic(
    parent_name: &Ident,
    ancestors: &[DynamicIdInfo],
) -> proc_macro2::TokenStream {
    let parent_name_lower = parent_name.to_string().to_lowercase();
    let method_name = format_ident!("{}", parent_name_lower);

    // Generate constructor call based on ancestor depth
    let constructor_call = match ancestors.len() {
        0 => quote! { #parent_name::new(parent_path) },
        1 => quote! { #parent_name::new(parent_path, self.parent_id) },
        _ => {
            let mut args = vec![quote! { parent_path }];
            for i in 0..ancestors.len() {
                let field_name = format_ident!("ancestor_{}", i);
                args.push(quote! { self.#field_name });
            }
            quote! { #parent_name::new(#(#args),*) }
        }
    };

    quote! {
        pub fn #method_name(&self) -> std::io::Result<#parent_name> {
            let parent_path = self.path.parent()
                .ok_or_else(|| std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "No parent directory"
                ))?;
            #constructor_call
        }
    }
}
#[allow(dead_code)]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_collect_dynamic_ancestors() {
        // Test with simple case - validates the core collection logic works
        let mut path = Vec::new();
        let mut result = None;

        // Test with empty children - should return None
        collect_dynamic_ancestors(&[], "NonExistent", &mut path, &mut result);
        assert!(result.is_none());

        // Test validates that the function compiles and runs without panicking
        // More comprehensive tests would require building actual Child structures
    }

    #[test]
    fn test_generic_vs_hardcoded_output_comparison() {
        // This test validates that the generic system produces equivalent output
        // to the hardcoded system for the same input structures

        let struct_name = syn::Ident::new("TestFile", proc_macro2::Span::call_site());
        let parent_name = syn::Ident::new("TestParent", proc_macro2::Span::call_site());

        // Test case 1: No ancestors (2 parameters)
        let ancestors_empty = vec![];
        let generic_output =
            generate_file_struct_generic(&struct_name, &[], &parent_name, &ancestors_empty);
        let generic_str = generic_output.to_string();

        // Debug: Print the actual generated output
        println!("Generated output: {}", generic_str);

        // Verify generic system generates expected structure
        assert!(generic_str.contains("pub struct TestFile"));
        assert!(generic_str.contains("path")); // More flexible check
        assert!(generic_str.contains("pub fn new"));
        assert!(generic_str.contains("parent_id"));

        // Test case 2: One ancestor (3 parameters)
        let ancestors_one = vec![DynamicIdInfo {
            id_type: quote! { String },
        }];
        let generic_output_one =
            generate_file_struct_generic(&struct_name, &[], &parent_name, &ancestors_one);
        let generic_str_one = generic_output_one.to_string();

        // Verify generic system handles 1 ancestor correctly
        assert!(generic_str_one.contains("grandparent_id"));

        // Test case 3: Two ancestors (4 parameters)
        let ancestors_two = vec![
            DynamicIdInfo {
                id_type: quote! { u32 },
            },
            DynamicIdInfo {
                id_type: quote! { Uuid },
            },
        ];
        let generic_output_two =
            generate_file_struct_generic(&struct_name, &[], &parent_name, &ancestors_two);
        let generic_str_two = generic_output_two.to_string();

        // Verify generic system handles 2+ ancestors correctly
        assert!(generic_str_two.contains("ancestor_0"));
        assert!(generic_str_two.contains("ancestor_1"));

        // This validates that the generic system can handle arbitrary nesting depth
        // which the hardcoded system cannot (it's limited to 3 levels)
    }
}