rs-hack 0.5.2

AST-aware Rust refactoring tool for AI agents - transform, rename, inspect & more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
use anyhow::{Context, Result};
use proc_macro2::{LineColumn, Span};
use syn::{
    parse_str, File, Item, ItemEnum, ItemStruct,
    Fields, Field, spanned::Spanned, Arm, ExprMatch, ExprStruct,
    visit_mut::VisitMut, Expr,
};
use quote::ToTokens;

use crate::operations::*;
use crate::path_resolver::PathResolver;
use prettyplease;

pub struct RustEditor {
    content: String,
    syntax_tree: File,
    line_offsets: Vec<usize>, // Byte offset for each line start
}

impl RustEditor {
    pub fn new(content: &str) -> Result<Self> {
        let syntax_tree: File = syn::parse_str(content)
            .context("Failed to parse Rust code")?;

        let line_offsets = Self::compute_line_offsets(content);

        Ok(Self {
            content: content.to_string(),
            syntax_tree,
            line_offsets,
        })
    }

    /// Format a field without extra spaces (e.g., "pub name: String" not "pub name : String")
    fn format_field(field: &Field) -> String {
        let mut result = String::new();

        // Add visibility
        if let syn::Visibility::Public(_) = field.vis {
            result.push_str("pub ");
        }

        // Add field name
        if let Some(ident) = &field.ident {
            result.push_str(&ident.to_string());
        }

        // Add colon and type (no space before colon)
        result.push_str(": ");

        // Format type without extra spaces
        let type_str = field.ty.to_token_stream().to_string();
        let type_str = type_str.replace(" < ", "<").replace(" >", ">");
        result.push_str(&type_str);

        result
    }
    
    fn compute_line_offsets(content: &str) -> Vec<usize> {
        let mut offsets = vec![0];
        for (i, ch) in content.char_indices() {
            if ch == '\n' {
                offsets.push(i + 1);
            }
        }
        offsets
    }

    /// Find similar field names using Levenshtein distance for fuzzy matching
    fn find_similar_fields(target: &str, available: &[String]) -> Vec<String> {
        use strsim::levenshtein;

        let mut scored: Vec<_> = available.iter()
            .map(|field| (field, levenshtein(target, field)))
            .filter(|(_, distance)| *distance <= 3)  // Max 3 character difference
            .collect();

        scored.sort_by_key(|(_, distance)| *distance);
        scored.into_iter()
            .take(3)  // Top 3 suggestions
            .map(|(field, _)| field.to_string())
            .collect()
    }

    pub fn apply_operation(&mut self, op: &Operation) -> Result<ModificationResult> {
        match op {
            Operation::AddStructField(op) => self.add_struct_field(op),
            Operation::UpdateStructField(op) => self.update_struct_field(op),
            Operation::RemoveStructField(op) => self.remove_struct_field(op),
            Operation::AddStructLiteralField(op) => self.add_struct_literal_field(op),
            Operation::AddEnumVariant(op) => self.add_enum_variant(op),
            Operation::UpdateEnumVariant(op) => self.update_enum_variant(op),
            Operation::RemoveEnumVariant(op) => self.remove_enum_variant(op),
            Operation::AddMatchArm(op) => self.add_match_arm(op),
            Operation::UpdateMatchArm(op) => self.update_match_arm(op),
            Operation::RemoveMatchArm(op) => self.remove_match_arm(op),
            Operation::AddImplMethod(op) => self.add_impl_method(op),
            Operation::AddUseStatement(op) => self.add_use_statement(op),
            Operation::AddDerive(op) => self.add_derive(op),
            Operation::Transform(op) => self.transform(op),
            Operation::RenameEnumVariant(op) => self.rename_enum_variant(op),
            Operation::RenameFunction(op) => self.rename_function(op),
            Operation::AddDocComment(op) => self.add_doc_comment_surgical(
                &op.target_type,
                &op.name,
                &op.doc_comment,
                &op.style,
            ),
            Operation::UpdateDocComment(op) => self.update_doc_comment_surgical(
                &op.target_type,
                &op.name,
                &op.doc_comment,
                &DocCommentStyle::Line, // Default to line style for updates
            ),
            Operation::RemoveDocComment(op) => self.remove_doc_comment_surgical(
                &op.target_type,
                &op.name,
            ),
        }
    }
    
    pub(crate) fn add_struct_field(&mut self, op: &AddStructFieldOp) -> Result<ModificationResult> {
        let mut modified_nodes = Vec::new();

        // Check if this is an enum variant struct literal (contains ::)
        let is_enum_variant = op.struct_name.contains("::");

        // For enum variant literals, automatically operate on literals only
        // (since we can't modify the enum variant definition without the full enum context)
        if is_enum_variant {
            // Parse the field_def to extract field name and value/type
            // field_def can be:
            // - "layer: None" (with explicit value)
            // - "layer: Option<Layer>" (with type, needs literal_default)
            // - "layer" (just name, needs literal_default)

            let final_field_def = if let Some(literal_default) = &op.literal_default {
                // literal_default provided - use it
                let field_name = op.field_def.split(':')
                    .next()
                    .map(|s| s.trim().to_string())
                    .context("Failed to extract field name")?;
                format!("{}: {}", field_name, literal_default)
            } else if op.field_def.contains(':') {
                // field_def already contains a value (e.g., "layer: None")
                op.field_def.clone()
            } else {
                anyhow::bail!(
                    "For enum variant literals, field definition must include a value.\n\
                     Either use: --field \"layer: None\" or --field \"layer\" --literal-default \"None\""
                );
            };

            // Create the AddStructLiteralFieldOp
            let literal_op = AddStructLiteralFieldOp {
                struct_name: op.struct_name.clone(),
                field_def: final_field_def,
                position: op.position.clone(),
                struct_path: None,
            };

            // Update all struct literals
            let literal_result = self.add_struct_literal_field(&literal_op)
                .context("Failed to update struct literals")?;

            return Ok(literal_result);
        }

        // Find the struct and clone it to avoid borrowing issues
        let item_struct = self.syntax_tree.items.iter()
            .find_map(|item| {
                if let Item::Struct(s) = item {
                    if s.ident == op.struct_name {
                        return Some(s.clone());
                    }
                }
                None
            })
            .ok_or_else(|| anyhow::anyhow!("Struct '{}' not found", op.struct_name))?;

        // Check if the struct matches the where filter (if specified)
        if let Some(ref where_filter) = op.where_filter {
            if !self.matches_where_filter(&item_struct.attrs, where_filter)? {
                // Struct doesn't match filter - skip without error
                return Ok(ModificationResult {
                    changed: false,
                    modified_nodes: vec![],
                });
            }
        }

        // If literal_default is NOT provided, only modify the definition
        if op.literal_default.is_none() {
            // Create backup of original struct before modification
            let backup_node = BackupNode {
                node_type: "struct".to_string(),
                identifier: op.struct_name.clone(),
                original_content: self.unparse_item(&Item::Struct(item_struct.clone())),
                location: self.span_to_location(item_struct.span()),
            };

            // Insert the field into the struct definition
            let modified = self.insert_struct_field(&item_struct, op)
                .context("Failed to add field to struct definition")?;

            if !modified {
                return Ok(ModificationResult {
                    changed: false,
                    modified_nodes: vec![],
                });
            }

            return Ok(ModificationResult {
                changed: true,
                modified_nodes: vec![backup_node],
            });
        }

        // If literal_default IS provided:
        // 1. Try to add to definition (idempotent - silently skips if field exists OR if field_def is incomplete)
        // 2. Always update literals
        let literal_default = op.literal_default.as_ref().unwrap();

        // Check if field_def contains a type (has ':')
        // If it doesn't, skip definition modification (literals-only mode)
        let has_type = op.field_def.contains(':');

        let mut def_modified = false;
        if has_type {
            // Create backup before any modifications
            let backup_node = BackupNode {
                node_type: "struct".to_string(),
                identifier: op.struct_name.clone(),
                original_content: self.unparse_item(&Item::Struct(item_struct.clone())),
                location: self.span_to_location(item_struct.span()),
            };

            // Try to insert field into definition (idempotent - returns false if already exists)
            def_modified = self.insert_struct_field(&item_struct, op)
                .context("Failed to add field to struct definition")?;

            if def_modified {
                modified_nodes.push(backup_node);
                // Re-parse the content to update syntax_tree with the struct field changes
                self.syntax_tree = syn::parse_str(&self.content)
                    .context("Failed to re-parse content after adding struct field")?;
                self.line_offsets = Self::compute_line_offsets(&self.content);
            }
        }

        // Always update literals when literal_default is provided
        // Extract field name from field_def (e.g., "return_type: Option<Type>" -> "return_type" or just "return_type")
        let field_name = op.field_def.split(':')
            .next()
            .map(|s| s.trim().to_string())
            .context("Failed to extract field name from field definition")?;

        // Create the AddStructLiteralFieldOp
        let literal_op = AddStructLiteralFieldOp {
            struct_name: op.struct_name.clone(),
            field_def: format!("{}: {}", field_name, literal_default),
            position: op.position.clone(),
            struct_path: None,  // Path resolution not available from struct field operations
        };

        // Update all struct literals
        let literal_result = self.add_struct_literal_field(&literal_op)
            .context("Failed to update struct literals")?;
        modified_nodes.extend(literal_result.modified_nodes);

        Ok(ModificationResult {
            changed: true,
            modified_nodes,
        })
    }
    
    fn insert_struct_field(&mut self, item_struct: &ItemStruct, op: &AddStructFieldOp) -> Result<bool> {
        if let Fields::Named(ref fields) = item_struct.fields {
            // Parse the new field
            let field_code = format!("struct Dummy {{ {} }}", op.field_def);
            let dummy: ItemStruct = parse_str(&field_code)
                .context("Failed to parse field definition")?;

            let new_field = if let Fields::Named(ref nf) = dummy.fields {
                nf.named.first()
                    .context("No field found in definition")?
                    .clone()
            } else {
                anyhow::bail!("Expected named field");
            };

            // Check if field already exists
            let new_field_name = new_field.ident.as_ref()
                .map(|i| i.to_string())
                .context("Field must have a name")?;

            if fields.named.iter().any(|f| {
                f.ident.as_ref().map(|i| i.to_string()) == Some(new_field_name.clone())
            }) {
                // Field already exists, skip adding
                return Ok(false);
            }
            
            // Determine insertion point
            let insert_pos = match &op.position {
                InsertPosition::First => {
                    if let Some(first_field) = fields.named.first() {
                        self.span_to_byte_offset(first_field.span().start())
                    } else {
                        // Empty struct, insert after the opening brace
                        let brace_pos = self.span_to_byte_offset(fields.brace_token.span.join().start());
                        brace_pos + 1
                    }
                }
                InsertPosition::Last => {
                    if let Some(last_field) = fields.named.last() {
                        let end = self.span_to_byte_offset(last_field.span().end());
                        // Find the comma or end
                        self.find_after_field_end(end)
                    } else {
                        // Empty struct
                        let brace_pos = self.span_to_byte_offset(fields.brace_token.span.join().start());
                        brace_pos + 1
                    }
                }
                InsertPosition::After(name) => {
                    let field = fields.named.iter()
                        .find(|f| f.ident.as_ref().map(|i| i.to_string()) == Some(name.clone()))
                        .with_context(|| format!("Field '{}' not found", name))?;
                    let end = self.span_to_byte_offset(field.span().end());
                    self.find_after_field_end(end)
                }
                InsertPosition::Before(name) => {
                    let field = fields.named.iter()
                        .find(|f| f.ident.as_ref().map(|i| i.to_string()) == Some(name.clone()))
                        .with_context(|| format!("Field '{}' not found", name))?;
                    self.span_to_byte_offset(field.span().start())
                }
            };
            
            // Format the new field
            let indent = self.get_indentation(insert_pos);
            let field_str = Self::format_field(&new_field);
            let insert_text = if matches!(op.position, InsertPosition::First) {
                format!("\n{}{},", indent, field_str)
            } else {
                format!("\n{}{},", indent, field_str)
            };

            self.content.insert_str(insert_pos, &insert_text);
            return Ok(true);
        }
        
        anyhow::bail!("Struct '{}' does not have named fields", op.struct_name)
    }

    pub(crate) fn update_struct_field(&mut self, op: &UpdateStructFieldOp) -> Result<ModificationResult> {
        // Check if this is an enum variant struct literal (contains ::)
        let is_enum_variant = op.struct_name.contains("::");

        // For enum variant literals, we can't update the enum variant definition
        // (would need full enum context), so bail with helpful message
        if is_enum_variant {
            anyhow::bail!(
                "Cannot update field in enum variant definition '{}'.\n\
                 To update fields in enum variant struct literals, use the transform command:\n\
                 rs-hack transform --node-type struct-literal --name {} --action replace --with <new_pattern> --paths ... --apply",
                op.struct_name, op.struct_name
            );
        }

        // Find the struct and clone it to avoid borrowing issues
        let item_struct = self.syntax_tree.items.iter()
            .find_map(|item| {
                if let Item::Struct(s) = item {
                    if s.ident == op.struct_name {
                        return Some(s.clone());
                    }
                }
                None
            })
            .ok_or_else(|| anyhow::anyhow!("Struct '{}' not found", op.struct_name))?;

        // Check if the struct matches the where filter (if specified)
        if let Some(ref where_filter) = op.where_filter {
            if !self.matches_where_filter(&item_struct.attrs, where_filter)? {
                // Struct doesn't match filter - skip without error
                return Ok(ModificationResult {
                    changed: false,
                    modified_nodes: vec![],
                });
            }
        }

        // Create backup of original struct before modification
        let backup_node = BackupNode {
            node_type: "struct".to_string(),
            identifier: op.struct_name.clone(),
            original_content: self.unparse_item(&Item::Struct(item_struct.clone())),
            location: self.span_to_location(item_struct.span()),
        };

        let modified = self.replace_struct_field(&item_struct, op)?;

        Ok(ModificationResult {
            changed: modified,
            modified_nodes: if modified { vec![backup_node] } else { vec![] },
        })
    }

    fn replace_struct_field(&mut self, item_struct: &ItemStruct, op: &UpdateStructFieldOp) -> Result<bool> {
        if let Fields::Named(ref fields) = item_struct.fields {
            // Parse the new field definition to get the field name
            let field_code = format!("struct Dummy {{ {} }}", op.field_def);
            let dummy: ItemStruct = parse_str(&field_code)
                .context("Failed to parse field definition")?;

            let new_field = if let Fields::Named(ref nf) = dummy.fields {
                nf.named.first()
                    .context("No field found in definition")?
                    .clone()
            } else {
                anyhow::bail!("Expected named field");
            };

            // Extract the field name from the parsed field
            let field_name = new_field.ident.as_ref()
                .map(|i| i.to_string())
                .context("Field must have a name")?;

            // Find the existing field
            let existing_field = fields.named.iter()
                .find(|f| f.ident.as_ref().map(|i| i.to_string()) == Some(field_name.clone()))
                .ok_or_else(|| anyhow::anyhow!("Field '{}' not found in struct '{}'", field_name, op.struct_name))?;

            // Get the span of the existing field
            let start = self.span_to_byte_offset(existing_field.span().start());
            let end = self.span_to_byte_offset(existing_field.span().end());

            // Format and replace the field
            let new_field_str = Self::format_field(&new_field);

            // Remove the old field and insert the new one
            self.content.replace_range(start..end, &new_field_str);

            return Ok(true);
        }

        anyhow::bail!("Struct '{}' does not have named fields", op.struct_name)
    }

    pub(crate) fn remove_struct_field(&mut self, op: &RemoveStructFieldOp) -> Result<ModificationResult> {
        let mut modified_nodes = Vec::new();
        let mut changed = false;

        // Check if this is an enum variant struct literal (contains ::)
        let is_enum_variant = op.struct_name.contains("::");

        // For enum variant literals, automatically operate on literals only
        // (since we can't modify the enum variant definition without the full enum context)
        let effective_literal_only = op.literal_only || is_enum_variant;

        // Step 1: Remove from struct definition (unless literal_only is true or it's an enum variant)
        if !effective_literal_only {
            // Find the struct and clone it to avoid borrowing issues
            let item_struct = self.syntax_tree.items.iter()
                .find_map(|item| {
                    if let Item::Struct(s) = item {
                        if s.ident == op.struct_name {
                            return Some(s.clone());
                        }
                    }
                    None
                })
                .ok_or_else(|| anyhow::anyhow!("Struct '{}' not found", op.struct_name))?;

            // Check if the struct matches the where filter (if specified)
            if let Some(ref where_filter) = op.where_filter {
                if !self.matches_where_filter(&item_struct.attrs, where_filter)? {
                    // Struct doesn't match filter - skip without error
                    return Ok(ModificationResult {
                        changed: false,
                        modified_nodes: vec![],
                    });
                }
            }

            // Create backup of original struct before modification
            let backup_node = BackupNode {
                node_type: "struct".to_string(),
                identifier: op.struct_name.clone(),
                original_content: self.unparse_item(&Item::Struct(item_struct.clone())),
                location: self.span_to_location(item_struct.span()),
            };

            if let Fields::Named(ref fields) = item_struct.fields {
                // Find the field to remove
                let field_to_remove = fields.named.iter()
                    .find(|f| f.ident.as_ref().map(|i| i.to_string()) == Some(op.field_name.clone()));

                // If field not found, provide helpful error with suggestions
                if field_to_remove.is_none() {
                    let field_names: Vec<String> = fields.named.iter()
                        .filter_map(|f| f.ident.as_ref().map(|i| i.to_string()))
                        .collect();

                    let suggestions = Self::find_similar_fields(&op.field_name, &field_names);

                    if suggestions.is_empty() {
                        return Err(anyhow::anyhow!(
                            "Field '{}' not found in struct '{}'\n\nAvailable fields: {}",
                            op.field_name,
                            op.struct_name,
                            field_names.join(", ")
                        ));
                    } else {
                        return Err(anyhow::anyhow!(
                            "Field '{}' not found in struct '{}'\n\nDid you mean one of these?\n  - {}\n\nAll available fields: {}",
                            op.field_name,
                            op.struct_name,
                            suggestions.join("\n  - "),
                            field_names.join(", ")
                        ));
                    }
                }

                let field_to_remove = field_to_remove.unwrap();

                // Get the span including the comma
                let start = self.span_to_byte_offset(field_to_remove.span().start());
                let mut end = self.span_to_byte_offset(field_to_remove.span().end());

                // Find and include the comma and any trailing whitespace/newline
                while end < self.content.len() {
                    match self.content.as_bytes()[end] as char {
                        ',' => {
                            end += 1;
                            // Also consume the newline after the comma if present
                            if end < self.content.len() && self.content.as_bytes()[end] == b'\n' {
                                end += 1;
                            }
                            break;
                        }
                        ' ' | '\t' => end += 1,
                        '\n' => {
                            end += 1;
                            break;
                        }
                        _ => break,
                    }
                }

                // Also need to remove leading whitespace/indentation on the same line
                let mut line_start = start;
                while line_start > 0 && self.content.as_bytes()[line_start - 1] != b'\n' {
                    line_start -= 1;
                }

                // Check if there's only whitespace between line_start and start
                let before_field = &self.content[line_start..start];
                if before_field.trim().is_empty() {
                    // Remove the whole line
                    self.content.replace_range(line_start..end, "");
                } else {
                    // Just remove the field and comma
                    self.content.replace_range(start..end, "");
                }

                modified_nodes.push(backup_node);
                changed = true;

                // Re-parse the syntax tree after surgical edit
                self.syntax_tree = syn::parse_str(&self.content)?;
            } else {
                anyhow::bail!("Struct '{}' does not have named fields", op.struct_name)
            }
        }

        // Step 2: Remove from all struct literal expressions using surgical editing
        // Collect backups of struct literals before modification
        let literal_backups = self.collect_struct_literal_backups(&op.struct_name, None);

        // Find all field deletions (surgical approach)
        use syn::visit::Visit;

        struct FieldDeletionFinder<'a> {
            struct_name: String,
            field_name: String,
            deletion_ranges: Vec<(usize, usize)>, // (start_byte, end_byte)
            editor: &'a RustEditor,
        }

        impl<'ast, 'a> Visit<'ast> for FieldDeletionFinder<'a> {
            fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
                // Check if this matches our target
                let matches = if self.struct_name.contains("::") {
                    if self.struct_name.starts_with("*::") {
                        let target_name = &self.struct_name[3..];
                        node.path.segments.last()
                            .map(|seg| seg.ident.to_string() == target_name)
                            .unwrap_or(false)
                    } else {
                        let path_str = node.path.segments.iter()
                            .map(|seg| seg.ident.to_string())
                            .collect::<Vec<_>>()
                            .join("::");
                        path_str == self.struct_name
                    }
                } else {
                    node.path.segments.len() == 1
                        && node.path.segments.last()
                            .map(|seg| seg.ident.to_string())
                            .as_ref() == Some(&self.struct_name)
                };

                if matches {
                    // Find the field to remove
                    let field_idx = node.fields.iter().position(|fv| {
                        if let syn::Member::Named(ident) = &fv.member {
                            ident.to_string() == self.field_name
                        } else {
                            false
                        }
                    });

                    if let Some(idx) = field_idx {
                        let field = &node.fields[idx];
                        let start = self.editor.span_to_byte_offset(field.span().start());
                        let mut end = self.editor.span_to_byte_offset(field.span().end());

                        // Include the trailing comma if present
                        // Look ahead for comma and optional whitespace
                        let content_bytes = self.editor.content.as_bytes();
                        while end < content_bytes.len() {
                            match content_bytes[end] {
                                b',' => {
                                    end += 1;
                                    // Also consume the newline after comma if present
                                    if end < content_bytes.len() && content_bytes[end] == b'\n' {
                                        end += 1;
                                    }
                                    break;
                                }
                                b' ' | b'\t' => {
                                    end += 1;
                                }
                                _ => break,
                            }
                        }

                        // Also include leading whitespace/newline on the same line
                        let mut line_start = start;
                        while line_start > 0 {
                            let ch = content_bytes[line_start - 1];
                            if ch == b'\n' {
                                break;
                            } else if ch == b' ' || ch == b'\t' {
                                line_start -= 1;
                            } else {
                                break;
                            }
                        }

                        self.deletion_ranges.push((line_start, end));
                    }
                }

                syn::visit::visit_expr_struct(self, node);
            }
        }

        let mut finder = FieldDeletionFinder {
            struct_name: op.struct_name.clone(),
            field_name: op.field_name.clone(),
            deletion_ranges: Vec::new(),
            editor: self,
        };

        finder.visit_file(&self.syntax_tree);

        if !finder.deletion_ranges.is_empty() {
            // Sort ranges in reverse order to preserve offsets
            let mut ranges = finder.deletion_ranges;
            ranges.sort_by_key(|(start, _)| std::cmp::Reverse(*start));

            // Perform surgical deletions
            for (start, end) in ranges {
                self.content.drain(start..end);
            }

            // Re-parse to update syntax_tree
            self.syntax_tree = syn::parse_str(&self.content)
                .context("Failed to re-parse after removing struct literal fields")?;
            self.line_offsets = Self::compute_line_offsets(&self.content);

            modified_nodes.extend(literal_backups);
            changed = true;
        }

        Ok(ModificationResult {
            changed,
            modified_nodes,
        })
    }

    pub(crate) fn add_struct_literal_field(&mut self, op: &AddStructLiteralFieldOp) -> Result<ModificationResult> {
        // Parse the field name from field_def (e.g., "return_type: None" -> "return_type")
        let field_name = op.field_def.split(':')
            .next()
            .map(|s| s.trim().to_string())
            .context("Field definition must contain ':'")?;

        // Create a path resolver if a canonical path was provided
        let path_resolver = if let Some(struct_path) = &op.struct_path {
            let mut resolver = PathResolver::new(struct_path)
                .ok_or_else(|| anyhow::anyhow!("Invalid struct path: {}", struct_path))?;

            // Scan the file for use statements to build the alias map
            resolver.scan_file(&self.syntax_tree);
            Some(resolver)
        } else {
            None
        };

        // Collect backups of all struct literal expressions that will be modified
        let backup_nodes = self.collect_struct_literal_backups(&op.struct_name, path_resolver.as_ref());

        // Find all struct literals and their field insertion points (surgical approach)
        use syn::visit::Visit;

        struct LiteralFieldInserter<'a> {
            struct_name: String,
            field_name: String,
            path_resolver: Option<&'a PathResolver>,
            insertion_points: Vec<(usize, usize)>, // (byte_offset, indentation_spaces)
            editor: &'a RustEditor,
        }

        impl<'ast, 'a> Visit<'ast> for LiteralFieldInserter<'a> {
            fn visit_expr_macro(&mut self, node: &'ast syn::ExprMacro) {
                // Parse macro contents to find struct literals inside (e.g., vec![...])
                use syn::parse::Parser;

                if let Ok(exprs) = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated
                    .parse2(node.mac.tokens.clone())
                {
                    for expr in exprs.iter() {
                        syn::visit::visit_expr(self, expr);
                    }
                }

                syn::visit::visit_expr_macro(self, node);
            }

            fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
                // Check if this matches our target
                let is_match = if let Some(resolver) = &self.path_resolver {
                    resolver.matches_target(&node.path)
                } else {
                    // Legacy matching logic
                    if self.struct_name.contains("::") {
                        if self.struct_name.starts_with("*::") {
                            let target_name = &self.struct_name[3..];
                            node.path.segments.last()
                                .map(|seg| seg.ident.to_string() == target_name)
                                .unwrap_or(false)
                        } else {
                            let path_str = node.path.segments.iter()
                                .map(|seg| seg.ident.to_string())
                                .collect::<Vec<_>>()
                                .join("::");
                            path_str == self.struct_name
                        }
                    } else {
                        node.path.segments.len() == 1
                            && node.path.segments.last()
                                .map(|seg| seg.ident.to_string())
                                .as_ref() == Some(&self.struct_name)
                    }
                };

                if is_match {
                    // Check if field already exists
                    let field_exists = node.fields.iter().any(|fv| {
                        fv.member.to_token_stream().to_string() == self.field_name
                    });

                    if !field_exists {
                        // Find insertion point after last field or after opening brace
                        let insert_offset = if let Some(last_field) = node.fields.last() {
                            // Insert after last field
                            self.editor.span_to_byte_offset(last_field.span().end())
                        } else {
                            // No fields, insert after opening brace
                            let brace_pos = self.editor.span_to_byte_offset(node.brace_token.span.join().start());
                            brace_pos + 1 // After the '{'
                        };

                        // Determine indentation from the last field or struct context
                        let indent = if let Some(last_field) = node.fields.last() {
                            let line_start = self.editor.span_to_byte_offset(last_field.span().start());
                            self.editor.get_indentation(line_start).len()
                        } else {
                            // Use struct opening indentation + 4 spaces
                            let struct_start = self.editor.span_to_byte_offset(node.span().start());
                            self.editor.get_indentation(struct_start).len() + 4
                        };

                        self.insertion_points.push((insert_offset, indent));
                    }
                }

                syn::visit::visit_expr_struct(self, node);
            }
        }

        let mut inserter = LiteralFieldInserter {
            struct_name: op.struct_name.clone(),
            field_name: field_name.clone(),
            path_resolver: path_resolver.as_ref(),
            insertion_points: Vec::new(),
            editor: self,
        };

        inserter.visit_file(&self.syntax_tree);

        if inserter.insertion_points.is_empty() {
            return Ok(ModificationResult {
                changed: false,
                modified_nodes: vec![],
            });
        }

        // Sort insertion points in reverse order so we can insert from end to beginning
        // (this way earlier offsets don't get invalidated by later insertions)
        let mut points = inserter.insertion_points;
        points.sort_by_key(|(offset, _)| std::cmp::Reverse(*offset));

        // Perform surgical insertions
        for (insert_offset, indent_spaces) in points {
            let indent = " ".repeat(indent_spaces);
            let field_str = format!(",\n{}{}", indent, op.field_def);
            self.content.insert_str(insert_offset, &field_str);
        }

        // Re-parse to update syntax_tree
        self.syntax_tree = syn::parse_str(&self.content)
            .context("Failed to re-parse after adding struct literal fields")?;
        self.line_offsets = Self::compute_line_offsets(&self.content);

        Ok(ModificationResult {
            changed: true,
            modified_nodes: backup_nodes,
        })
    }

    /// Collect backups of all struct literal expressions for a given struct name
    fn collect_struct_literal_backups(&self, struct_name: &str, path_resolver: Option<&PathResolver>) -> Vec<BackupNode> {
        use syn::visit::Visit;
        use syn::spanned::Spanned;

        struct LiteralCollector<'a> {
            struct_name: String,
            path_resolver: Option<&'a PathResolver>,
            backups: Vec<BackupNode>,
            counter: usize,
            editor: &'a RustEditor,
        }

        impl<'ast, 'a> Visit<'ast> for LiteralCollector<'a> {
            fn visit_expr_macro(&mut self, node: &'ast syn::ExprMacro) {
                // Parse macro contents to find struct literals inside (e.g., vec![...])
                use syn::parse::Parser;

                if let Ok(exprs) = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated
                    .parse2(node.mac.tokens.clone())
                {
                    for expr in exprs.iter() {
                        syn::visit::visit_expr(self, expr);
                    }
                }

                syn::visit::visit_expr_macro(self, node);
            }

            fn visit_expr(&mut self, node: &'ast Expr) {
                if let Expr::Struct(expr_struct) = node {
                    let matches = if let Some(resolver) = self.path_resolver {
                        // Use PathResolver for safe matching
                        resolver.matches_target(&expr_struct.path)
                    } else {
                        // Fallback to legacy pattern matching
                        // - "Rectangle" → only Rectangle { ... } (no :: prefix)
                        // - "*::Rectangle" → any path ending with Rectangle (View::Rectangle, etc.)
                        // - "View::Rectangle" → exact match only View::Rectangle

                        if self.struct_name.contains("::") {
                            // Pattern contains :: - check for exact or wildcard match
                            if self.struct_name.starts_with("*::") {
                                // Wildcard: *::Rectangle matches any path ending with Rectangle
                                let target_name = &self.struct_name[3..]; // Skip "*::"
                                expr_struct.path.segments.last()
                                    .map(|seg| seg.ident.to_string() == target_name)
                                    .unwrap_or(false)
                            } else {
                                // Exact path match: View::Rectangle
                                let path_str = expr_struct.path.segments.iter()
                                    .map(|seg| seg.ident.to_string())
                                    .collect::<Vec<_>>()
                                    .join("::");
                                path_str == self.struct_name
                            }
                        } else {
                            // No :: in pattern - only match pure struct literals (no path qualifier)
                            expr_struct.path.segments.len() == 1
                                && expr_struct.path.segments.last()
                                    .map(|seg| seg.ident.to_string() == self.struct_name)
                                    .unwrap_or(false)
                        }
                    };

                    if matches {
                        // Extract original source text with formatting preserved
                        let start = self.editor.span_to_byte_offset(expr_struct.span().start());
                        let end = self.editor.span_to_byte_offset(expr_struct.span().end());
                        let original_source = &self.editor.content[start..end];

                        self.backups.push(BackupNode {
                            node_type: "struct-literal".to_string(),
                            identifier: format!("{}#{}", self.struct_name, self.counter),
                            original_content: original_source.to_string(),
                            location: NodeLocation {
                                line: 0, // We don't have precise location info in visitor
                                column: 0,
                                end_line: 0,
                                end_column: 0,
                            },
                        });
                        self.counter += 1;
                    }
                }
                syn::visit::visit_expr(self, node);
            }
        }

        let mut collector = LiteralCollector {
            struct_name: struct_name.to_string(),
            path_resolver,
            backups: Vec::new(),
            counter: 0,
            editor: self,
        };

        collector.visit_file(&self.syntax_tree);
        collector.backups
    }

    pub(crate) fn add_enum_variant(&mut self, op: &AddEnumVariantOp) -> Result<ModificationResult> {
        // Find the enum and clone it to avoid borrowing issues
        let item_enum = self.syntax_tree.items.iter()
            .find_map(|item| {
                if let Item::Enum(e) = item {
                    if e.ident == op.enum_name {
                        return Some(e.clone());
                    }
                }
                None
            })
            .ok_or_else(|| anyhow::anyhow!("Enum '{}' not found", op.enum_name))?;

        // Check if the enum matches the where filter (if specified)
        if let Some(ref where_filter) = op.where_filter {
            if !self.matches_where_filter(&item_enum.attrs, where_filter)? {
                // Enum doesn't match filter - skip without error
                return Ok(ModificationResult {
                    changed: false,
                    modified_nodes: vec![],
                });
            }
        }

        // Create backup of original enum before modification
        let backup_node = BackupNode {
            node_type: "enum".to_string(),
            identifier: op.enum_name.clone(),
            original_content: self.unparse_item(&Item::Enum(item_enum.clone())),
            location: self.span_to_location(item_enum.span()),
        };

        let modified = self.insert_enum_variant(&item_enum, op)?;

        Ok(ModificationResult {
            changed: modified,
            modified_nodes: if modified { vec![backup_node] } else { vec![] },
        })
    }
    
    fn insert_enum_variant(&mut self, item_enum: &ItemEnum, op: &AddEnumVariantOp) -> Result<bool> {
        // Parse the new variant
        let variant_code = format!("enum Dummy {{ {} }}", op.variant_def);
        let dummy: ItemEnum = parse_str(&variant_code)
            .context("Failed to parse variant definition")?;

        let new_variant = dummy.variants.first()
            .context("No variant found in definition")?
            .clone();

        // Check if variant already exists
        let variant_name = new_variant.ident.to_string();
        if item_enum.variants.iter().any(|v| v.ident.to_string() == variant_name) {
            // Variant already exists, skip adding
            return Ok(false);
        }

        // Determine insertion point
        let insert_pos = match &op.position {
            InsertPosition::First => {
                if let Some(first_var) = item_enum.variants.first() {
                    self.span_to_byte_offset(first_var.span().start())
                } else {
                    let brace_pos = self.span_to_byte_offset(item_enum.brace_token.span.join().start());
                    brace_pos + 1
                }
            }
            InsertPosition::Last => {
                if let Some(last_var) = item_enum.variants.last() {
                    let end = self.span_to_byte_offset(last_var.span().end());
                    self.find_after_field_end(end)
                } else {
                    let brace_pos = self.span_to_byte_offset(item_enum.brace_token.span.join().start());
                    brace_pos + 1
                }
            }
            InsertPosition::After(name) => {
                let variant = item_enum.variants.iter()
                    .find(|v| v.ident.to_string() == *name)
                    .with_context(|| format!("Variant '{}' not found", name))?;
                let end = self.span_to_byte_offset(variant.span().end());
                self.find_after_field_end(end)
            }
            InsertPosition::Before(name) => {
                let variant = item_enum.variants.iter()
                    .find(|v| v.ident.to_string() == *name)
                    .with_context(|| format!("Variant '{}' not found", name))?;
                self.span_to_byte_offset(variant.span().start())
            }
        };
        
        let indent = self.get_indentation(insert_pos);
        let variant_str = new_variant.to_token_stream().to_string();
        let insert_text = format!("\n{}{},", indent, variant_str);
        
        self.content.insert_str(insert_pos, &insert_text);
        Ok(true)
    }

    fn update_enum_variant(&mut self, op: &UpdateEnumVariantOp) -> Result<ModificationResult> {
        // Find the enum and clone it
        let item_enum = self.syntax_tree.items.iter()
            .find_map(|item| {
                if let Item::Enum(e) = item {
                    if e.ident == op.enum_name {
                        return Some(e.clone());
                    }
                }
                None
            })
            .ok_or_else(|| anyhow::anyhow!("Enum '{}' not found", op.enum_name))?;

        // Check if the enum matches the where filter (if specified)
        if let Some(ref where_filter) = op.where_filter {
            if !self.matches_where_filter(&item_enum.attrs, where_filter)? {
                // Enum doesn't match filter - skip without error
                return Ok(ModificationResult {
                    changed: false,
                    modified_nodes: vec![],
                });
            }
        }

        // Create backup of original enum before modification
        let backup_node = BackupNode {
            node_type: "enum".to_string(),
            identifier: op.enum_name.clone(),
            original_content: self.unparse_item(&Item::Enum(item_enum.clone())),
            location: self.span_to_location(item_enum.span()),
        };

        // Parse the new variant to get its name
        let variant_code = format!("enum Dummy {{ {} }}", op.variant_def);
        let dummy: ItemEnum = parse_str(&variant_code)
            .context("Failed to parse variant definition")?;

        let new_variant = dummy.variants.first()
            .context("No variant found in definition")?
            .clone();

        let variant_name = new_variant.ident.to_string();

        // Find the existing variant
        let existing_variant = item_enum.variants.iter()
            .find(|v| v.ident.to_string() == variant_name)
            .ok_or_else(|| anyhow::anyhow!("Variant '{}' not found in enum '{}'", variant_name, op.enum_name))?;

        // Get the span
        let start = self.span_to_byte_offset(existing_variant.span().start());
        let end = self.span_to_byte_offset(existing_variant.span().end());

        // Format and replace
        let variant_str = new_variant.to_token_stream().to_string();
        self.content.replace_range(start..end, &variant_str);

        Ok(ModificationResult {
            changed: true,
            modified_nodes: vec![backup_node],
        })
    }

    pub(crate) fn remove_enum_variant(&mut self, op: &RemoveEnumVariantOp) -> Result<ModificationResult> {
        // Find the enum
        let item_enum = self.syntax_tree.items.iter()
            .find_map(|item| {
                if let Item::Enum(e) = item {
                    if e.ident == op.enum_name {
                        return Some(e.clone());
                    }
                }
                None
            })
            .ok_or_else(|| anyhow::anyhow!("Enum '{}' not found", op.enum_name))?;

        // Check if the enum matches the where filter (if specified)
        if let Some(ref where_filter) = op.where_filter {
            if !self.matches_where_filter(&item_enum.attrs, where_filter)? {
                // Enum doesn't match filter - skip without error
                return Ok(ModificationResult {
                    changed: false,
                    modified_nodes: vec![],
                });
            }
        }

        // Create backup of original enum before modification
        let backup_node = BackupNode {
            node_type: "enum".to_string(),
            identifier: op.enum_name.clone(),
            original_content: self.unparse_item(&Item::Enum(item_enum.clone())),
            location: self.span_to_location(item_enum.span()),
        };

        // Find the variant to remove
        let variant_to_remove = item_enum.variants.iter()
            .find(|v| v.ident.to_string() == op.variant_name)
            .ok_or_else(|| anyhow::anyhow!("Variant '{}' not found in enum '{}'", op.variant_name, op.enum_name))?;

        // Get the span including comma
        let start = self.span_to_byte_offset(variant_to_remove.span().start());
        let mut end = self.span_to_byte_offset(variant_to_remove.span().end());

        // Find and include the comma and trailing whitespace
        while end < self.content.len() {
            match self.content.as_bytes()[end] as char {
                ',' => {
                    end += 1;
                    if end < self.content.len() && self.content.as_bytes()[end] == b'\n' {
                        end += 1;
                    }
                    break;
                }
                ' ' | '\t' => end += 1,
                '\n' => {
                    end += 1;
                    break;
                }
                _ => break,
            }
        }

        // Remove leading whitespace on the line
        let mut line_start = start;
        while line_start > 0 && self.content.as_bytes()[line_start - 1] != b'\n' {
            line_start -= 1;
        }

        let before_variant = &self.content[line_start..start];
        if before_variant.trim().is_empty() {
            self.content.replace_range(line_start..end, "");
        } else {
            self.content.replace_range(start..end, "");
        }

        Ok(ModificationResult {
            changed: true,
            modified_nodes: vec![backup_node],
        })
    }

    pub(crate) fn add_match_arm(&mut self, op: &AddMatchArmOp) -> Result<ModificationResult> {
        if op.auto_detect {
            // Auto-detect mode: find all missing enum variants
            self.add_missing_match_arms(op)
        } else {
            // Normal mode: add a single match arm
            self.add_single_match_arm(op)
        }
    }

    fn add_single_match_arm(&mut self, op: &AddMatchArmOp) -> Result<ModificationResult> {
        // Parse the pattern and body by creating a dummy match expression
        let dummy_match = format!("match () {{ {} => {}, }}", op.pattern, op.body);
        let expr: syn::Expr = parse_str(&dummy_match)
            .with_context(|| format!("Failed to parse pattern/body: {} => {}", op.pattern, op.body))?;

        // Extract the arm from the dummy match
        let arm = if let syn::Expr::Match(match_expr) = expr {
            match_expr.arms.into_iter().next()
                .context("Failed to extract arm from dummy match")?
        } else {
            anyhow::bail!("Expected match expression");
        };

        // Collect backup of function before modification
        let backup_node = if let Some(ref fn_name) = op.function_name {
            self.get_function_backup(fn_name)?
        } else {
            // If no function specified, we'll backup all modified functions later
            // For now, create a generic backup
            BackupNode {
                node_type: "Unknown".to_string(),
                identifier: "match_expression".to_string(),
                original_content: String::new(),
                location: NodeLocation {
                    line: 0,
                    column: 0,
                    end_line: 0,
                    end_column: 0,
                },
            }
        };

        // Find and modify match expressions
        let mut visitor = MatchArmAdder {
            target_function: op.function_name.clone(),
            arm_to_add: arm,
            modified: false,
            current_function: None,
            modified_function: None,
        };

        visitor.visit_file_mut(&mut self.syntax_tree);

        if visitor.modified {
            // Replace just the modified function
            self.replace_modified_functions(&visitor.modified_function)?;
            Ok(ModificationResult {
                changed: true,
                modified_nodes: vec![backup_node],
            })
        } else {
            Ok(ModificationResult {
                changed: false,
                modified_nodes: vec![],
            })
        }
    }

    /// Format a single item to string using prettyplease
    fn unparse_item(&self, item: &Item) -> String {
        let temp_file = syn::File {
            shebang: None,
            attrs: Vec::new(),
            items: vec![item.clone()],
        };
        prettyplease::unparse(&temp_file).trim().to_string()
    }

    /// Isolated prettyplease: Reformat only a specific item, preserving the rest of the file
    /// This finds an item in the original syntax tree, formats it with prettyplease, and surgically replaces it
    fn reformat_item_isolated<F>(&mut self, predicate: F) -> Result<bool>
    where
        F: Fn(&Item) -> bool,
    {
        // Find the item index in the ORIGINAL syntax tree (before mutations)
        let original_syntax_tree: syn::File = syn::parse_str(&self.content)
            .context("Failed to parse original content")?;

        let (item_index, original_item) = original_syntax_tree.items.iter()
            .enumerate()
            .find(|(_, item)| predicate(item))
            .ok_or_else(|| anyhow::anyhow!("Item not found"))?;

        // Get the byte range of the original item
        let start = self.span_to_byte_offset(original_item.span().start());
        let end = self.span_to_byte_offset(original_item.span().end());

        // Get the modified item from the current syntax tree
        if item_index >= self.syntax_tree.items.len() {
            anyhow::bail!("Item index out of bounds after modification");
        }
        let modified_item = &self.syntax_tree.items[item_index];

        // Format just this item with prettyplease
        let formatted_item = self.unparse_item(modified_item);

        // Surgically replace the old item with the formatted version
        self.content.replace_range(start..end, &formatted_item);

        // Re-parse to update syntax_tree
        self.syntax_tree = syn::parse_str(&self.content)
            .context("Failed to re-parse after isolated prettyplease")?;
        self.line_offsets = Self::compute_line_offsets(&self.content);

        Ok(true)
    }

    /// Get backup of a function before modification
    fn get_function_backup(&self, fn_name: &str) -> Result<BackupNode> {
        for item in &self.syntax_tree.items {
            if let Item::Fn(f) = item {
                if f.sig.ident == fn_name {
                    return Ok(BackupNode {
                        node_type: "function".to_string(),
                        identifier: fn_name.to_string(),
                        original_content: self.unparse_item(&Item::Fn(f.clone())),
                        location: self.span_to_location(f.span()),
                    });
                }
            }
        }
        anyhow::bail!("Function '{}' not found", fn_name)
    }

    fn add_missing_match_arms(&mut self, op: &AddMatchArmOp) -> Result<ModificationResult> {
        // Get the enum name
        let enum_name = op.enum_name.as_ref()
            .ok_or_else(|| anyhow::anyhow!("enum_name is required for auto-detect"))?;

        // Find all enum variants
        let enum_variants = self.find_enum_variants(enum_name)?;

        if enum_variants.is_empty() {
            anyhow::bail!("Enum '{}' not found or has no variants", enum_name);
        }

        // Find existing match arms
        let existing_patterns = self.find_existing_match_patterns(&op.function_name);

        // Determine missing variants
        let mut missing_variants = Vec::new();
        for variant in &enum_variants {
            let pattern = format!("{}::{}", enum_name, variant);
            let pattern_normalized = pattern.replace(" ", "");

            let exists = existing_patterns.iter().any(|p| {
                p.replace(" ", "") == pattern_normalized
            });

            if !exists {
                missing_variants.push(variant.clone());
            }
        }

        if missing_variants.is_empty() {
            println!("All enum variants already covered in match expressions");
            return Ok(ModificationResult {
                changed: false,
                modified_nodes: vec![],
            });
        }

        // Get backup of function before modification
        let backup_node = if let Some(ref fn_name) = op.function_name {
            self.get_function_backup(fn_name)?
        } else {
            BackupNode {
                node_type: "Unknown".to_string(),
                identifier: "match_expression".to_string(),
                original_content: String::new(),
                location: NodeLocation {
                    line: 0,
                    column: 0,
                    end_line: 0,
                    end_column: 0,
                },
            }
        };

        // Add ALL missing match arms in one pass using a visitor
        let mut arms_to_add = Vec::new();
        for variant in &missing_variants {
            let pattern = format!("{}::{}", enum_name, variant);
            let dummy_match = format!("match () {{ {} => {}, }}", pattern, op.body);
            let expr: syn::Expr = parse_str(&dummy_match)
                .with_context(|| format!("Failed to parse pattern/body: {} => {}", pattern, op.body))?;

            if let syn::Expr::Match(match_expr) = expr {
                if let Some(arm) = match_expr.arms.into_iter().next() {
                    arms_to_add.push((pattern.clone(), arm));
                }
            }
        }

        // Find and modify match expressions with all arms at once
        let mut visitor = MultiMatchArmAdder {
            target_function: op.function_name.clone(),
            arms_to_add,
            modified: false,
            current_function: None,
            modified_function: None,
        };

        visitor.visit_file_mut(&mut self.syntax_tree);

        if visitor.modified {
            // Print what was added
            for variant in &missing_variants {
                println!("Added match arm for: {}::{}", enum_name, variant);
            }

            // Replace just the modified function
            self.replace_modified_functions(&visitor.modified_function)?;
            Ok(ModificationResult {
                changed: true,
                modified_nodes: vec![backup_node],
            })
        } else {
            Ok(ModificationResult {
                changed: false,
                modified_nodes: vec![],
            })
        }
    }

    fn find_enum_variants(&self, enum_name: &str) -> Result<Vec<String>> {
        // Find the enum in the syntax tree
        for item in &self.syntax_tree.items {
            if let Item::Enum(e) = item {
                if e.ident == enum_name {
                    let variants: Vec<String> = e.variants.iter()
                        .map(|v| v.ident.to_string())
                        .collect();
                    return Ok(variants);
                }
            }
        }

        Ok(Vec::new())
    }

    fn find_existing_match_patterns(&self, function_name: &Option<String>) -> Vec<String> {
        use syn::visit::Visit;

        struct PatternCollector {
            target_function: Option<String>,
            current_function: Option<String>,
            patterns: Vec<String>,
        }

        impl<'ast> Visit<'ast> for PatternCollector {
            fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
                let prev_fn = self.current_function.clone();
                self.current_function = Some(node.sig.ident.to_string());
                syn::visit::visit_item_fn(self, node);
                self.current_function = prev_fn;
            }

            fn visit_expr_match(&mut self, node: &'ast ExprMatch) {
                // Check if we're in the right function (if specified)
                if let Some(ref target) = self.target_function {
                    if self.current_function.as_ref() != Some(target) {
                        syn::visit::visit_expr_match(self, node);
                        return;
                    }
                }

                // Collect all patterns
                for arm in &node.arms {
                    self.patterns.push(arm.pat.to_token_stream().to_string());
                }

                syn::visit::visit_expr_match(self, node);
            }
        }

        let mut collector = PatternCollector {
            target_function: function_name.clone(),
            current_function: None,
            patterns: Vec::new(),
        };

        collector.visit_file(&self.syntax_tree);
        collector.patterns
    }

    pub(crate) fn update_match_arm(&mut self, op: &UpdateMatchArmOp) -> Result<ModificationResult> {
        // Get backup of function before modification
        let backup_node = if let Some(ref fn_name) = op.function_name {
            self.get_function_backup(fn_name)?
        } else {
            BackupNode {
                node_type: "Unknown".to_string(),
                identifier: "match_expression".to_string(),
                original_content: String::new(),
                location: NodeLocation {
                    line: 0,
                    column: 0,
                    end_line: 0,
                    end_column: 0,
                },
            }
        };

        // Parse the new body
        let new_body: syn::Expr = parse_str(&op.new_body)
            .with_context(|| format!("Failed to parse new body: {}", op.new_body))?;

        // Find and modify match expressions
        let mut visitor = MatchArmUpdater {
            target_function: op.function_name.clone(),
            pattern_to_match: op.pattern.clone(),
            new_body,
            modified: false,
            current_function: None,
            modified_function: None,
        };

        visitor.visit_file_mut(&mut self.syntax_tree);

        if visitor.modified {
            // Replace just the modified function
            self.replace_modified_functions(&visitor.modified_function)?;
            Ok(ModificationResult {
                changed: true,
                modified_nodes: vec![backup_node],
            })
        } else {
            anyhow::bail!("Pattern '{}' not found in any match expression", op.pattern)
        }
    }

    pub(crate) fn remove_match_arm(&mut self, op: &RemoveMatchArmOp) -> Result<ModificationResult> {
        // Get backup of function before modification
        let backup_node = if let Some(ref fn_name) = op.function_name {
            self.get_function_backup(fn_name)?
        } else {
            BackupNode {
                node_type: "Unknown".to_string(),
                identifier: "match_expression".to_string(),
                original_content: String::new(),
                location: NodeLocation {
                    line: 0,
                    column: 0,
                    end_line: 0,
                    end_column: 0,
                },
            }
        };

        // Find and modify match expressions
        let mut visitor = MatchArmRemover {
            target_function: op.function_name.clone(),
            pattern_to_remove: op.pattern.clone(),
            modified: false,
            current_function: None,
            modified_function: None,
        };

        visitor.visit_file_mut(&mut self.syntax_tree);

        if visitor.modified {
            // Replace just the modified function
            self.replace_modified_functions(&visitor.modified_function)?;
            Ok(ModificationResult {
                changed: true,
                modified_nodes: vec![backup_node],
            })
        } else {
            anyhow::bail!("Pattern '{}' not found in any match expression", op.pattern)
        }
    }

    pub(crate) fn add_impl_method(&mut self, op: &AddImplMethodOp) -> Result<ModificationResult> {
        // Parse the method definition
        let method_code = format!("impl Dummy {{ {} }}", op.method_def);
        let dummy: syn::ItemImpl = parse_str(&method_code)
            .context("Failed to parse method definition")?;

        let new_method = dummy.items.first()
            .context("No method found in definition")?
            .clone();

        // Get the method name for idempotency check
        let method_name = match &new_method {
            syn::ImplItem::Fn(f) => f.sig.ident.to_string(),
            _ => anyhow::bail!("Only method definitions are supported"),
        };

        // Find the impl block
        let impl_index = self.syntax_tree.items.iter().position(|item| {
            if let Item::Impl(impl_block) = item {
                // Check if this is the right impl block
                if let syn::Type::Path(type_path) = &*impl_block.self_ty {
                    if let Some(segment) = type_path.path.segments.last() {
                        return segment.ident == op.target;
                    }
                }
            }
            false
        }).ok_or_else(|| anyhow::anyhow!("impl block for '{}' not found", op.target))?;

        // Check if method already exists (idempotent)
        let impl_block = match &self.syntax_tree.items[impl_index] {
            Item::Impl(i) => i,
            _ => unreachable!(),
        };

        let method_exists = impl_block.items.iter().any(|item| {
            if let syn::ImplItem::Fn(f) = item {
                f.sig.ident == method_name
            } else {
                false
            }
        });

        if method_exists {
            return Ok(ModificationResult {
                changed: false,
                modified_nodes: vec![],
            });
        }

        // Create backup of original impl block before modification
        let backup_node = BackupNode {
            node_type: "ItemImpl".to_string(),
            identifier: op.target.clone(),
            original_content: self.unparse_item(&self.syntax_tree.items[impl_index].clone()),
            location: self.span_to_location(impl_block.span()),
        };

        // Get the span before modification
        let impl_span = impl_block.span();

        // Add the method to the impl block
        match &mut self.syntax_tree.items[impl_index] {
            Item::Impl(impl_block) => {
                // Add based on position
                match &op.position {
                    InsertPosition::First => {
                        impl_block.items.insert(0, new_method);
                    }
                    InsertPosition::Last => {
                        impl_block.items.push(new_method);
                    }
                    InsertPosition::After(name) => {
                        let pos = impl_block.items.iter().position(|item| {
                            if let syn::ImplItem::Fn(f) = item {
                                f.sig.ident == name
                            } else {
                                false
                            }
                        }).with_context(|| format!("Method '{}' not found", name))?;
                        impl_block.items.insert(pos + 1, new_method);
                    }
                    InsertPosition::Before(name) => {
                        let pos = impl_block.items.iter().position(|item| {
                            if let syn::ImplItem::Fn(f) = item {
                                f.sig.ident == name
                            } else {
                                false
                            }
                        }).with_context(|| format!("Method '{}' not found", name))?;
                        impl_block.items.insert(pos, new_method);
                    }
                }
            }
            _ => unreachable!(),
        }

        // Use prettyplease to format just this impl block
        self.replace_formatted_item(impl_index, impl_span)?;

        Ok(ModificationResult {
            changed: true,
            modified_nodes: vec![backup_node],
        })
    }

    pub(crate) fn add_use_statement(&mut self, op: &AddUseStatementOp) -> Result<ModificationResult> {
        // Parse the use statement
        let use_code = format!("use {};", op.use_path);
        let use_item: syn::ItemUse = parse_str(&use_code)
            .context("Failed to parse use statement")?;

        // Check if this use statement already exists (idempotent)
        let use_exists = self.syntax_tree.items.iter().any(|item| {
            if let Item::Use(existing_use) = item {
                // Compare the use trees
                existing_use.tree.to_token_stream().to_string() ==
                    use_item.tree.to_token_stream().to_string()
            } else {
                false
            }
        });

        if use_exists {
            return Ok(ModificationResult {
                changed: false,
                modified_nodes: vec![],
            });
        }

        // Create a simple backup for use statements (track by line position)
        let backup_node = BackupNode {
            node_type: "ItemUse".to_string(),
            identifier: op.use_path.clone(),
            original_content: format!("use {};", op.use_path),
            location: NodeLocation {
                line: 0,
                column: 0,
                end_line: 0,
                end_column: 0,
            },
        };

        // Find the position to insert the use statement
        let insert_index = match &op.position {
            InsertPosition::First => 0,
            InsertPosition::Last => {
                // Find the last use statement
                self.syntax_tree.items.iter()
                    .rposition(|item| matches!(item, Item::Use(_)))
                    .map(|i| i + 1)
                    .unwrap_or(0)
            }
            InsertPosition::After(path) => {
                // Find the use statement matching the path
                let pos = self.syntax_tree.items.iter().position(|item| {
                    if let Item::Use(u) = item {
                        u.tree.to_token_stream().to_string().contains(path)
                    } else {
                        false
                    }
                }).with_context(|| format!("Use statement for '{}' not found", path))?;
                pos + 1
            }
            InsertPosition::Before(path) => {
                // Find the use statement matching the path
                self.syntax_tree.items.iter().position(|item| {
                    if let Item::Use(u) = item {
                        u.tree.to_token_stream().to_string().contains(path)
                    } else {
                        false
                    }
                }).with_context(|| format!("Use statement for '{}' not found", path))?
            }
        };

        // Insert the use statement into the AST
        self.syntax_tree.items.insert(insert_index, Item::Use(use_item));

        // Find the byte position in the source where we need to insert
        // We want to insert at the beginning of a line
        let insert_line_pos = if insert_index == 0 {
            // Insert at very beginning
            0
        } else {
            // Insert after the previous item
            let prev_item = &self.syntax_tree.items[insert_index - 1];
            let span = prev_item.span();
            let end_pos = self.span_to_byte_offset(span.end());

            // Find the end of this line (where the newline is)
            let mut line_end = end_pos;
            while line_end < self.content.len() && self.content.as_bytes()[line_end] != b'\n' {
                line_end += 1;
            }
            // Move past the newline to the start of the next line
            if line_end < self.content.len() {
                line_end + 1
            } else {
                // At end of file, add a newline first
                self.content.push('\n');
                self.content.len()
            }
        };

        // Format the use statement
        let use_str = format!("use {};\n", op.use_path);

        // Insert the use statement
        self.content.insert_str(insert_line_pos, &use_str);

        Ok(ModificationResult {
            changed: true,
            modified_nodes: vec![backup_node],
        })
    }

    pub(crate) fn add_derive(&mut self, op: &AddDeriveOp) -> Result<ModificationResult> {
        // Find the target item (struct or enum)
        let item_index = self.syntax_tree.items.iter().position(|item| {
            match (&op.target_type as &str, item) {
                ("struct", Item::Struct(s)) => s.ident == op.target_name,
                ("enum", Item::Enum(e)) => e.ident == op.target_name,
                _ => false,
            }
        }).ok_or_else(|| anyhow::anyhow!("{} '{}' not found", op.target_type, op.target_name))?;

        // Get the item and check for existing derives
        let (existing_derives, item_span, item_attrs) = match &self.syntax_tree.items[item_index] {
            Item::Struct(s) => (Self::extract_derives(&s.attrs), s.span(), &s.attrs),
            Item::Enum(e) => (Self::extract_derives(&e.attrs), e.span(), &e.attrs),
            _ => (Vec::new(), proc_macro2::Span::call_site(), &Vec::new() as &Vec<syn::Attribute>),
        };

        // Check if the item matches the where filter (if specified)
        if let Some(ref where_filter) = op.where_filter {
            if !self.matches_where_filter(item_attrs, where_filter)? {
                // Item doesn't match filter - skip without error
                return Ok(ModificationResult {
                    changed: false,
                    modified_nodes: vec![],
                });
            }
        }

        // Create backup of original item before modification
        let backup_node = BackupNode {
            node_type: if op.target_type == "struct" { "struct" } else { "enum" }.to_string(),
            identifier: op.target_name.clone(),
            original_content: self.unparse_item(&self.syntax_tree.items[item_index].clone()),
            location: self.span_to_location(item_span),
        };

        // Filter out derives that already exist (idempotent)
        let new_derives: Vec<String> = op.derives.iter()
            .filter(|d| !existing_derives.contains(&d.to_string()))
            .cloned()
            .collect();

        if new_derives.is_empty() {
            // All derives already exist
            return Ok(ModificationResult {
                changed: false,
                modified_nodes: vec![],
            });
        }

        // Combine existing and new derives
        let mut all_derives = existing_derives;
        all_derives.extend(new_derives);

        // Convert to string refs for the update function
        let all_derives_refs: Vec<&str> = all_derives.iter().map(|s| s.as_str()).collect();

        // Update the AST item's attributes
        match &mut self.syntax_tree.items[item_index] {
            Item::Struct(s) => {
                Self::update_derive_attr(&mut s.attrs, &all_derives_refs)?;
            }
            Item::Enum(e) => {
                Self::update_derive_attr(&mut e.attrs, &all_derives_refs)?;
            }
            _ => unreachable!(),
        }

        // Use prettyplease to format just this item
        self.replace_formatted_item(item_index, item_span)?;

        Ok(ModificationResult {
            changed: true,
            modified_nodes: vec![backup_node],
        })
    }

    /// Replace an item in the content with a formatted version
    fn replace_formatted_item(&mut self, item_index: usize, original_span: Span) -> Result<()> {
        // Get the item start and end positions from the original source
        let item_start_pos = self.span_to_byte_offset(original_span.start());
        let item_end_pos = self.span_to_byte_offset(original_span.end());

        // Find the actual start (including attributes)
        let mut actual_start = item_start_pos;

        // Search backwards for attributes
        let mut temp_pos = item_start_pos;
        while temp_pos > 0 {
            // Move to previous line
            temp_pos = temp_pos.saturating_sub(1);
            let mut line_start = temp_pos;
            while line_start > 0 && self.content.as_bytes()[line_start - 1] != b'\n' {
                line_start -= 1;
            }

            let line = if temp_pos < self.content.len() {
                &self.content[line_start..temp_pos + 1]
            } else {
                &self.content[line_start..]
            };
            let trimmed = line.trim();

            if trimmed.starts_with("#[") {
                actual_start = line_start;
                temp_pos = line_start;
            } else if trimmed.is_empty() {
                temp_pos = line_start;
            } else {
                break;
            }

            if line_start == 0 {
                break;
            }
        }

        // Create a temporary file with just this item for pretty formatting
        let item_clone = self.syntax_tree.items[item_index].clone();
        let temp_file = syn::File {
            shebang: None,
            attrs: Vec::new(),
            items: vec![item_clone],
        };

        // Format the item using prettyplease
        let formatted = prettyplease::unparse(&temp_file);
        let formatted = formatted.trim();

        // Replace in content
        self.content.replace_range(actual_start..item_end_pos, formatted);

        Ok(())
    }

    /// Extract existing derive traits from attributes - returns owned Strings
    fn extract_derives(attrs: &[syn::Attribute]) -> Vec<String> {
        for attr in attrs {
            if attr.path().is_ident("derive") {
                if let Ok(syn::Meta::List(meta_list)) = attr.meta.clone().try_into() {
                    let tokens_str = meta_list.tokens.to_string();
                    return tokens_str
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .collect();
                }
            }
        }
        Vec::new()
    }

    /// Check if an item matches the where filter criteria
    /// Supports filters like:
    /// - "derives_trait:Clone" - matches if item derives Clone
    /// - "derives_trait:Clone,Debug" - matches if item derives Clone OR Debug
    fn matches_where_filter(&self, attrs: &[syn::Attribute], where_filter: &str) -> Result<bool> {
        // Parse the filter: "derives_trait:Clone,Debug"
        if let Some(filter_value) = where_filter.strip_prefix("derives_trait:") {
            let required_traits: Vec<&str> = filter_value.split(',').map(|s| s.trim()).collect();
            let existing_derives = Self::extract_derives(attrs);

            // Check if ANY of the required traits are present
            for required_trait in required_traits {
                if existing_derives.iter().any(|d| d == required_trait) {
                    return Ok(true);
                }
            }
            return Ok(false);
        }

        // Unknown filter type - default to match (don't break existing behavior)
        Ok(true)
    }

    /// Update or create derive attribute in the attribute list
    fn update_derive_attr(attrs: &mut Vec<syn::Attribute>, derives: &[&str]) -> Result<()> {
        let derive_str = derives.join(", ");

        // Parse a dummy struct with the derive to extract the attribute
        let dummy = format!("#[derive({})]\nstruct Dummy;", derive_str);
        let parsed: syn::ItemStruct = parse_str(&dummy)
            .context("Failed to parse derive attribute")?;

        let new_attr = parsed.attrs.into_iter()
            .find(|a| a.path().is_ident("derive"))
            .context("Failed to extract derive attribute")?;

        // Find existing derive attribute and replace it
        if let Some(pos) = attrs.iter().position(|a| a.path().is_ident("derive")) {
            attrs[pos] = new_attr;
        } else {
            // Add new derive attribute at the beginning
            attrs.insert(0, new_attr);
        }

        Ok(())
    }

    /// Replace the modified function(s) in the content with formatted versions
    fn replace_modified_functions(&mut self, modified_function: &Option<String>) -> Result<()> {
        // If no specific function was targeted, use isolated prettyplease for all modified functions
        if modified_function.is_none() {
            // This case shouldn't happen in practice, but if it does, fall back to whole-file format
            // TODO: Track which functions were modified and format only those
            self.content = prettyplease::unparse(&self.syntax_tree);
            return Ok(());
        }

        // Parse the ORIGINAL content to get the correct spans
        let original_syntax_tree: File = syn::parse_str(&self.content)
            .context("Failed to re-parse original content")?;

        let function_name = modified_function.as_ref().unwrap();

        // Find the function in the ORIGINAL syntax tree to get correct byte positions
        let original_fn = original_syntax_tree.items.iter()
            .find_map(|item| {
                if let Item::Fn(f) = item {
                    if f.sig.ident == function_name {
                        return Some(f.clone());
                    }
                }
                None
            })
            .ok_or_else(|| anyhow::anyhow!("Function '{}' not found in original", function_name))?;

        // Get the span of the original function (these are the correct byte positions)
        let start = self.span_to_byte_offset(original_fn.span().start());
        let end = self.span_to_byte_offset(original_fn.span().end());

        // Find the MODIFIED function in the modified syntax tree
        let modified_fn = self.syntax_tree.items.iter()
            .find_map(|item| {
                if let Item::Fn(f) = item {
                    if f.sig.ident == function_name {
                        return Some(f.clone());
                    }
                }
                None
            })
            .ok_or_else(|| anyhow::anyhow!("Function '{}' not found in modified AST", function_name))?;

        // Format just the modified function using prettyplease
        let dummy_file = syn::File {
            shebang: None,
            attrs: Vec::new(),
            items: vec![Item::Fn(modified_fn)],
        };

        let formatted_fn = prettyplease::unparse(&dummy_file);

        // Extract just the function (remove any extra newlines at start/end)
        let formatted_fn = formatted_fn.trim();

        // Replace the function in the original content using original spans
        self.content.replace_range(start..end, formatted_fn);

        Ok(())
    }

    pub fn span_to_byte_offset(&self, pos: LineColumn) -> usize {
        let line_idx = pos.line.saturating_sub(1);
        if line_idx < self.line_offsets.len() {
            self.line_offsets[line_idx] + pos.column
        } else {
            self.content.len()
        }
    }
    
    fn find_after_field_end(&self, pos: usize) -> usize {
        // Look for comma or newline after the field
        let mut i = pos;
        while i < self.content.len() {
            match self.content.as_bytes()[i] as char {
                ',' => return i + 1,
                '\n' => return i + 1,
                _ => i += 1,
            }
        }
        pos
    }
    
    fn get_indentation(&self, pos: usize) -> String {
        // Find the start of the current line
        let mut line_start = pos;
        while line_start > 0 && self.content.as_bytes()[line_start - 1] != b'\n' {
            line_start -= 1;
        }
        
        // Count spaces/tabs at the start of the line
        let mut indent = String::new();
        let mut i = line_start;
        while i < self.content.len() {
            match self.content.as_bytes()[i] as char {
                ' ' | '\t' => {
                    indent.push(self.content.as_bytes()[i] as char);
                    i += 1;
                }
                _ => break,
            }
        }
        
        // If we're inserting in an empty struct/enum, add default indentation
        if indent.is_empty() {
            "    ".to_string()
        } else {
            indent
        }
    }
    
    pub fn to_string(&self) -> String {
        self.content.clone()
    }

    /// Get a reference to the syntax tree (for revert operations)
    pub fn get_syntax_tree(&self) -> &syn::File {
        &self.syntax_tree
    }

    /// Replace a range of bytes with new content (for revert operations)
    pub fn replace_range(&mut self, start: usize, end: usize, new_content: &str) -> Result<()> {
        if start > end || end > self.content.len() {
            anyhow::bail!("Invalid range: {}..{} (content length: {})", start, end, self.content.len());
        }

        self.content.replace_range(start..end, new_content);

        // Re-parse the syntax tree
        self.syntax_tree = syn::parse_str(&self.content)
            .context("Failed to re-parse after replace_range")?;
        self.line_offsets = Self::compute_line_offsets(&self.content);

        Ok(())
    }

    /// Find all locations where a field appears in the codebase
    pub fn find_field_locations(&self, field_name: &str) -> Result<Vec<crate::operations::FieldLocation>> {
        use syn::visit::Visit;
        use crate::operations::{FieldLocation, FieldContext};

        let mut locations = Vec::new();

        // Search struct definitions
        for item in &self.syntax_tree.items {
            if let Item::Struct(s) = item {
                if let Fields::Named(ref fields) = s.fields {
                    for field in &fields.named {
                        if let Some(ident) = &field.ident {
                            if ident == field_name {
                                let field_type = quote::quote!(#field).to_string()
                                    .split(':')
                                    .nth(1)
                                    .map(|s| s.trim().to_string())
                                    .unwrap_or_else(|| "unknown".to_string());
                                locations.push(FieldLocation {
                                    file_path: String::new(),
                                    line: s.span().start().line,
                                    context: FieldContext::StructDefinition {
                                        struct_name: s.ident.to_string(),
                                        field_type,
                                    },
                                });
                            }
                        }
                    }
                }
            }

            // Search enum variants
            if let Item::Enum(e) = item {
                for variant in &e.variants {
                    if let Fields::Named(ref fields) = variant.fields {
                        for field in &fields.named {
                            if let Some(ident) = &field.ident {
                                if ident == field_name {
                                    let field_type = quote::quote!(#field).to_string()
                                        .split(':')
                                        .nth(1)
                                        .map(|s| s.trim().to_string())
                                        .unwrap_or_else(|| "unknown".to_string());
                                    locations.push(FieldLocation {
                                        file_path: String::new(),
                                        line: variant.span().start().line,
                                        context: FieldContext::EnumVariantDefinition {
                                            enum_name: e.ident.to_string(),
                                            variant_name: variant.ident.to_string(),
                                            field_type,
                                        },
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }

        // Search struct literals
        struct LiteralVisitor<'a> {
            field_name: &'a str,
            locations: Vec<FieldLocation>,
        }

        impl<'ast, 'a> Visit<'ast> for LiteralVisitor<'a> {
            fn visit_expr(&mut self, node: &'ast Expr) {
                if let Expr::Struct(expr_struct) = node {
                    // Check if this struct literal has the field
                    for field_value in &expr_struct.fields {
                        if let syn::Member::Named(ident) = &field_value.member {
                            if ident == self.field_name {
                                let struct_name = expr_struct.path.segments.iter()
                                    .map(|seg| seg.ident.to_string())
                                    .collect::<Vec<_>>()
                                    .join("::");

                                self.locations.push(FieldLocation {
                                    file_path: String::new(),
                                    line: expr_struct.span().start().line,
                                    context: FieldContext::StructLiteral {
                                        struct_name,
                                    },
                                });
                                break;
                            }
                        }
                    }
                }
                syn::visit::visit_expr(self, node);
            }
        }

        let mut visitor = LiteralVisitor {
            field_name,
            locations: Vec::new(),
        };

        visitor.visit_file(&self.syntax_tree);
        locations.extend(visitor.locations);

        Ok(locations)
    }

    /// Inspect and list AST nodes (e.g., struct literals) in the file
    pub fn inspect(&self, node_type: Option<&str>, name_filter: Option<&str>, variant_filter: Option<&str>, include_comments: bool) -> Result<Vec<crate::operations::InspectResult>> {
        use syn::visit::Visit;
        use crate::operations::InspectResult;

        let mut results = Vec::new();

        // If node_type is None, search all node types
        if node_type.is_none() {
            let all_types = vec![
                "struct", "enum", "function", "impl-method", "trait", "const", "static", "type-alias", "mod",
                "struct-literal", "match-arm", "enum-usage", "function-call", "method-call", "macro-call", "identifier", "type-ref",
            ];
            for nt in all_types {
                let mut type_results = self.inspect(Some(nt), name_filter, variant_filter, include_comments)?;
                results.append(&mut type_results);
            }
            return Ok(results);
        }

        let node_type = node_type.unwrap(); // Safe because we checked is_none above

        match node_type {
            "struct-literal" => {
                // Find all struct literal expressions
                struct StructLiteralVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for StructLiteralVisitor<'a> {
                    fn visit_expr_macro(&mut self, node: &'ast syn::ExprMacro) {
                        // Try to parse macro contents as expressions to find struct literals inside
                        // This handles cases like: vec![View::Rectangle { ... }]
                        use syn::parse::Parser;

                        // Try to parse the macro tokens as a punctuated list of expressions (common in vec!, etc.)
                        if let Ok(exprs) = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated
                            .parse2(node.mac.tokens.clone())
                        {
                            for expr in exprs.iter() {
                                syn::visit::visit_expr(self, expr);
                            }
                        }

                        // Continue with default visit behavior
                        syn::visit::visit_expr_macro(self, node);
                    }

                    fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
                        // Match based on pattern:
                        // - "Rectangle" → only Rectangle { ... } (no :: prefix)
                        // - "*::Rectangle" → any path ending with Rectangle (View::Rectangle, etc.)
                        // - "View::Rectangle" → exact match only View::Rectangle

                        let filter = match self.name_filter {
                            Some(f) => f,
                            None => {
                                // No filter - match anything
                                let struct_name = node.path.segments.last()
                                    .map(|seg| seg.ident.to_string())
                                    .unwrap_or_default();

                                let snippet = self.editor.format_expr_struct(node);
                                let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                                // Extract preceding comment if requested
                                let preceding_comment = if self.include_comments {
                                    extract_preceding_comment(&self.editor.content, location.line)
                                } else {
                                    None
                                };

                                self.results.push(InspectResult {
                                    file_path: String::new(),
                                    node_type: "struct-literal".to_string(),
                                    identifier: struct_name,
                                    location,
                                    snippet,
                                    preceding_comment,
                                });

                                syn::visit::visit_expr_struct(self, node);
                                return;
                            }
                        };

                        // Check if this struct literal matches the filter pattern
                        let matches = if filter.contains("::") {
                            // Pattern contains :: - check for exact or wildcard match
                            if filter.starts_with("*::") {
                                // Wildcard: *::Rectangle matches any path ending with Rectangle
                                let target_name = &filter[3..]; // Skip "*::"
                                node.path.segments.last()
                                    .map(|seg| seg.ident.to_string() == target_name)
                                    .unwrap_or(false)
                            } else {
                                // Exact path match: View::Rectangle
                                let path_str = node.path.segments.iter()
                                    .map(|seg| seg.ident.to_string())
                                    .collect::<Vec<_>>()
                                    .join("::");
                                path_str == filter
                            }
                        } else {
                            // No :: in pattern - eagerly match any path ending with this name
                            // This matches both "Rectangle" and "View::Rectangle" when searching for "Rectangle"
                            node.path.segments.last()
                                .map(|seg| seg.ident.to_string() == filter)
                                .unwrap_or(false)
                        };

                        if !matches {
                            syn::visit::visit_expr_struct(self, node);
                            return;
                        }

                        // Get the struct name for the identifier
                        let struct_name = node.path.segments.last()
                            .map(|seg| seg.ident.to_string())
                            .unwrap_or_default();

                        // Format the struct literal
                        let snippet = self.editor.format_expr_struct(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(), // Will be filled in by caller
                            node_type: "struct-literal".to_string(),
                            identifier: struct_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        // Continue visiting nested expressions
                        syn::visit::visit_expr_struct(self, node);
                    }
                }

                let mut visitor = StructLiteralVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                // Visit all items in the file
                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "match-arm" => {
                // Find all match arms
                struct MatchArmVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    pattern_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for MatchArmVisitor<'a> {
                    fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
                        // Iterate through all arms in this match expression
                        for arm in &node.arms {
                            // Convert pattern to string for matching
                            let pat = &arm.pat;
                            let pattern_str = quote::quote!(#pat).to_string();

                            // Apply pattern filter if specified
                            if let Some(filter) = self.pattern_filter {
                                // Normalize both for comparison (remove spaces)
                                let normalized_pattern = pattern_str.replace(" ", "");
                                let normalized_filter = filter.replace(" ", "");

                                if !normalized_pattern.contains(&normalized_filter) {
                                    continue;
                                }
                            }

                            // Format the match arm (pattern => body)
                            let snippet = self.editor.format_match_arm(arm);
                            let location = self.editor.span_to_location(arm.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                            // Extract preceding comment if requested
                            let preceding_comment = if self.include_comments {
                                extract_preceding_comment(&self.editor.content, location.line)
                            } else {
                                None
                            };

                            self.results.push(InspectResult {
                                file_path: String::new(), // Will be filled in by caller
                                node_type: "match-arm".to_string(),
                                identifier: pattern_str.replace(" ", ""),
                                location,
                                snippet,
                                preceding_comment,
                            });
                        }

                        // Continue visiting nested expressions
                        syn::visit::visit_expr_match(self, node);
                    }
                }

                let mut visitor = MatchArmVisitor {
                    results: &mut results,
                    pattern_filter: name_filter,
                    editor: self,
                    include_comments,
                };

                // Visit all items in the file
                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "enum-usage" => {
                // Find all enum variant usages (paths like Operator::Error)
                struct EnumUsageVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    path_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for EnumUsageVisitor<'a> {
                    fn visit_expr_path(&mut self, node: &'ast syn::ExprPath) {
                        // Convert path to string
                        let path = &node.path;
                        let path_str = quote::quote!(#path).to_string();

                        // Apply path filter if specified
                        if let Some(filter) = self.path_filter {
                            // Normalize both for comparison (remove spaces)
                            let normalized_path = path_str.replace(" ", "");
                            let normalized_filter = filter.replace(" ", "");

                            if !normalized_path.contains(&normalized_filter) {
                                syn::visit::visit_expr_path(self, node);
                                return;
                            }
                        }

                        // Format the path expression
                        let snippet = self.editor.format_expr_path(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(), // Will be filled in by caller
                            node_type: "enum-usage".to_string(),
                            identifier: path_str.replace(" ", ""),
                            location,
                            snippet,
                            preceding_comment,
                        });

                        // Continue visiting nested expressions
                        syn::visit::visit_expr_path(self, node);
                    }
                }

                let mut visitor = EnumUsageVisitor {
                    results: &mut results,
                    path_filter: name_filter,
                    editor: self,
                    include_comments,
                };

                // Visit all items in the file
                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "function-call" => {
                // Find all function call expressions
                struct FunctionCallVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for FunctionCallVisitor<'a> {
                    fn visit_expr_call(&mut self, node: &'ast syn::ExprCall) {
                        // Extract function name from the call expression
                        let func_name = if let syn::Expr::Path(expr_path) = &*node.func {
                            // Get the last segment of the path as the function name
                            expr_path.path.segments.last()
                                .map(|seg| seg.ident.to_string())
                                .unwrap_or_default()
                        } else {
                            // For other expression types, use quote to convert to string
                            quote::quote!(#node.func).to_string()
                        };

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if func_name != filter {
                                syn::visit::visit_expr_call(self, node);
                                return;
                            }
                        }

                        // Format the function call
                        let snippet = self.editor.format_expr_call(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(), // Will be filled in by caller
                            node_type: "function-call".to_string(),
                            identifier: func_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        // Continue visiting nested expressions
                        syn::visit::visit_expr_call(self, node);
                    }
                }

                let mut visitor = FunctionCallVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                // Visit all items in the file
                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "trait-method" => {
                // Find methods within trait definitions
                struct TraitMethodVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                    current_trait_name: Option<String>,
                }

                impl<'ast, 'a> Visit<'ast> for TraitMethodVisitor<'a> {
                    fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
                        // Track which trait this is
                        let prev_trait_name = self.current_trait_name.clone();
                        self.current_trait_name = Some(node.ident.to_string());

                        syn::visit::visit_item_trait(self, node);

                        self.current_trait_name = prev_trait_name;
                    }

                    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
                        let method_name = node.sig.ident.to_string();

                        // Create identifier with trait context if available
                        let identifier = if let Some(ref trait_name) = self.current_trait_name {
                            format!("{}::{}", trait_name, method_name)
                        } else {
                            method_name.clone()
                        };

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            // Support filtering by "Trait::method" or just "method"
                            if !identifier.contains(filter) && method_name != filter {
                                syn::visit::visit_trait_item_fn(self, node);
                                return;
                            }
                        }

                        // Format the method definition
                        let snippet = self.editor.format_trait_item_fn(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "trait-method".to_string(),
                            identifier,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_trait_item_fn(self, node);
                    }
                }

                let mut visitor = TraitMethodVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                    current_trait_name: None,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "method-call" => {
                // Find all method call expressions
                struct MethodCallVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for MethodCallVisitor<'a> {
                    fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
                        // Extract method name
                        let method_name = node.method.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if method_name != filter {
                                syn::visit::visit_expr_method_call(self, node);
                                return;
                            }
                        }

                        // Format the method call
                        let snippet = self.editor.format_expr_method_call(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(), // Will be filled in by caller
                            node_type: "method-call".to_string(),
                            identifier: method_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        // Continue visiting nested expressions
                        syn::visit::visit_expr_method_call(self, node);
                    }
                }

                let mut visitor = MethodCallVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                // Visit all items in the file
                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "identifier" => {
                // Find all identifier references
                struct IdentifierVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for IdentifierVisitor<'a> {
                    fn visit_ident(&mut self, node: &'ast syn::Ident) {
                        // Extract identifier name
                        let ident_name = node.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if ident_name != filter {
                                syn::visit::visit_ident(self, node);
                                return;
                            }
                        }

                        // Format the identifier
                        let snippet = self.editor.format_ident(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(), // Will be filled in by caller
                            node_type: "identifier".to_string(),
                            identifier: ident_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        // Continue visiting
                        syn::visit::visit_ident(self, node);
                    }
                }

                let mut visitor = IdentifierVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                // Visit all items in the file
                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "type-ref" => {
                // Find all type path usages
                struct TypeRefVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for TypeRefVisitor<'a> {
                    fn visit_type_path(&mut self, node: &'ast syn::TypePath) {
                        // Extract type name (last segment of path)
                        let type_name = node.path.segments.last()
                            .map(|seg| seg.ident.to_string())
                            .unwrap_or_default();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if type_name != filter {
                                syn::visit::visit_type_path(self, node);
                                return;
                            }
                        }

                        // Format the type path
                        let snippet = self.editor.format_type_path(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        // Get full path for identifier
                        let path = &node.path;
                        let path_str = quote::quote!(#path).to_string();

                        self.results.push(InspectResult {
                            file_path: String::new(), // Will be filled in by caller
                            node_type: "type-ref".to_string(),
                            identifier: path_str.replace(" ", ""),
                            location,
                            snippet,
                            preceding_comment,
                        });

                        // Continue visiting
                        syn::visit::visit_type_path(self, node);
                    }
                }

                let mut visitor = TypeRefVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                // Visit all items in the file
                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "macro-call" => {
                // Find all macro call expressions
                struct MacroCallVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for MacroCallVisitor<'a> {
                    fn visit_expr_macro(&mut self, node: &'ast syn::ExprMacro) {
                        // Extract macro name from the path
                        let macro_name = node.mac.path.segments.last()
                            .map(|seg| seg.ident.to_string())
                            .unwrap_or_default();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if macro_name != filter {
                                syn::visit::visit_expr_macro(self, node);
                                return;
                            }
                        }

                        // Format the macro call
                        let snippet = self.editor.format_expr_macro(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(), // Will be filled in by caller
                            node_type: "macro-call".to_string(),
                            identifier: macro_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        // Continue visiting nested expressions
                        syn::visit::visit_expr_macro(self, node);
                    }

                    fn visit_stmt(&mut self, node: &'ast syn::Stmt) {
                        // Also catch macro calls at statement level (e.g., println! as statement)
                        if let syn::Stmt::Macro(macro_stmt) = node {
                            let macro_name = macro_stmt.mac.path.segments.last()
                                .map(|seg| seg.ident.to_string())
                                .unwrap_or_default();

                            // Apply name filter if specified
                            if let Some(filter) = self.name_filter {
                                if macro_name != filter {
                                    syn::visit::visit_stmt(self, node);
                                    return;
                                }
                            }

                            // Format the macro call
                            let snippet = self.editor.format_stmt_macro(macro_stmt);
                            let location = self.editor.span_to_location(macro_stmt.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                            self.results.push(InspectResult {
                                file_path: String::new(), // Will be filled in by caller
                                node_type: "macro-call".to_string(),
                                identifier: macro_name,
                                location,
                                snippet,
                                preceding_comment,
                            });
                        }

                        // Continue visiting
                        syn::visit::visit_stmt(self, node);
                    }
                }

                let mut visitor = MacroCallVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                // Visit all items in the file
                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "struct" => {
                // Find all struct definitions
                struct StructDefVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for StructDefVisitor<'a> {
                    fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
                        let struct_name = node.ident.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if struct_name != filter {
                                syn::visit::visit_item_struct(self, node);
                                return;
                            }
                        }

                        // Format the struct definition
                        let snippet = self.editor.format_item_struct(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "struct".to_string(),
                            identifier: struct_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_item_struct(self, node);
                    }
                }

                let mut visitor = StructDefVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "enum" => {
                // Find all enum definitions
                // Supports:
                // 1. --variant Rectangle (all enums with Rectangle variant)
                // 2. --name View --variant Rectangle (View enum, Rectangle variant only)
                // 3. --name View::Rectangle (:: syntax auto-detects variant filter)
                // 4. --name *::Rectangle (wildcard: any enum with Rectangle variant)
                struct EnumDefVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    variant_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for EnumDefVisitor<'a> {
                    fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
                        let enum_name = node.ident.to_string();

                        // Parse name_filter for :: syntax
                        let (enum_name_filter, implicit_variant_filter) = if let Some(filter) = self.name_filter {
                            if filter.contains("::") {
                                // View::Rectangle or *::Rectangle
                                let parts: Vec<&str> = filter.split("::").collect();
                                if parts.len() == 2 {
                                    if parts[0] == "*" {
                                        // *::Rectangle - match any enum with this variant
                                        (None, Some(parts[1]))
                                    } else {
                                        // View::Rectangle - match specific enum with this variant
                                        (Some(parts[0]), Some(parts[1]))
                                    }
                                } else {
                                    // Invalid :: syntax, treat as exact enum name
                                    (Some(filter), None)
                                }
                            } else {
                                // Simple enum name filter
                                (Some(filter), None)
                            }
                        } else {
                            (None, None)
                        };

                        // Determine which variant filter to use (explicit --variant flag or implicit from ::)
                        let effective_variant_filter = self.variant_filter.or(implicit_variant_filter);

                        // Apply enum name filter if specified
                        if let Some(filter) = enum_name_filter {
                            if enum_name != filter {
                                syn::visit::visit_item_enum(self, node);
                                return;
                            }
                        }

                        // If variant filter is specified, check if this enum has that variant
                        if let Some(variant_name) = effective_variant_filter {
                            let has_variant = node.variants.iter().any(|v| v.ident.to_string() == variant_name);
                            if !has_variant {
                                syn::visit::visit_item_enum(self, node);
                                return;
                            }
                        }

                        // Format the enum definition
                        let snippet = if let Some(variant_name) = effective_variant_filter {
                            // Filter to show only the matching variant
                            self.editor.format_item_enum_variant_only(node, variant_name)
                        } else {
                            self.editor.format_item_enum(node)
                        };

                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "enum".to_string(),
                            identifier: enum_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_item_enum(self, node);
                    }
                }

                let mut visitor = EnumDefVisitor {
                    results: &mut results,
                    name_filter,
                    variant_filter,
                    editor: self,
                    include_comments,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "function" => {
                // Find all function definitions
                struct FunctionDefVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for FunctionDefVisitor<'a> {
                    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
                        let fn_name = node.sig.ident.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if fn_name != filter {
                                syn::visit::visit_item_fn(self, node);
                                return;
                            }
                        }

                        // Format the function definition
                        let snippet = self.editor.format_item_fn(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "function".to_string(),
                            identifier: fn_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_item_fn(self, node);
                    }
                }

                let mut visitor = FunctionDefVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "impl-method" => {
                // Find methods within impl blocks
                struct ImplMethodVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                    current_impl_type: Option<String>,
                }

                impl<'ast, 'a> Visit<'ast> for ImplMethodVisitor<'a> {
                    fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
                        // Track which type this impl is for
                        let impl_type = if let syn::Type::Path(type_path) = &*node.self_ty {
                            type_path.path.segments.last()
                                .map(|seg| seg.ident.to_string())
                        } else {
                            None
                        };

                        let prev_impl_type = self.current_impl_type.clone();
                        self.current_impl_type = impl_type;

                        syn::visit::visit_item_impl(self, node);

                        self.current_impl_type = prev_impl_type;
                    }

                    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
                        let method_name = node.sig.ident.to_string();

                        // Create identifier with impl type context if available
                        let identifier = if let Some(ref impl_type) = self.current_impl_type {
                            format!("{}::{}", impl_type, method_name)
                        } else {
                            method_name.clone()
                        };

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            // Support filtering by "Type::method" or just "method"
                            if !identifier.contains(filter) && method_name != filter {
                                syn::visit::visit_impl_item_fn(self, node);
                                return;
                            }
                        }

                        // Format the method definition
                        let snippet = self.editor.format_impl_item_fn(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "impl-method".to_string(),
                            identifier,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_impl_item_fn(self, node);
                    }
                }

                let mut visitor = ImplMethodVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                    current_impl_type: None,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "trait" => {
                // Find all trait definitions
                struct TraitDefVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for TraitDefVisitor<'a> {
                    fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
                        let trait_name = node.ident.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if trait_name != filter {
                                syn::visit::visit_item_trait(self, node);
                                return;
                            }
                        }

                        // Format the trait definition
                        let snippet = self.editor.format_item_trait(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "trait".to_string(),
                            identifier: trait_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_item_trait(self, node);
                    }
                }

                let mut visitor = TraitDefVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "const" => {
                // Find all const definitions
                struct ConstDefVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for ConstDefVisitor<'a> {
                    fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
                        let const_name = node.ident.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if const_name != filter {
                                syn::visit::visit_item_const(self, node);
                                return;
                            }
                        }

                        // Format the const definition
                        let snippet = self.editor.format_item_const(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "const".to_string(),
                            identifier: const_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_item_const(self, node);
                    }
                }

                let mut visitor = ConstDefVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "static" => {
                // Find all static definitions
                struct StaticDefVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for StaticDefVisitor<'a> {
                    fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
                        let static_name = node.ident.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if static_name != filter {
                                syn::visit::visit_item_static(self, node);
                                return;
                            }
                        }

                        // Format the static definition
                        let snippet = self.editor.format_item_static(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "static".to_string(),
                            identifier: static_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_item_static(self, node);
                    }
                }

                let mut visitor = StaticDefVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "type-alias" => {
                // Find all type alias definitions
                struct TypeAliasVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for TypeAliasVisitor<'a> {
                    fn visit_item_type(&mut self, node: &'ast syn::ItemType) {
                        let type_name = node.ident.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if type_name != filter {
                                syn::visit::visit_item_type(self, node);
                                return;
                            }
                        }

                        // Format the type alias definition
                        let snippet = self.editor.format_item_type(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "type-alias".to_string(),
                            identifier: type_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_item_type(self, node);
                    }
                }

                let mut visitor = TypeAliasVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            "mod" => {
                // Find all module definitions
                struct ModDefVisitor<'a> {
                    results: &'a mut Vec<InspectResult>,
                    name_filter: Option<&'a str>,
                    editor: &'a RustEditor,
                    include_comments: bool,
                }

                impl<'ast, 'a> Visit<'ast> for ModDefVisitor<'a> {
                    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
                        let mod_name = node.ident.to_string();

                        // Apply name filter if specified
                        if let Some(filter) = self.name_filter {
                            if mod_name != filter {
                                syn::visit::visit_item_mod(self, node);
                                return;
                            }
                        }

                        // Format the module definition
                        let snippet = self.editor.format_item_mod(node);
                        let location = self.editor.span_to_location(node.span());

                        // Extract preceding comment if requested
                        let preceding_comment = if self.include_comments {
                            extract_preceding_comment(&self.editor.content, location.line)
                        } else {
                            None
                        };

                        self.results.push(InspectResult {
                            file_path: String::new(),
                            node_type: "mod".to_string(),
                            identifier: mod_name,
                            location,
                            snippet,
                            preceding_comment,
                        });

                        syn::visit::visit_item_mod(self, node);
                    }
                }

                let mut visitor = ModDefVisitor {
                    results: &mut results,
                    name_filter,
                    editor: self,
                    include_comments,
                };

                for item in &self.syntax_tree.items {
                    syn::visit::visit_item(&mut visitor, item);
                }
            }
            _ => anyhow::bail!("Unsupported node type: {}", node_type),
        }

        Ok(results)
    }

    /// Format an ExprStruct node as a string - extracts original source
    fn format_expr_struct(&self, expr: &syn::ExprStruct) -> String {
        // Extract the original source code from the file content using the span
        let start = self.span_to_byte_offset(expr.span().start());
        let end = self.span_to_byte_offset(expr.span().end());

        // Get the original text and collapse to single line
        let original = &self.content[start..end];

        // Replace multiple whitespace/newlines with single space for single-line format
        original.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Format a match arm as a string - extracts original source
    fn format_match_arm(&self, arm: &syn::Arm) -> String {
        // Extract the original source code from the file content using the span
        let start = self.span_to_byte_offset(arm.span().start());
        let end = self.span_to_byte_offset(arm.span().end());

        // Get the original text and collapse to single line
        let original = &self.content[start..end];

        // Replace multiple whitespace/newlines with single space for single-line format
        original.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Format an ExprPath node as a string - extracts original source
    fn format_expr_path(&self, expr: &syn::ExprPath) -> String {
        // Extract the original source code from the file content using the span
        let start = self.span_to_byte_offset(expr.span().start());
        let end = self.span_to_byte_offset(expr.span().end());

        // Get the original text and collapse to single line
        let original = &self.content[start..end];

        // Replace multiple whitespace/newlines with single space for single-line format
        original.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Format an ExprCall node as a string - extracts original source
    fn format_expr_call(&self, expr: &syn::ExprCall) -> String {
        // Extract the original source code from the file content using the span
        let start = self.span_to_byte_offset(expr.span().start());
        let end = self.span_to_byte_offset(expr.span().end());

        // Get the original text and collapse to single line
        let original = &self.content[start..end];

        // Replace multiple whitespace/newlines with single space for single-line format
        original.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Format an ExprMethodCall node as a string - extracts original source
    fn format_expr_method_call(&self, expr: &syn::ExprMethodCall) -> String {
        // Extract the original source code from the file content using the span
        let start = self.span_to_byte_offset(expr.span().start());
        let end = self.span_to_byte_offset(expr.span().end());

        // Get the original text and collapse to single line
        let original = &self.content[start..end];

        // Replace multiple whitespace/newlines with single space for single-line format
        original.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Format an Ident node as a string - just return the identifier
    fn format_ident(&self, ident: &syn::Ident) -> String {
        ident.to_string()
    }

    /// Format a TypePath node as a string - extracts original source
    fn format_type_path(&self, ty: &syn::TypePath) -> String {
        // Extract the original source code from the file content using the span
        let start = self.span_to_byte_offset(ty.span().start());
        let end = self.span_to_byte_offset(ty.span().end());

        // Get the original text and collapse to single line
        let original = &self.content[start..end];

        // Replace multiple whitespace/newlines with single space for single-line format
        original.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Format an ExprMacro node as a string - extracts original source
    fn format_expr_macro(&self, expr: &syn::ExprMacro) -> String {
        // Extract the original source code from the file content using the span
        let start = self.span_to_byte_offset(expr.span().start());
        let end = self.span_to_byte_offset(expr.span().end());

        // Get the original text and collapse to single line
        let original = &self.content[start..end];

        // Replace multiple whitespace/newlines with single space for single-line format
        original.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Format a StmtMacro node as a string - extracts original source
    fn format_stmt_macro(&self, stmt: &syn::StmtMacro) -> String {
        // Extract the original source code from the file content using the span
        let start = self.span_to_byte_offset(stmt.span().start());
        let end = self.span_to_byte_offset(stmt.span().end());

        // Get the original text and collapse to single line
        let original = &self.content[start..end];

        // Replace multiple whitespace/newlines with single space for single-line format
        original.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// Format an ItemStruct node as a string - extracts original source
    fn format_item_struct(&self, item: &syn::ItemStruct) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format an ItemEnum node as a string - extracts original source
    fn format_item_enum(&self, item: &syn::ItemEnum) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format an ItemEnum showing only a specific variant
    fn format_item_enum_variant_only(&self, item: &syn::ItemEnum, variant_name: &str) -> String {
        // Find the matching variant
        let variant = item.variants.iter()
            .find(|v| v.ident.to_string() == variant_name);

        if let Some(variant) = variant {
            // Extract the enum header (visibility, enum keyword, name, generics, where clause)
            let enum_start = self.span_to_byte_offset(item.span().start());
            let variants_start = if !item.variants.is_empty() {
                self.span_to_byte_offset(item.variants.first().unwrap().span().start())
            } else {
                self.span_to_byte_offset(item.span().end())
            };

            // Get everything before the first variant (header)
            let header = &self.content[enum_start..variants_start].trim_end();

            // Extract the specific variant source
            let variant_start = self.span_to_byte_offset(variant.span().start());
            let variant_end = self.span_to_byte_offset(variant.span().end());
            let variant_source = &self.content[variant_start..variant_end];

            // Build the filtered output
            format!("{}\n    {},\n    // ... {} other variant{}\n}}",
                header,
                variant_source,
                item.variants.len() - 1,
                if item.variants.len() - 1 == 1 { "" } else { "s" }
            )
        } else {
            // Fallback: show full enum if variant not found
            self.format_item_enum(item)
        }
    }

    /// Format an ItemFn node as a string - extracts original source
    fn format_item_fn(&self, item: &syn::ItemFn) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format an ImplItemFn node as a string - extracts original source
    fn format_impl_item_fn(&self, item: &syn::ImplItemFn) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format a TraitItemFn node as a string - extracts original source
    fn format_trait_item_fn(&self, item: &syn::TraitItemFn) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format an ItemTrait node as a string - extracts original source
    fn format_item_trait(&self, item: &syn::ItemTrait) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format an ItemConst node as a string - extracts original source
    fn format_item_const(&self, item: &syn::ItemConst) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format an ItemStatic node as a string - extracts original source
    fn format_item_static(&self, item: &syn::ItemStatic) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format an ItemType node as a string - extracts original source
    fn format_item_type(&self, item: &syn::ItemType) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Format an ItemMod node as a string - extracts original source
    fn format_item_mod(&self, item: &syn::ItemMod) -> String {
        let start = self.span_to_byte_offset(item.span().start());
        let end = self.span_to_byte_offset(item.span().end());
        let original = &self.content[start..end];
        original.to_string()
    }

    /// Find the index of an item by type and name
    #[allow(dead_code)]
    pub(crate) fn find_item_index(&self, node_type: &str, name: &str) -> Result<usize> {
        for (index, item) in self.syntax_tree.items.iter().enumerate() {
            match (node_type, item) {
                ("struct", Item::Struct(s)) if s.ident == name => {
                    return Ok(index);
                }
                ("enum", Item::Enum(e)) if e.ident == name => {
                    return Ok(index);
                }
                ("fn", Item::Fn(f)) if f.sig.ident == name => {
                    return Ok(index);
                }
                ("impl", Item::Impl(impl_block)) => {
                    // For impl blocks, match on the self_ty
                    if let syn::Type::Path(type_path) = &*impl_block.self_ty {
                        if let Some(segment) = type_path.path.segments.last() {
                            if segment.ident == name {
                                return Ok(index);
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        anyhow::bail!("Item '{}' of type '{}' not found", name, node_type)
    }

    /// Replace an item at a specific index with a new item
    #[allow(dead_code)]
    pub(crate) fn replace_item_at_index(&mut self, index: usize, new_item: Item) -> Result<()> {
        if index >= self.syntax_tree.items.len() {
            anyhow::bail!("Index {} out of bounds", index);
        }

        // Replace the item in the syntax tree
        self.syntax_tree.items[index] = new_item;

        // Reformat the entire file using prettyplease
        self.content = prettyplease::unparse(&self.syntax_tree);

        // Recompute line offsets
        self.line_offsets = Self::compute_line_offsets(&self.content);

        Ok(())
    }

    fn span_to_location(&self, span: Span) -> NodeLocation {
        let start = span.start();
        let end = span.end();

        NodeLocation {
            line: start.line,
            column: start.column,
            end_line: end.line,
            end_column: end.column,
        }
    }

    /// Generic transform operation - find matching nodes and apply action
    pub(crate) fn transform(&mut self, op: &crate::operations::TransformOp) -> Result<ModificationResult> {
        use crate::operations::{InspectResult, TransformAction};

        // First, use inspect to find all matching nodes (comments not needed for transform)
        let matches = self.inspect(Some(&op.node_type), op.name_filter.as_deref(), None, false)?;

        // Apply content filter if specified
        let filtered_matches: Vec<InspectResult> = if let Some(ref content_filter) = op.content_filter {
            matches.into_iter()
                .filter(|m| m.snippet.contains(content_filter))
                .collect()
        } else {
            matches
        };

        if filtered_matches.is_empty() {
            return Ok(ModificationResult {
                changed: false,
                modified_nodes: vec![],
            });
        }

        // Now apply the transformation action to each match
        // We need to work backwards through the file to avoid offset issues
        let mut sorted_matches = filtered_matches;
        sorted_matches.sort_by(|a, b| {
            b.location.line.cmp(&a.location.line)
                .then(b.location.column.cmp(&a.location.column))
        });

        let mut modified_nodes = Vec::new();

        for match_result in &sorted_matches {
            // Create backup node
            let backup_node = BackupNode {
                node_type: match_result.node_type.clone(),
                identifier: match_result.identifier.clone(),
                original_content: match_result.snippet.clone(),
                location: match_result.location.clone(),
            };

            // Find the byte offsets for this node
            let start_offset = self.line_column_to_byte_offset(
                match_result.location.line,
                match_result.location.column
            )?;
            let end_offset = self.line_column_to_byte_offset(
                match_result.location.end_line,
                match_result.location.end_column
            )?;

            // Extract the original text
            let original_text = &self.content[start_offset..end_offset];

            // Apply the action
            let replacement = match &op.action {
                TransformAction::Comment => {
                    // Comment out the code
                    format!("// {}", original_text.replace("\n", "\n// "))
                }
                TransformAction::Remove => {
                    // Remove the entire node
                    String::new()
                }
                TransformAction::Replace { with } => {
                    // Replace with provided code
                    with.clone()
                }
            };

            // Replace in content
            self.content.replace_range(start_offset..end_offset, &replacement);

            // Recompute line offsets after each change
            self.line_offsets = Self::compute_line_offsets(&self.content);

            modified_nodes.push(backup_node);
        }

        // Re-parse the content if we made changes
        if !modified_nodes.is_empty() {
            // Don't reparse for now - we're doing text-level operations
            // self.syntax_tree = syn::parse_str(&self.content)
            //     .context("Failed to re-parse content after transformation")?;
        }

        Ok(ModificationResult {
            changed: !modified_nodes.is_empty(),
            modified_nodes,
        })
    }

    /// Rename an enum variant across the entire file
    pub(crate) fn rename_enum_variant(&mut self, op: &crate::operations::RenameEnumVariantOp) -> Result<ModificationResult> {
        use crate::operations::EditMode;

        // Create a path resolver if a canonical path was provided
        let path_resolver = if let Some(enum_path) = &op.enum_path {
            let mut resolver = PathResolver::new(enum_path)
                .ok_or_else(|| anyhow::anyhow!("Invalid enum path: {}", enum_path))?;

            // Scan the file for use statements to build the alias map
            resolver.scan_file(&self.syntax_tree);
            Some(resolver)
        } else {
            None
        };

        match op.edit_mode {
            EditMode::Surgical => {
                // Use non-mutating visitor to collect replacement locations
                use syn::visit::Visit;
                use crate::surgical::Replacement;

                let mut collector = EnumVariantReplacementCollector {
                    enum_name: op.enum_name.clone(),
                    old_variant: op.old_variant.clone(),
                    new_variant: op.new_variant.clone(),
                    path_resolver,
                    replacements: Vec::new(),
                };

                collector.visit_file(&self.syntax_tree);

                if collector.replacements.is_empty() {
                    return Ok(ModificationResult {
                        changed: false,
                        modified_nodes: vec![],
                    });
                }

                // Apply surgical edits to original content
                self.content = crate::surgical::apply_surgical_edits(&self.content, collector.replacements);

                // Recompute line offsets
                self.line_offsets = Self::compute_line_offsets(&self.content);

                // Re-parse the modified content
                self.syntax_tree = syn::parse_str(&self.content)
                    .context("Failed to re-parse after surgical edit")?;

                let backup_node = BackupNode {
                    node_type: "EnumVariantRename".to_string(),
                    identifier: format!("{}::{} -> {} (surgical)", op.enum_name, op.old_variant, op.new_variant),
                    original_content: format!("Renamed {} to {} in enum {} (surgical mode)", op.old_variant, op.new_variant, op.enum_name),
                    location: NodeLocation {
                        line: 1,
                        column: 0,
                        end_line: 1,
                        end_column: 0,
                    },
                };

                Ok(ModificationResult {
                    changed: true,
                    modified_nodes: vec![backup_node],
                })
            }
            EditMode::Reformat => {
                // Use mutating visitor (original behavior)
                let mut renamer = EnumVariantRenamer {
                    enum_name: op.enum_name.clone(),
                    old_variant: op.old_variant.clone(),
                    new_variant: op.new_variant.clone(),
                    path_resolver,
                    modified: false,
                };

                // Visit and mutate the syntax tree
                renamer.visit_file_mut(&mut self.syntax_tree);

                if !renamer.modified {
                    return Ok(ModificationResult {
                        changed: false,
                        modified_nodes: vec![],
                    });
                }

                // Reformat the entire file using prettyplease
                self.content = prettyplease::unparse(&self.syntax_tree);

                // Recompute line offsets
                self.line_offsets = Self::compute_line_offsets(&self.content);

                // Create a backup node for the entire file operation
                let backup_node = BackupNode {
                    node_type: "EnumVariantRename".to_string(),
                    identifier: format!("{}::{} -> {}", op.enum_name, op.old_variant, op.new_variant),
                    original_content: format!("Renamed {} to {} in enum {}", op.old_variant, op.new_variant, op.enum_name),
                    location: NodeLocation {
                        line: 1,
                        column: 0,
                        end_line: 1,
                        end_column: 0,
                    },
                };

                Ok(ModificationResult {
                    changed: true,
                    modified_nodes: vec![backup_node],
                })
            }
        }
    }

    /// Rename a function across the entire file
    pub(crate) fn rename_function(&mut self, op: &crate::operations::RenameFunctionOp) -> Result<ModificationResult> {
        use crate::operations::EditMode;

        // Create a path resolver if a canonical path was provided
        let path_resolver = if let Some(function_path) = &op.function_path {
            let mut resolver = PathResolver::new(function_path)
                .ok_or_else(|| anyhow::anyhow!("Invalid function path: {}", function_path))?;

            // Scan the file for use statements to build the alias map
            resolver.scan_file(&self.syntax_tree);
            Some(resolver)
        } else {
            None
        };

        match op.edit_mode {
            EditMode::Surgical => {
                // Use non-mutating visitor to collect replacement locations
                use syn::visit::Visit;

                let mut collector = FunctionReplacementCollector {
                    old_name: op.old_name.clone(),
                    new_name: op.new_name.clone(),
                    path_resolver,
                    replacements: Vec::new(),
                };

                collector.visit_file(&self.syntax_tree);

                if collector.replacements.is_empty() {
                    return Ok(ModificationResult {
                        changed: false,
                        modified_nodes: vec![],
                    });
                }

                // Apply surgical edits to original content
                self.content = crate::surgical::apply_surgical_edits(&self.content, collector.replacements);

                // Recompute line offsets
                self.line_offsets = Self::compute_line_offsets(&self.content);

                // Re-parse the modified content
                self.syntax_tree = syn::parse_str(&self.content)
                    .context("Failed to re-parse after surgical edit")?;

                let backup_node = BackupNode {
                    node_type: "FunctionRename".to_string(),
                    identifier: format!("{} -> {} (surgical)", op.old_name, op.new_name),
                    original_content: format!("Renamed {} to {} (surgical mode)", op.old_name, op.new_name),
                    location: NodeLocation {
                        line: 1,
                        column: 0,
                        end_line: 1,
                        end_column: 0,
                    },
                };

                Ok(ModificationResult {
                    changed: true,
                    modified_nodes: vec![backup_node],
                })
            }
            EditMode::Reformat => {
                // Use mutating visitor (original behavior)
                let mut renamer = FunctionRenamer {
                    old_name: op.old_name.clone(),
                    new_name: op.new_name.clone(),
                    path_resolver,
                    modified: false,
                };

                // Visit and mutate the syntax tree
                renamer.visit_file_mut(&mut self.syntax_tree);

                if !renamer.modified {
                    return Ok(ModificationResult {
                        changed: false,
                        modified_nodes: vec![],
                    });
                }

                // Reformat the entire file using prettyplease
                self.content = prettyplease::unparse(&self.syntax_tree);

                // Recompute line offsets
                self.line_offsets = Self::compute_line_offsets(&self.content);

                // Create a backup node for the entire file operation
                let backup_node = BackupNode {
                    node_type: "FunctionRename".to_string(),
                    identifier: format!("{} -> {}", op.old_name, op.new_name),
                    original_content: format!("Renamed {} to {}", op.old_name, op.new_name),
                    location: NodeLocation {
                        line: 1,
                        column: 0,
                        end_line: 1,
                        end_column: 0,
                    },
                };

                Ok(ModificationResult {
                    changed: true,
                    modified_nodes: vec![backup_node],
                })
            }
        }
    }

    /// Convert line/column to byte offset
    fn line_column_to_byte_offset(&self, line: usize, column: usize) -> Result<usize> {
        if line == 0 || line > self.line_offsets.len() {
            anyhow::bail!("Line {} out of range", line);
        }

        let line_start = self.line_offsets[line - 1];
        Ok(line_start + column)
    }
}

// Visitor for adding match arms
struct MatchArmAdder {
    target_function: Option<String>,
    arm_to_add: Arm,
    modified: bool,
    current_function: Option<String>,
    modified_function: Option<String>,
}

impl VisitMut for MatchArmAdder {
    fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
        let prev_fn = self.current_function.clone();
        self.current_function = Some(node.sig.ident.to_string());

        // Continue visiting nested items
        syn::visit_mut::visit_item_fn_mut(self, node);

        self.current_function = prev_fn;
    }

    fn visit_expr_match_mut(&mut self, node: &mut ExprMatch) {
        // Check if we're in the right function (if specified)
        if let Some(ref target) = self.target_function {
            if self.current_function.as_ref() != Some(target) {
                // Continue visiting nested expressions
                syn::visit_mut::visit_expr_match_mut(self, node);
                return;
            }
        }

        // Check if the pattern already exists (idempotent)
        let pattern_str = self.arm_to_add.pat.to_token_stream().to_string();
        let already_exists = node.arms.iter().any(|arm| {
            arm.pat.to_token_stream().to_string() == pattern_str
        });

        if !already_exists {
            // Add the arm to the end
            node.arms.push(self.arm_to_add.clone());
            self.modified = true;
            self.modified_function = self.current_function.clone();
        }

        // Continue visiting nested expressions
        syn::visit_mut::visit_expr_match_mut(self, node);
    }
}

// Visitor for updating match arms
struct MatchArmUpdater {
    target_function: Option<String>,
    pattern_to_match: String,
    new_body: syn::Expr,
    modified: bool,
    current_function: Option<String>,
    modified_function: Option<String>,
}

impl VisitMut for MatchArmUpdater {
    fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
        let prev_fn = self.current_function.clone();
        self.current_function = Some(node.sig.ident.to_string());

        syn::visit_mut::visit_item_fn_mut(self, node);

        self.current_function = prev_fn;
    }

    fn visit_expr_match_mut(&mut self, node: &mut ExprMatch) {
        // Check if we're in the right function (if specified)
        if let Some(ref target) = self.target_function {
            if self.current_function.as_ref() != Some(target) {
                syn::visit_mut::visit_expr_match_mut(self, node);
                return;
            }
        }

        // Find and update the matching arm
        for arm in &mut node.arms {
            let pattern_str = arm.pat.to_token_stream().to_string();
            // Normalize whitespace for comparison
            let pattern_normalized = pattern_str.replace(" ", "");
            let target_normalized = self.pattern_to_match.replace(" ", "");

            if pattern_normalized == target_normalized {
                arm.body = Box::new(self.new_body.clone());
                self.modified = true;
                self.modified_function = self.current_function.clone();
                break;
            }
        }

        syn::visit_mut::visit_expr_match_mut(self, node);
    }
}

// Visitor for removing match arms
struct MatchArmRemover {
    target_function: Option<String>,
    pattern_to_remove: String,
    modified: bool,
    current_function: Option<String>,
    modified_function: Option<String>,
}

impl VisitMut for MatchArmRemover {
    fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
        let prev_fn = self.current_function.clone();
        self.current_function = Some(node.sig.ident.to_string());

        syn::visit_mut::visit_item_fn_mut(self, node);

        self.current_function = prev_fn;
    }

    fn visit_expr_match_mut(&mut self, node: &mut ExprMatch) {
        // Check if we're in the right function (if specified)
        if let Some(ref target) = self.target_function {
            if self.current_function.as_ref() != Some(target) {
                syn::visit_mut::visit_expr_match_mut(self, node);
                return;
            }
        }

        // Find and remove the matching arm
        let mut index_to_remove = None;
        for (i, arm) in node.arms.iter().enumerate() {
            let pattern_str = arm.pat.to_token_stream().to_string();
            // Normalize whitespace for comparison
            let pattern_normalized = pattern_str.replace(" ", "");
            let target_normalized = self.pattern_to_remove.replace(" ", "");

            if pattern_normalized == target_normalized {
                index_to_remove = Some(i);
                break;
            }
        }

        if let Some(index) = index_to_remove {
            node.arms.remove(index);
            self.modified = true;
            self.modified_function = self.current_function.clone();
        }

        syn::visit_mut::visit_expr_match_mut(self, node);
    }
}

// Visitor for adding multiple match arms at once (for auto-detect)
struct MultiMatchArmAdder {
    target_function: Option<String>,
    arms_to_add: Vec<(String, Arm)>,  // (pattern_string, arm)
    modified: bool,
    current_function: Option<String>,
    modified_function: Option<String>,
}

impl VisitMut for MultiMatchArmAdder {
    fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
        let prev_fn = self.current_function.clone();
        self.current_function = Some(node.sig.ident.to_string());

        syn::visit_mut::visit_item_fn_mut(self, node);

        self.current_function = prev_fn;
    }

    fn visit_expr_match_mut(&mut self, node: &mut ExprMatch) {
        // Check if we're in the right function (if specified)
        if let Some(ref target) = self.target_function {
            if self.current_function.as_ref() != Some(target) {
                syn::visit_mut::visit_expr_match_mut(self, node);
                return;
            }
        }

        // Add all missing arms
        for (pattern_str, arm) in &self.arms_to_add {
            // Check if the pattern already exists (idempotent)
            let already_exists = node.arms.iter().any(|existing_arm| {
                existing_arm.pat.to_token_stream().to_string() == *pattern_str
            });

            if !already_exists {
                node.arms.push(arm.clone());
                self.modified = true;
                self.modified_function = self.current_function.clone();
            }
        }

        syn::visit_mut::visit_expr_match_mut(self, node);
    }
}

// Visitor for adding fields to struct literal expressions
struct StructLiteralFieldAdder {
    struct_name: String,
    field_def: String,
    field_name: String,
    position: InsertPosition,
    path_resolver: Option<PathResolver>,
    modified: bool,
}

impl VisitMut for StructLiteralFieldAdder {
    fn visit_expr_mut(&mut self, node: &mut Expr) {
        // Check if this is a struct literal expression
        if let Expr::Struct(expr_struct) = node {
            let is_match = if let Some(resolver) = &self.path_resolver {
                // Use PathResolver for safe matching
                resolver.matches_target(&expr_struct.path)
            } else {
                // Fallback to legacy pattern matching
                // - "Rectangle" → only Rectangle { ... } (no :: prefix)
                // - "*::Rectangle" → any path ending with Rectangle (View::Rectangle, etc.)
                // - "View::Rectangle" → exact match only View::Rectangle

                if self.struct_name.contains("::") {
                    // Pattern contains :: - check for exact or wildcard match
                    if self.struct_name.starts_with("*::") {
                        // Wildcard: *::Rectangle matches any path ending with Rectangle
                        let target_name = &self.struct_name[3..]; // Skip "*::"
                        expr_struct.path.segments.last()
                            .map(|seg| seg.ident.to_string() == target_name)
                            .unwrap_or(false)
                    } else {
                        // Exact path match: View::Rectangle
                        let path_str = expr_struct.path.segments.iter()
                            .map(|seg| seg.ident.to_string())
                            .collect::<Vec<_>>()
                            .join("::");
                        path_str == self.struct_name
                    }
                } else {
                    // No :: in pattern - only match pure struct literals (no path qualifier)
                    expr_struct.path.segments.len() == 1
                        && expr_struct.path.segments.last()
                            .map(|seg| seg.ident.to_string())
                            .as_ref() == Some(&self.struct_name)
                }
            };

            if is_match {
                // Check if field already exists (idempotent)
                let field_exists = expr_struct.fields.iter().any(|fv| {
                    fv.member.to_token_stream().to_string() == self.field_name
                });

                if !field_exists {
                    // Parse the field value from field_def
                    // field_def is like "return_type: None"
                    let field_value_code = format!("{{ {} }}", self.field_def);
                    if let Ok(expr) = parse_str::<ExprStruct>(&format!("Dummy {}", field_value_code)) {
                        if let Some(new_fv) = expr.fields.first() {
                            // Determine where to insert
                            match &self.position {
                                InsertPosition::First => {
                                    expr_struct.fields.insert(0, new_fv.clone());
                                    self.modified = true;
                                }
                                InsertPosition::Last => {
                                    expr_struct.fields.push(new_fv.clone());
                                    self.modified = true;
                                }
                                InsertPosition::After(after_field) => {
                                    // Find the position of the field to insert after
                                    if let Some(pos) = expr_struct.fields.iter().position(|fv| {
                                        fv.member.to_token_stream().to_string() == *after_field
                                    }) {
                                        expr_struct.fields.insert(pos + 1, new_fv.clone());
                                        self.modified = true;
                                    }
                                }
                                InsertPosition::Before(before_field) => {
                                    // Find the position of the field to insert before
                                    if let Some(pos) = expr_struct.fields.iter().position(|fv| {
                                        fv.member.to_token_stream().to_string() == *before_field
                                    }) {
                                        expr_struct.fields.insert(pos, new_fv.clone());
                                        self.modified = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // IMPORTANT: Visit children AFTER processing this node
        // This ensures we traverse into nested expressions
        syn::visit_mut::visit_expr_mut(self, node);
    }
}

// Visitor for renaming enum variants
struct EnumVariantRenamer {
    enum_name: String,
    old_variant: String,
    new_variant: String,
    path_resolver: Option<PathResolver>,
    modified: bool,
}

impl EnumVariantRenamer {
    /// Rename a path segment if it matches using path resolution.
    ///
    /// This method handles various path forms:
    /// - Simple paths: `EnumName::Variant`
    /// - Qualified paths: `crate::module::EnumName::Variant`
    /// - Imported paths: `Variant` (when enum is imported via use statement)
    ///
    /// When a PathResolver is configured, it validates that paths refer to
    /// the correct enum before renaming.
    fn rename_path(&mut self, path: &mut syn::Path) {
        // Check if the path ends with EnumName::VariantName
        let segments: Vec<_> = path.segments.iter().collect();
        let len = segments.len();

        if len >= 2 {
            // Path has at least enum and variant segments
            let potential_variant = &segments[len - 1];
            let potential_enum = &segments[len - 2];

            if potential_enum.ident == self.enum_name
                && potential_variant.ident == self.old_variant
            {
                // Path ends with EnumName::VariantName

                // If we have a path resolver, validate the enum path
                if let Some(resolver) = &self.path_resolver {
                    // Extract just the enum path (everything except the variant)
                    let enum_path = syn::Path {
                        leading_colon: path.leading_colon,
                        segments: path.segments.iter()
                            .take(len - 1)
                            .cloned()
                            .collect(),
                    };

                    // Only rename if the enum path matches our target
                    if resolver.matches_target(&enum_path) {
                        path.segments[len - 1].ident = syn::Ident::new(
                            &self.new_variant,
                            path.segments[len - 1].ident.span()
                        );
                        self.modified = true;
                    }
                } else {
                    // No resolver - use simple matching (backward compatible)
                    // Only match if it's exactly EnumName::Variant (2 segments)
                    if len == 2 {
                        path.segments[1].ident = syn::Ident::new(
                            &self.new_variant,
                            path.segments[1].ident.span()
                        );
                        self.modified = true;
                    }
                }
            }
        } else if len == 1 {
            // Single segment path - check if it's an imported variant
            if segments[0].ident == self.old_variant {
                // When using path resolver, we don't rename single-segment paths
                // unless they're explicitly imported (which would be unusual for variants)
                // For backward compatibility, we still rename them when no resolver is present
                if self.path_resolver.is_none() {
                    path.segments[0].ident = syn::Ident::new(
                        &self.new_variant,
                        path.segments[0].ident.span()
                    );
                    self.modified = true;
                }
            }
        }
    }
}

impl VisitMut for EnumVariantRenamer {
    /// Rename in enum definition
    fn visit_item_enum_mut(&mut self, node: &mut syn::ItemEnum) {
        if node.ident == self.enum_name {
            for variant in &mut node.variants {
                if variant.ident == self.old_variant {
                    variant.ident = syn::Ident::new(&self.new_variant, variant.ident.span());
                    self.modified = true;
                }
            }
        }

        // Continue visiting nested items
        syn::visit_mut::visit_item_enum_mut(self, node);
    }

    /// Rename in patterns (match arms, let bindings, function parameters, etc.)
    fn visit_pat_mut(&mut self, pat: &mut syn::Pat) {
        match pat {
            syn::Pat::TupleStruct(tuple_struct) => {
                self.rename_path(&mut tuple_struct.path);
            }
            syn::Pat::Struct(struct_pat) => {
                self.rename_path(&mut struct_pat.path);
            }
            syn::Pat::Path(path_pat) => {
                self.rename_path(&mut path_pat.path);
            }
            _ => {}
        }

        // Continue visiting nested patterns
        syn::visit_mut::visit_pat_mut(self, pat);
    }

    /// Rename in expressions (constructor calls, references, etc.)
    fn visit_expr_mut(&mut self, expr: &mut syn::Expr) {
        match expr {
            syn::Expr::Path(expr_path) => {
                self.rename_path(&mut expr_path.path);
            }
            syn::Expr::Call(call) => {
                if let syn::Expr::Path(path) = &mut *call.func {
                    self.rename_path(&mut path.path);
                }
            }
            syn::Expr::Struct(struct_expr) => {
                self.rename_path(&mut struct_expr.path);
            }
            _ => {}
        }

        // Continue visiting nested expressions
        syn::visit_mut::visit_expr_mut(self, expr);
    }
}

// Non-mutating visitor for collecting replacement locations (surgical mode)
struct EnumVariantReplacementCollector {
    enum_name: String,
    old_variant: String,
    new_variant: String,
    path_resolver: Option<PathResolver>,
    replacements: Vec<crate::surgical::Replacement>,
}

impl EnumVariantReplacementCollector {
    /// Check if a path matches and collect replacement if it does
    fn collect_path_replacement(&mut self, path: &syn::Path) {
        let segments: Vec<_> = path.segments.iter().collect();
        let len = segments.len();

        if len >= 2 {
            let potential_variant = &segments[len - 1];
            let potential_enum = &segments[len - 2];

            if potential_enum.ident == self.enum_name
                && potential_variant.ident == self.old_variant
            {
                // Path ends with EnumName::VariantName

                // Validate with path resolver if available
                let should_rename = if let Some(resolver) = &self.path_resolver {
                    let enum_path = syn::Path {
                        leading_colon: path.leading_colon,
                        segments: path.segments.iter()
                            .take(len - 1)
                            .cloned()
                            .collect(),
                    };
                    resolver.matches_target(&enum_path)
                } else {
                    // No resolver - only match exactly 2 segments
                    len == 2
                };

                if should_rename {
                    let span = potential_variant.ident.span();
                    let start = span.start();
                    let end = span.end();

                    self.replacements.push(crate::surgical::Replacement::new(
                        start,
                        end,
                        self.new_variant.clone(),
                    ));
                }
            }
        } else if len == 1 && self.path_resolver.is_none() {
            // Single segment - only without path resolver (backward compat)
            if segments[0].ident == self.old_variant {
                let span = segments[0].ident.span();
                let start = span.start();
                let end = span.end();

                self.replacements.push(crate::surgical::Replacement::new(
                    start,
                    end,
                    self.new_variant.clone(),
                ));
            }
        }
    }
}

impl<'ast> syn::visit::Visit<'ast> for EnumVariantReplacementCollector {
    fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
        if node.ident == self.enum_name {
            for variant in &node.variants {
                if variant.ident == self.old_variant {
                    let span = variant.ident.span();
                    let start = span.start();
                    let end = span.end();

                    self.replacements.push(crate::surgical::Replacement::new(
                        start,
                        end,
                        self.new_variant.clone(),
                    ));
                }
            }
        }
        syn::visit::visit_item_enum(self, node);
    }

    fn visit_pat(&mut self, pat: &'ast syn::Pat) {
        match pat {
            syn::Pat::TupleStruct(tuple_struct) => {
                self.collect_path_replacement(&tuple_struct.path);
            }
            syn::Pat::Struct(struct_pat) => {
                self.collect_path_replacement(&struct_pat.path);
            }
            syn::Pat::Path(path_pat) => {
                self.collect_path_replacement(&path_pat.path);
            }
            _ => {}
        }
        syn::visit::visit_pat(self, pat);
    }

    fn visit_expr(&mut self, expr: &'ast syn::Expr) {
        match expr {
            syn::Expr::Path(expr_path) => {
                self.collect_path_replacement(&expr_path.path);
            }
            syn::Expr::Call(call) => {
                if let syn::Expr::Path(path) = &*call.func {
                    self.collect_path_replacement(&path.path);
                }
            }
            syn::Expr::Struct(struct_expr) => {
                self.collect_path_replacement(&struct_expr.path);
            }
            _ => {}
        }
        syn::visit::visit_expr(self, expr);
    }
}

// Mutating visitor for renaming functions (reformat mode)
struct FunctionRenamer {
    old_name: String,
    new_name: String,
    path_resolver: Option<PathResolver>,
    modified: bool,
}

impl FunctionRenamer {
    /// Rename a function identifier if it matches
    fn rename_ident(&mut self, ident: &mut syn::Ident) {
        if ident == &self.old_name {
            *ident = syn::Ident::new(&self.new_name, ident.span());
            self.modified = true;
        }
    }

    /// Check if a path matches our target function (with path resolution)
    fn matches_target_function(&self, path: &syn::Path) -> bool {
        if let Some(resolver) = &self.path_resolver {
            resolver.matches_target(path)
        } else {
            // Simple matching: just check if the last segment is our function name
            path.segments.len() == 1 && path.segments.last().unwrap().ident == self.old_name
        }
    }
}

impl VisitMut for FunctionRenamer {
    fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
        // Rename function definition
        self.rename_ident(&mut node.sig.ident);
        syn::visit_mut::visit_item_fn_mut(self, node);
    }

    fn visit_impl_item_fn_mut(&mut self, node: &mut syn::ImplItemFn) {
        // Rename impl method definition
        self.rename_ident(&mut node.sig.ident);
        syn::visit_mut::visit_impl_item_fn_mut(self, node);
    }

    fn visit_trait_item_fn_mut(&mut self, node: &mut syn::TraitItemFn) {
        // Rename trait method definition
        self.rename_ident(&mut node.sig.ident);
        syn::visit_mut::visit_trait_item_fn_mut(self, node);
    }

    fn visit_expr_mut(&mut self, expr: &mut syn::Expr) {
        match expr {
            syn::Expr::Call(call) => {
                // Rename function calls
                if let syn::Expr::Path(expr_path) = &mut *call.func {
                    if self.matches_target_function(&expr_path.path) {
                        if let Some(last_seg) = expr_path.path.segments.last_mut() {
                            self.rename_ident(&mut last_seg.ident);
                        }
                    }
                }
            }
            syn::Expr::Path(expr_path) => {
                // Rename function references (not calls)
                if self.matches_target_function(&expr_path.path) {
                    if let Some(last_seg) = expr_path.path.segments.last_mut() {
                        self.rename_ident(&mut last_seg.ident);
                    }
                }
            }
            _ => {}
        }
        syn::visit_mut::visit_expr_mut(self, expr);
    }
}

// Non-mutating visitor for collecting function replacement locations (surgical mode)
struct FunctionReplacementCollector {
    old_name: String,
    new_name: String,
    path_resolver: Option<PathResolver>,
    replacements: Vec<crate::surgical::Replacement>,
}

impl FunctionReplacementCollector {
    /// Collect replacement for a function identifier
    fn collect_replacement(&mut self, ident: &syn::Ident) {
        if ident == &self.old_name {
            let span = ident.span();
            let start = span.start();
            let end = span.end();

            self.replacements.push(crate::surgical::Replacement::new(
                start,
                end,
                self.new_name.clone(),
            ));
        }
    }

    /// Check if a path matches our target function
    fn matches_target_function(&self, path: &syn::Path) -> bool {
        if let Some(resolver) = &self.path_resolver {
            resolver.matches_target(path)
        } else {
            // Simple matching
            path.segments.len() == 1 && path.segments.last().unwrap().ident == self.old_name
        }
    }
}

impl<'ast> syn::visit::Visit<'ast> for FunctionReplacementCollector {
    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        // Collect function definition rename
        self.collect_replacement(&node.sig.ident);
        syn::visit::visit_item_fn(self, node);
    }

    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        // Collect impl method definition rename
        self.collect_replacement(&node.sig.ident);
        syn::visit::visit_impl_item_fn(self, node);
    }

    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
        // Collect trait method definition rename
        self.collect_replacement(&node.sig.ident);
        syn::visit::visit_trait_item_fn(self, node);
    }

    fn visit_expr(&mut self, expr: &'ast syn::Expr) {
        match expr {
            syn::Expr::Call(call) => {
                // Collect function call renames
                if let syn::Expr::Path(expr_path) = &*call.func {
                    if self.matches_target_function(&expr_path.path) {
                        if let Some(last_seg) = expr_path.path.segments.last() {
                            self.collect_replacement(&last_seg.ident);
                        }
                    }
                }
                // Visit call arguments but NOT the func (already handled above)
                for arg in &call.args {
                    syn::visit::visit_expr(self, arg);
                }
                // Don't call the default visitor which would re-visit call.func
                return;
            }
            syn::Expr::Path(expr_path) => {
                // Collect function reference renames (not calls)
                if self.matches_target_function(&expr_path.path) {
                    if let Some(last_seg) = expr_path.path.segments.last() {
                        self.collect_replacement(&last_seg.ident);
                    }
                }
            }
            _ => {}
        }
        syn::visit::visit_expr(self, expr);
    }
}

// ============================================================================
// Doc Comment Operations
// ============================================================================

/// Generate a documentation comment in the specified style
fn generate_doc_comment(text: &str, style: &DocCommentStyle) -> String {
    match style {
        DocCommentStyle::Line => {
            // Split by newlines and add /// prefix to each line
            text.lines()
                .map(|line| {
                    if line.trim().is_empty() {
                        "///".to_string()
                    } else {
                        format!("/// {}", line)
                    }
                })
                .collect::<Vec<_>>()
                .join("\n")
        }
        DocCommentStyle::Block => {
            // Simple block comment
            if text.contains('\n') {
                // Multi-line block comment
                let lines = text.lines()
                    .map(|line| format!(" * {}", line))
                    .collect::<Vec<_>>()
                    .join("\n");
                format!("/**\n{}\n */", lines)
            } else {
                // Single-line block comment
                format!("/** {} */", text)
            }
        }
    }
}

/// Extract preceding comments (both doc and regular) before a given line
/// Returns None if no comments found, Some(comment_text) if comments exist
fn extract_preceding_comment(content: &str, start_line: usize) -> Option<String> {
    if start_line == 0 {
        return None;
    }

    let lines: Vec<&str> = content.lines().collect();
    if start_line > lines.len() {
        return None;
    }

    let line_idx = start_line.saturating_sub(1); // Convert 1-based to 0-based

    // Scan backwards from target to find comment lines
    let mut comment_start = line_idx;
    let mut found_any_comment = false;

    while comment_start > 0 {
        let prev_line = lines[comment_start - 1].trim();

        // Check if this is a comment line
        let is_comment = prev_line.starts_with("///")
            || prev_line.starts_with("//!")
            || prev_line.starts_with("//")
            || prev_line.starts_with("/**")
            || prev_line.starts_with("/*!")
            || prev_line.starts_with("/*")
            || (prev_line.starts_with("*") && !prev_line.starts_with("*/"))
            || prev_line == "*/";

        if is_comment {
            comment_start -= 1;
            found_any_comment = true;
        } else if prev_line.is_empty() && found_any_comment {
            // Allow blank lines within comment blocks, but don't continue past them
            // unless we're in the middle of a block comment
            comment_start -= 1;
        } else {
            break;
        }
    }

    if !found_any_comment {
        return None;
    }

    // Extract the comment lines and preserve original formatting
    let comment_lines: Vec<String> = lines[comment_start..line_idx]
        .iter()
        .map(|&line| line.to_string())
        .collect();

    if comment_lines.is_empty() {
        None
    } else {
        Some(comment_lines.join("\n"))
    }
}

/// Find the byte position and indentation of a target item
struct TargetFinder {
    target_type: String,
    target_name: String,
    found_position: Option<(usize, String)>, // (line_number, indentation)
}

impl TargetFinder {
    fn new(target_type: String, target_name: String) -> Self {
        Self {
            target_type,
            target_name,
            found_position: None,
        }
    }
}

impl<'ast> syn::visit::Visit<'ast> for TargetFinder {
    fn visit_item_struct(&mut self, node: &'ast ItemStruct) {
        if self.target_type == "struct" && node.ident.to_string() == self.target_name {
            // Use struct_token span to get the line where "struct" keyword appears,
            // not the first line of the item (which includes doc comments)
            let line = node.struct_token.span.start().line;
            self.found_position = Some((line, String::new()));
        }
        syn::visit::visit_item_struct(self, node);
    }

    fn visit_item_enum(&mut self, node: &'ast ItemEnum) {
        if self.target_type == "enum" && node.ident.to_string() == self.target_name {
            // Use enum_token span to get the line where "enum" keyword appears
            let line = node.enum_token.span.start().line;
            self.found_position = Some((line, String::new()));
        }
        syn::visit::visit_item_enum(self, node);
    }

    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        if self.target_type == "function" && node.sig.ident.to_string() == self.target_name {
            // Use fn_token span to get the line where "fn" keyword appears
            let line = node.sig.fn_token.span.start().line;
            self.found_position = Some((line, String::new()));
        }
        syn::visit::visit_item_fn(self, node);
    }
}

impl RustEditor {
    /// Add a documentation comment to a target item using surgical editing
    pub fn add_doc_comment_surgical(
        &mut self,
        target_type: &str,
        target_name: &str,
        doc_text: &str,
        style: &DocCommentStyle,
    ) -> Result<ModificationResult> {
        use syn::visit::Visit;

        // Find the target item
        let mut finder = TargetFinder::new(
            target_type.to_string(),
            target_name.to_string(),
        );
        finder.visit_file(&self.syntax_tree);

        if let Some((line_num, _indent)) = finder.found_position {
            // Lines are 1-indexed from syn, convert to 0-indexed
            let line_idx = line_num.saturating_sub(1);

            // Generate the doc comment
            let comment = generate_doc_comment(doc_text, style);

            // Find the actual line in the source
            let lines: Vec<&str> = self.content.lines().collect();
            if line_idx >= lines.len() {
                anyhow::bail!("Target not found at line {}", line_num);
            }

            let target_line = lines[line_idx].to_string(); // Clone to avoid borrow issues
            let target_line_len = target_line.len();

            // Detect indentation from the target line
            let indent = target_line
                .chars()
                .take_while(|c| c.is_whitespace())
                .collect::<String>();

            // Build the new content with comment inserted
            let mut new_lines: Vec<String> = lines.iter().map(|s| s.to_string()).collect();

            // Insert comment lines before the target
            let comment_lines: Vec<String> = comment
                .lines()
                .map(|line| format!("{}{}", indent, line))
                .collect();

            // Insert in reverse order to maintain indices
            for (i, comment_line) in comment_lines.iter().rev().enumerate() {
                new_lines.insert(line_idx, comment_line.clone());
            }

            // Update content
            self.content = new_lines.join("\n");

            // Re-parse to update syntax tree
            self.syntax_tree = syn::parse_str(&self.content)
                .context("Failed to re-parse after adding comment")?;

            Ok(ModificationResult {
                changed: true,
                modified_nodes: vec![BackupNode {
                    node_type: target_type.to_string(),
                    identifier: target_name.to_string(),
                    original_content: target_line,
                    location: NodeLocation {
                        line: line_num,
                        column: 1,
                        end_line: line_num,
                        end_column: target_line_len,
                    },
                }],
            })
        } else {
            anyhow::bail!("Target {} '{}' not found", target_type, target_name)
        }
    }

    /// Update an existing documentation comment on a target item using surgical editing
    pub fn update_doc_comment_surgical(
        &mut self,
        target_type: &str,
        target_name: &str,
        doc_text: &str,
        style: &DocCommentStyle,
    ) -> Result<ModificationResult> {
        use syn::visit::Visit;

        // Find the target item
        let mut finder = TargetFinder::new(
            target_type.to_string(),
            target_name.to_string(),
        );
        finder.visit_file(&self.syntax_tree);

        if let Some((line_num, _indent)) = finder.found_position {
            // Lines are 1-indexed from syn, convert to 0-indexed
            let line_idx = line_num.saturating_sub(1);

            // Find the actual line in the source
            let lines: Vec<&str> = self.content.lines().collect();
            if line_idx >= lines.len() {
                anyhow::bail!("Target not found at line {}", line_num);
            }

            let target_line = lines[line_idx].to_string(); // Clone to avoid borrow issues
            let target_line_len = target_line.len();

            // Detect indentation from the target line
            let indent = target_line
                .chars()
                .take_while(|c| c.is_whitespace())
                .collect::<String>();

            // Scan backwards from target to find existing doc comment lines
            let mut doc_comment_start = line_idx;
            while doc_comment_start > 0 {
                let prev_line = lines[doc_comment_start - 1].trim();
                if prev_line.starts_with("///") || prev_line.starts_with("//!") ||
                   prev_line.starts_with("/**") || prev_line.starts_with("/*!") ||
                   (prev_line.starts_with("*") && !prev_line.starts_with("*/")) ||
                   prev_line == "*/" {
                    doc_comment_start -= 1;
                } else {
                    break;
                }
            }

            // Build new content with old comments removed and new ones inserted
            let mut new_lines: Vec<String> = Vec::new();

            // Add lines before the doc comments
            for i in 0..doc_comment_start {
                new_lines.push(lines[i].to_string());
            }

            // Generate and add new doc comment
            let comment = generate_doc_comment(doc_text, style);
            let comment_lines: Vec<String> = comment
                .lines()
                .map(|line| format!("{}{}", indent, line))
                .collect();

            for comment_line in comment_lines {
                new_lines.push(comment_line);
            }

            // Add remaining lines (from target onwards)
            for i in line_idx..lines.len() {
                new_lines.push(lines[i].to_string());
            }

            // Update content
            self.content = new_lines.join("\n");

            // Re-parse to update syntax tree
            self.syntax_tree = syn::parse_str(&self.content)
                .context("Failed to re-parse after updating comment")?;

            Ok(ModificationResult {
                changed: true,
                modified_nodes: vec![BackupNode {
                    node_type: target_type.to_string(),
                    identifier: target_name.to_string(),
                    original_content: target_line,
                    location: NodeLocation {
                        line: line_num,
                        column: 1,
                        end_line: line_num,
                        end_column: target_line_len,
                    },
                }],
            })
        } else {
            anyhow::bail!("Target {} '{}' not found", target_type, target_name)
        }
    }

    /// Remove a documentation comment from a target item using surgical editing
    pub fn remove_doc_comment_surgical(
        &mut self,
        target_type: &str,
        target_name: &str,
    ) -> Result<ModificationResult> {
        use syn::visit::Visit;

        // Find the target item
        let mut finder = TargetFinder::new(
            target_type.to_string(),
            target_name.to_string(),
        );
        finder.visit_file(&self.syntax_tree);

        if let Some((line_num, _indent)) = finder.found_position {
            // Lines are 1-indexed from syn, convert to 0-indexed
            let line_idx = line_num.saturating_sub(1);

            // Find the actual line in the source
            let lines: Vec<&str> = self.content.lines().collect();
            if line_idx >= lines.len() {
                anyhow::bail!("Target not found at line {}", line_num);
            }

            let target_line = lines[line_idx].to_string(); // Clone to avoid borrow issues
            let target_line_len = target_line.len();

            // Scan backwards from target to find existing doc comment lines
            let mut doc_comment_start = line_idx;
            while doc_comment_start > 0 {
                let prev_line = lines[doc_comment_start - 1].trim();
                if prev_line.starts_with("///") || prev_line.starts_with("//!") ||
                   prev_line.starts_with("/**") || prev_line.starts_with("/*!") ||
                   (prev_line.starts_with("*") && !prev_line.starts_with("*/")) ||
                   prev_line == "*/" {
                    doc_comment_start -= 1;
                } else {
                    break;
                }
            }

            // Build new content with doc comments removed
            let mut new_lines: Vec<String> = Vec::new();

            // Add lines before the doc comments
            for i in 0..doc_comment_start {
                new_lines.push(lines[i].to_string());
            }

            // Skip the doc comment lines (from doc_comment_start to line_idx)

            // Add remaining lines (from target onwards)
            for i in line_idx..lines.len() {
                new_lines.push(lines[i].to_string());
            }

            // Update content
            self.content = new_lines.join("\n");

            // Re-parse to update syntax tree
            self.syntax_tree = syn::parse_str(&self.content)
                .context("Failed to re-parse after removing comment")?;

            Ok(ModificationResult {
                changed: true,
                modified_nodes: vec![BackupNode {
                    node_type: target_type.to_string(),
                    identifier: target_name.to_string(),
                    original_content: target_line,
                    location: NodeLocation {
                        line: line_num,
                        column: 1,
                        end_line: line_num,
                        end_column: target_line_len,
                    },
                }],
            })
        } else {
            anyhow::bail!("Target {} '{}' not found", target_type, target_name)
        }
    }
}