ryo-executor 0.1.0

[experimental] Mutation execution engine for RYO - parallel execution, conflict detection, workspace management
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
//! V2 ASTRegApply implementations for trait operations
//!
//! - ExtractTrait: Extract methods from impl block into a new trait
//! - InlineTrait: Inline trait methods back into inherent impl
//!
//! # Implementation Strategy
//!
//! **ExtractTrait:**
//! 1. Find the inherent impl for the struct (impl Foo { ... } where trait_ is None)
//! 2. Extract specified methods (or all if methods is None)
//! 3. Create a new trait definition with method signatures
//! 4. Create a new trait impl (impl TraitName for Foo { ... }) with method bodies
//! 5. Remove the extracted methods from the inherent impl
//!
//! **InlineTrait:**
//! 1. Find the trait impl (impl TraitName for Foo { ... })
//! 2. Find or create the inherent impl (impl Foo { ... })
//! 3. Move methods from trait impl to inherent impl
//! 4. Optionally remove the trait definition and trait impl

use ryo_analysis::SymbolKind;
use ryo_mutations::basic::{
    EnumToTraitMutation, EnumToTraitStrategy, ExtractTraitMutation, InlineTraitMutation,
    MatchHandling, RemoveTraitMutation,
};
use ryo_mutations::{Mutation, MutationResult};
use ryo_source::pure::{
    MacroDelimiter, PureBlock, PureExpr, PureField, PureFields, PureFn, PureGenericParam,
    PureGenerics, PureImpl, PureImplItem, PureItem, PureParam, PureStmt, PureStruct, PureTrait,
    PureTraitItem, PureType, PureVis,
};

use crate::engine::{ASTMutationContext, ASTRegApply};

impl ASTRegApply for ExtractTraitMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Step 1: O(1) lookup for the inherent impl using symbol_id
        let impl_id = self.symbol_id;
        let impl_path = match ctx.symbol_registry.path(impl_id) {
            Some(path) => path.clone(),
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("SymbolId {:?} not found in registry", impl_id),
                };
            }
        };

        // Verify it's an impl and get the AST
        let inherent_impl = match ctx.ast_registry.get(impl_id) {
            Some(PureItem::Impl(imp)) => {
                // Verify it's an inherent impl (not a trait impl)
                if imp.trait_.is_some() {
                    return MutationResult {
                        mutation_type: self.mutation_type().to_string(),
                        changes: 0,
                        description: format!(
                            "SymbolId {:?} is a trait impl, not an inherent impl",
                            impl_id
                        ),
                    };
                }
                imp.clone()
            }
            Some(_) => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("SymbolId {:?} is not an impl block", impl_id),
                };
            }
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("No AST found for SymbolId {:?}", impl_id),
                };
            }
        };

        // Get struct name from the impl's self_ty
        let struct_name = inherent_impl.self_ty.clone();

        // Step 2: Partition methods into extracted vs remaining
        let (extracted_items, remaining_items): (Vec<_>, Vec<_>) =
            inherent_impl.items.into_iter().partition(|item| {
                if let PureImplItem::Fn(f) = item {
                    match &self.methods {
                        Some(methods) => methods.contains(&f.name),
                        None => true, // Extract all methods
                    }
                } else {
                    false // Don't extract non-method items
                }
            });

        if extracted_items.is_empty() {
            return MutationResult {
                mutation_type: self.mutation_type().to_string(),
                changes: 0,
                description: "No methods to extract".to_string(),
            };
        }

        let mut changes = 0;

        // Step 3: Create trait definition with method signatures
        let trait_items: Vec<PureTraitItem> = extracted_items
            .iter()
            .filter_map(|item| {
                if let PureImplItem::Fn(f) = item {
                    // Create trait method signature (empty body for trait definition)
                    let trait_fn = PureFn {
                        attrs: f.attrs.clone(),
                        vis: PureVis::Private, // Trait methods use default visibility
                        is_async: f.is_async,
                        is_async_inferred: f.is_async_inferred,
                        is_const: f.is_const,
                        is_unsafe: f.is_unsafe,
                        abi: None,
                        name: f.name.clone(),
                        generics: f.generics.clone(),
                        params: f.params.clone(),
                        ret: f.ret.clone(),
                        body: PureBlock::default(), // Empty body for trait signature
                    };
                    Some(PureTraitItem::Fn(trait_fn))
                } else {
                    None
                }
            })
            .collect();

        let new_trait = PureTrait {
            attrs: Vec::new(),
            vis: PureVis::Public, // Default to public trait
            is_unsafe: false,
            is_auto: false,
            name: self.trait_name.clone(),
            generics: PureGenerics::default(),
            supertraits: Vec::new(),
            items: trait_items,
        };

        // Register the new trait
        let trait_path = match impl_path
            .parent()
            .and_then(|p| p.child(&self.trait_name).ok())
        {
            Some(path) => path,
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("Failed to create path for trait '{}'", self.trait_name),
                };
            }
        };

        if ctx
            .register_with_ast(
                trait_path.clone(),
                SymbolKind::Trait,
                PureItem::Trait(new_trait),
            )
            .is_some()
        {
            changes += 1;
        }

        // Step 4: Create trait impl with method bodies
        // Trait impl methods must NOT have visibility qualifiers (pub is inherited from trait)
        let trait_impl_items: Vec<PureImplItem> = extracted_items
            .into_iter()
            .map(|item| {
                if let PureImplItem::Fn(mut f) = item {
                    f.vis = PureVis::Private; // Remove pub for trait impl methods
                    PureImplItem::Fn(f)
                } else {
                    item
                }
            })
            .collect();

        let trait_impl = PureImpl {
            attrs: Vec::new(),
            generics: inherent_impl.generics.clone(),
            is_unsafe: false,
            trait_: Some(self.trait_name.clone()),
            self_ty: struct_name.clone(),
            items: trait_impl_items,
        };

        // Register the trait impl
        let trait_impl_name = format!(
            "<impl {} for {}>",
            self.trait_name,
            struct_name
                .replace("::", "_")
                .replace('<', "_")
                .replace('>', "")
        );
        let trait_impl_path = match impl_path
            .parent()
            .and_then(|p| p.child(&trait_impl_name).ok())
        {
            Some(path) => path,
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes,
                    description: "Failed to create path for trait impl".to_string(),
                };
            }
        };

        if let Some(_trait_impl_id) = ctx.register_with_ast(
            trait_impl_path,
            SymbolKind::Impl,
            PureItem::Impl(trait_impl.clone()),
        ) {
            // Also add to module_items
            if let Some(parent_path) = impl_path.parent() {
                if let Some(parent_id) = ctx.symbol_registry.lookup(&parent_path) {
                    if let Some(module_items) = ctx.ast_registry.get_module_items_mut(parent_id) {
                        module_items.push(PureItem::Impl(trait_impl));
                    }
                }
            }
            changes += 1;
        }

        // Step 5: Update the inherent impl to remove extracted methods
        if remaining_items.is_empty() {
            // If no methods remain, remove the inherent impl
            ctx.remove_symbol(impl_id);
            changes += 1;
        } else {
            let updated_impl = PureImpl {
                attrs: inherent_impl.attrs,
                generics: inherent_impl.generics,
                is_unsafe: inherent_impl.is_unsafe,
                trait_: None,
                self_ty: struct_name.clone(),
                items: remaining_items,
            };
            ctx.set_ast(impl_id, PureItem::Impl(updated_impl));
            changes += 1;
        }

        MutationResult {
            mutation_type: self.mutation_type().to_string(),
            changes,
            description: format!(
                "Extracted trait '{}' from '{}'",
                self.trait_name, struct_name
            ),
        }
    }
}

impl ASTRegApply for InlineTraitMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Get trait name from symbol_id (O(1) lookup)
        let trait_name = match ctx.symbol_registry.path(self.symbol_id) {
            Some(path) => path.name().to_string(),
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("Trait symbol {:?} not found in registry", self.symbol_id),
                };
            }
        };

        // Step 1: Find the trait impl (impl TraitName for Foo)
        let trait_impl_entry = ctx.symbol_registry.iter().find(|(id, _path)| {
            if !matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Impl)) {
                return false;
            }
            if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(*id) {
                imp.trait_.as_ref() == Some(&trait_name) && imp.self_ty == self.struct_name
            } else {
                false
            }
        });

        let (trait_impl_id, trait_impl_path) = match trait_impl_entry {
            Some((id, path)) => (id, path.clone()),
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!(
                        "No impl of '{}' for '{}' found",
                        trait_name, self.struct_name
                    ),
                };
            }
        };

        let trait_impl = match ctx.ast_registry.get(trait_impl_id) {
            Some(PureItem::Impl(imp)) => imp.clone(),
            _ => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: "No AST found for trait impl".to_string(),
                };
            }
        };

        let mut changes = 0;

        // Step 2: Find or identify the inherent impl
        let inherent_impl_entry = ctx.symbol_registry.iter().find(|(id, _path)| {
            if !matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Impl)) {
                return false;
            }
            if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(*id) {
                imp.trait_.is_none() && imp.self_ty == self.struct_name
            } else {
                false
            }
        });

        // Step 3: Move methods to inherent impl
        if let Some((inherent_impl_id, _)) = inherent_impl_entry {
            // Existing inherent impl - add methods to it (both ASTRegistry and module_items)
            if let Some(PureItem::Impl(mut inherent_impl)) =
                ctx.ast_registry.get(inherent_impl_id).cloned()
            {
                inherent_impl.items.extend(trait_impl.items.clone());
                ctx.set_ast(inherent_impl_id, PureItem::Impl(inherent_impl.clone()));

                // Also update in module_items
                if let Some(parent_path) = trait_impl_path.parent() {
                    if let Some(parent_id) = ctx.symbol_registry.lookup(&parent_path) {
                        if let Some(module_items) = ctx.ast_registry.get_module_items_mut(parent_id)
                        {
                            for item in module_items.iter_mut() {
                                if let PureItem::Impl(impl_block) = item {
                                    if impl_block.trait_.is_none()
                                        && impl_block.self_ty == self.struct_name
                                    {
                                        impl_block.items.extend(trait_impl.items.clone());
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                changes += 1;
            }
        } else {
            // No inherent impl exists - create one with the trait methods
            let new_inherent_impl = PureImpl {
                attrs: Vec::new(),
                generics: trait_impl.generics.clone(),
                is_unsafe: false,
                trait_: None,
                self_ty: self.struct_name.clone(),
                items: trait_impl.items.clone(),
            };

            let impl_name = format!(
                "<impl {}>",
                self.struct_name
                    .replace("::", "_")
                    .replace('<', "_")
                    .replace('>', "")
            );
            let impl_path = match trait_impl_path
                .parent()
                .and_then(|p| p.child(&impl_name).ok())
            {
                Some(path) => path,
                None => {
                    return MutationResult {
                        mutation_type: self.mutation_type().to_string(),
                        changes: 0,
                        description: "Failed to create path for inherent impl".to_string(),
                    };
                }
            };

            if let Some(_new_impl_id) = ctx.register_with_ast(
                impl_path,
                SymbolKind::Impl,
                PureItem::Impl(new_inherent_impl.clone()),
            ) {
                // Also add to module_items
                if let Some(parent_path) = trait_impl_path.parent() {
                    if let Some(parent_id) = ctx.symbol_registry.lookup(&parent_path) {
                        if let Some(module_items) = ctx.ast_registry.get_module_items_mut(parent_id)
                        {
                            module_items.push(PureItem::Impl(new_inherent_impl));
                        }
                    }
                }
                changes += 1;
            }
        }

        // Step 4: Remove the trait impl
        ctx.remove_symbol(trait_impl_id);
        changes += 1;

        // Step 5: Optionally remove the trait definition (O(1) using symbol_id)
        if self.remove_trait {
            ctx.remove_symbol(self.symbol_id);
            changes += 1;
        }

        MutationResult {
            mutation_type: self.mutation_type().to_string(),
            changes,
            description: format!(
                "Inlined trait '{}' into '{}'{}",
                trait_name,
                self.struct_name,
                if self.remove_trait {
                    " (trait removed)"
                } else {
                    ""
                }
            ),
        }
    }
}

impl ASTRegApply for RemoveTraitMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Use the provided SymbolId for O(1) access
        let trait_id = self.trait_id;

        // Verify the trait exists and is a trait
        if ctx.symbol_registry.kind(trait_id) != Some(SymbolKind::Trait) {
            return MutationResult {
                mutation_type: "RemoveTrait".to_string(),
                changes: 0,
                description: format!("Symbol {} is not a trait", trait_id),
            };
        }

        ctx.ast_registry.remove(trait_id);

        MutationResult {
            mutation_type: "RemoveTrait".to_string(),
            changes: 1,
            description: format!("Removed trait {}", trait_id),
        }
    }
}

impl ASTRegApply for EnumToTraitMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        let enum_id = self.symbol_id;

        // Verify the symbol exists and is an enum
        if !matches!(ctx.symbol_registry.kind(enum_id), Some(SymbolKind::Enum)) {
            return MutationResult {
                mutation_type: self.mutation_type().to_string(),
                changes: 0,
                description: format!("Symbol {:?} is not an enum or not found", enum_id),
            };
        }

        let enum_path = match ctx.symbol_registry.path(enum_id) {
            Some(p) => p.clone(),
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("Path not found for symbol {:?}", enum_id),
                };
            }
        };

        // Get enum name from path for trait name and usage replacement
        let enum_name = enum_path.name().to_string();

        // Determine trait name:
        // - If user specified trait_name, use it
        // - For MarkerOnly without specified name, use {EnumName}Trait to avoid collision
        // - Otherwise, use enum_name
        let default_trait_name;
        let trait_name = match &self.trait_name {
            Some(name) => name.as_str(),
            None => {
                match self.strategy {
                    EnumToTraitStrategy::MarkerOnly => {
                        // MarkerOnly keeps enum, so trait needs different name
                        default_trait_name = format!("{}Trait", enum_name);
                        &default_trait_name
                    }
                    _ => &enum_name,
                }
            }
        };

        // Get the enum AST
        let enum_def = match ctx.ast_registry.get(enum_id) {
            Some(PureItem::Enum(e)) => e.clone(),
            _ => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("No AST found for enum '{}'", enum_name),
                };
            }
        };

        let mut changes = 0;
        let parent_path = match enum_path.parent() {
            Some(p) => p,
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: "Cannot determine parent module".to_string(),
                };
            }
        };

        // Collect variant names for usage site replacement
        let variant_names: Vec<String> = enum_def.variants.iter().map(|v| v.name.clone()).collect();

        // Step 1.5: Find enum's inherent impl block and extract methods
        let enum_impl_id: Option<_> = ctx
            .symbol_registry
            .iter()
            .find(|(id, _)| {
                if !matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Impl)) {
                    return false;
                }
                if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(*id) {
                    // Inherent impl: no trait, matches enum name
                    imp.trait_.is_none() && imp.self_ty == enum_name
                } else {
                    false
                }
            })
            .map(|(id, _)| id); // Extract just the SymbolId to end the borrow

        // Extract methods from enum's impl block
        let enum_methods: Vec<PureFn> = if let Some(impl_id) = enum_impl_id {
            if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(impl_id) {
                imp.items
                    .iter()
                    .filter_map(|item| {
                        if let PureImplItem::Fn(f) = item {
                            // Only extract instance methods (with &self or &mut self)
                            let has_self = f
                                .params
                                .iter()
                                .any(|p| matches!(p, PureParam::SelfValue { .. }));
                            if has_self {
                                Some(f.clone())
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    })
                    .collect()
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };

        // Step 1.6: Remove enum FIRST if trait name equals enum name (to free the path)
        // This must happen before trait registration to avoid path collision
        // MarkerOnly: NEVER remove enum early (types still reference it)
        let enum_removed_early = match self.strategy {
            EnumToTraitStrategy::MarkerOnly => false, // Never remove for MarkerOnly
            _ if self.remove_enum && trait_name == enum_name => {
                ctx.remove_symbol(enum_id);
                changes += 1;
                // Also remove the enum's inherent impl block early
                if let Some(impl_id) = enum_impl_id {
                    ctx.remove_symbol(impl_id);
                    changes += 1;
                }
                true
            }
            _ => false,
        };

        // Step 2: Create trait definition with method signatures
        let trait_items: Vec<PureTraitItem> = enum_methods
            .iter()
            .map(|f| {
                // Create trait method signature (no body for trait definition)
                let trait_fn = PureFn {
                    attrs: Vec::new(),
                    vis: PureVis::Private, // Trait methods use default visibility
                    is_async: f.is_async,
                    is_async_inferred: f.is_async_inferred,
                    is_const: f.is_const,
                    is_unsafe: f.is_unsafe,
                    abi: None,
                    name: f.name.clone(),
                    generics: f.generics.clone(),
                    params: f.params.clone(),
                    ret: f.ret.clone(),
                    body: PureBlock::default(), // Empty body = abstract method in trait
                };
                PureTraitItem::Fn(trait_fn)
            })
            .collect();

        let new_trait = PureTrait {
            attrs: Vec::new(),
            vis: PureVis::Public,
            is_unsafe: false,
            is_auto: false,
            name: trait_name.to_string(),
            generics: PureGenerics::default(),
            supertraits: Vec::new(),
            items: trait_items,
        };

        let trait_path = match parent_path.child(trait_name) {
            Ok(path) => path,
            Err(_) => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("Failed to create path for trait '{}'", trait_name),
                };
            }
        };

        if ctx
            .register_with_ast(
                trait_path.clone(),
                SymbolKind::Trait,
                PureItem::Trait(new_trait),
            )
            .is_some()
        {
            changes += 1;
        }

        // Step 3: Create struct + impl for each variant
        for variant in &enum_def.variants {
            // Convert variant fields to struct fields
            let struct_fields = match &variant.fields {
                PureFields::Named(fields) => PureFields::Named(
                    fields
                        .iter()
                        .map(|f| PureField {
                            attrs: Vec::new(),
                            vis: PureVis::Public,
                            name: f.name.clone(),
                            ty: f.ty.clone(),
                        })
                        .collect(),
                ),
                PureFields::Tuple(types) => PureFields::Tuple(types.clone()),
                PureFields::Unit => PureFields::Unit,
            };

            let new_struct = PureStruct {
                attrs: Vec::new(),
                vis: PureVis::Public,
                name: variant.name.clone(),
                generics: PureGenerics::default(),
                fields: struct_fields,
            };

            let struct_path = match parent_path.child(&variant.name) {
                Ok(path) => path,
                Err(_) => continue,
            };

            if ctx
                .register_with_ast(
                    struct_path.clone(),
                    SymbolKind::Struct,
                    PureItem::Struct(new_struct),
                )
                .is_some()
            {
                changes += 1;
            }

            // Create impl Trait for struct with method implementations
            let impl_items: Vec<PureImplItem> = enum_methods
                .iter()
                .map(|f| {
                    // Create method implementation with todo!() body
                    let impl_fn = PureFn {
                        attrs: Vec::new(),
                        vis: PureVis::Private, // Trait impl methods don't have visibility
                        is_async: f.is_async,
                        is_async_inferred: f.is_async_inferred,
                        is_const: f.is_const,
                        is_unsafe: f.is_unsafe,
                        abi: None,
                        name: f.name.clone(),
                        generics: f.generics.clone(),
                        params: f.params.clone(),
                        ret: f.ret.clone(),
                        body: PureBlock {
                            stmts: vec![PureStmt::Expr(PureExpr::Macro {
                                name: "todo".to_string(),
                                delimiter: MacroDelimiter::Paren,
                                tokens: format!("\"{}::{}::{}\"", trait_name, variant.name, f.name),
                            })],
                        },
                    };
                    PureImplItem::Fn(impl_fn)
                })
                .collect();

            let trait_impl = PureImpl {
                attrs: Vec::new(),
                generics: PureGenerics::default(),
                is_unsafe: false,
                trait_: Some(trait_name.to_string()),
                self_ty: variant.name.clone(),
                items: impl_items,
            };

            let impl_name = format!("<impl {} for {}>", trait_name, variant.name);
            let impl_path = match parent_path.child(&impl_name) {
                Ok(path) => path,
                Err(_) => continue,
            };

            if ctx
                .register_with_ast(impl_path, SymbolKind::Impl, PureItem::Impl(trait_impl))
                .is_some()
            {
                changes += 1;
            }
        }

        // Step 4: Replace usage sites (EnumName::VariantName -> VariantName)
        // MarkerOnly: Do NOT replace usage sites - enum remains as the concrete type
        let usage_changes = match self.strategy {
            EnumToTraitStrategy::MarkerOnly => 0, // Keep enum usages as-is
            _ => replace_enum_usages(ctx, &enum_name, &variant_names),
        };
        changes += usage_changes;

        // Step 5: Replace type annotations based on strategy
        // Note: MarkerOnly does NOT replace types - the enum remains as the concrete type
        let type_changes = match self.strategy {
            EnumToTraitStrategy::Dynamic => {
                // Replace `EnumName` with `Box<dyn TraitName>`
                replace_type_annotations(ctx, &enum_name, trait_name, TypeReplacement::BoxDyn)
            }
            EnumToTraitStrategy::Static => {
                // Replace `EnumName` with `impl TraitName` (falls back to Box<dyn> for fields)
                replace_type_annotations(ctx, &enum_name, trait_name, TypeReplacement::ImplTrait)
            }
            EnumToTraitStrategy::Generic => {
                // Replace `EnumName` with generic type parameter, add generics to containers
                replace_type_annotations(ctx, &enum_name, trait_name, TypeReplacement::Generic)
            }
            EnumToTraitStrategy::MarkerOnly => {
                // No type replacement - enum remains as the concrete type
                0
            }
        };
        changes += type_changes;

        // Step 6: Handle match expressions based on match_handling
        let match_changes = match self.match_handling {
            MatchHandling::WarnOnly => {
                // TODO: Emit warnings for match expressions that need manual migration
                // For now, just count them for reporting
                count_match_expressions(ctx, &enum_name)
            }
            MatchHandling::Downcast => {
                // TODO: Convert match to downcast-based dispatch
                // This requires adding Any bound to trait
                0
            }
            MatchHandling::BlockOnMatch => {
                // This should have been checked before execution
                // If we're here, there were no match expressions
                0
            }
        };
        // Note: match_changes is informational, not counted as changes

        // Step 7: Optionally remove the original enum and its inherent impl
        // MarkerOnly strategy: NEVER remove enum (types still reference it)
        // Other strategies: remove if remove_enum is true (skip if already removed in step 1.5)
        let should_remove = match self.strategy {
            EnumToTraitStrategy::MarkerOnly => false, // Never remove for MarkerOnly
            _ => self.remove_enum && !enum_removed_early,
        };
        if should_remove {
            ctx.remove_symbol(enum_id);
            changes += 1;

            // Also remove the enum's inherent impl block
            if let Some(impl_id) = enum_impl_id {
                ctx.remove_symbol(impl_id);
                changes += 1;
            }
        }

        let strategy_desc = match self.strategy {
            EnumToTraitStrategy::Dynamic => " with Box<dyn>",
            EnumToTraitStrategy::Static => " with impl Trait",
            EnumToTraitStrategy::Generic => " with generics",
            EnumToTraitStrategy::MarkerOnly => " (marker only)",
        };

        let match_warning = if match_changes > 0 {
            format!(
                " ({} match expression(s) need manual migration)",
                match_changes
            )
        } else {
            String::new()
        };

        // Track if enum was actually removed (either early or in step 7)
        let enum_actually_removed = enum_removed_early || should_remove;

        MutationResult {
            mutation_type: self.mutation_type().to_string(),
            changes,
            description: format!(
                "Converted enum '{}' to trait '{}' with {} variants{}{}{}",
                enum_name,
                trait_name,
                variant_names.len(),
                strategy_desc,
                if enum_actually_removed {
                    " (enum removed)"
                } else {
                    ""
                },
                match_warning
            ),
        }
    }
}

/// Type replacement strategy
enum TypeReplacement {
    /// Replace with `Box<dyn TraitName>`
    BoxDyn,
    /// Replace with `impl TraitName`
    ImplTrait,
    /// Replace with generic type parameter `T` (requires adding generics to container)
    Generic,
}

/// Replace type annotations in functions, structs, and impl blocks
fn replace_type_annotations(
    ctx: &mut ASTMutationContext,
    enum_name: &str,
    trait_name: &str,
    replacement: TypeReplacement,
) -> usize {
    let mut changes = 0;

    // Collect all symbols to iterate
    let symbol_ids: Vec<_> = ctx.symbol_registry.iter().map(|(id, _)| id).collect();

    for symbol_id in symbol_ids {
        let item = match ctx.ast_registry.get(symbol_id) {
            Some(item) => item.clone(),
            None => continue,
        };

        let updated_item = match item {
            PureItem::Fn(mut f) => {
                let fn_changes = replace_types_in_fn(&mut f, enum_name, trait_name, &replacement);
                if fn_changes > 0 {
                    changes += fn_changes;
                    Some(PureItem::Fn(f))
                } else {
                    None
                }
            }
            PureItem::Struct(mut s) => {
                // For struct fields, impl Trait is not allowed in Rust
                // Fall back to Box<dyn Trait> for Static strategy (but keep Generic as-is)
                let field_replacement = match replacement {
                    TypeReplacement::ImplTrait => &TypeReplacement::BoxDyn,
                    _ => &replacement,
                };
                let struct_changes = replace_types_in_fields(
                    &mut s.fields,
                    enum_name,
                    trait_name,
                    field_replacement,
                );
                if struct_changes > 0 {
                    // For Generic strategy, add type parameter to struct
                    if matches!(replacement, TypeReplacement::Generic) {
                        add_generic_param(&mut s.generics, trait_name);
                    }
                    changes += struct_changes;
                    Some(PureItem::Struct(s))
                } else {
                    None
                }
            }
            PureItem::Impl(mut imp) => {
                let mut impl_changed = false;
                for item in &mut imp.items {
                    if let PureImplItem::Fn(ref mut f) = item {
                        if replace_types_in_fn(f, enum_name, trait_name, &replacement) > 0 {
                            impl_changed = true;
                        }
                    }
                }
                if impl_changed {
                    changes += 1;
                    Some(PureItem::Impl(imp))
                } else {
                    None
                }
            }
            PureItem::Trait(mut t) => {
                let mut trait_changed = false;
                for item in &mut t.items {
                    if let PureTraitItem::Fn(ref mut f) = item {
                        if replace_types_in_fn(f, enum_name, trait_name, &replacement) > 0 {
                            trait_changed = true;
                        }
                    }
                }
                if trait_changed {
                    changes += 1;
                    Some(PureItem::Trait(t))
                } else {
                    None
                }
            }
            _ => None,
        };

        if let Some(new_item) = updated_item {
            ctx.set_ast(symbol_id, new_item);
        }
    }

    changes
}

/// Replace types in a function signature
fn replace_types_in_fn(
    f: &mut PureFn,
    enum_name: &str,
    trait_name: &str,
    replacement: &TypeReplacement,
) -> usize {
    let mut changes = 0;

    // Replace in parameters
    for param in &mut f.params {
        if let PureParam::Typed { ty, .. } = param {
            if replace_type(ty, enum_name, trait_name, replacement) {
                changes += 1;
            }
        }
    }

    // Replace in return type
    if let Some(ref mut ret) = f.ret {
        if replace_type(ret, enum_name, trait_name, replacement) {
            changes += 1;
        }
    }

    // For Generic strategy, add type parameter if changes were made
    if changes > 0 && matches!(replacement, TypeReplacement::Generic) {
        add_generic_param(&mut f.generics, trait_name);
    }

    changes
}

/// Replace types in struct fields
fn replace_types_in_fields(
    fields: &mut PureFields,
    enum_name: &str,
    trait_name: &str,
    replacement: &TypeReplacement,
) -> usize {
    let mut changes = 0;

    match fields {
        PureFields::Named(named_fields) => {
            for field in named_fields {
                if replace_type(&mut field.ty, enum_name, trait_name, replacement) {
                    changes += 1;
                }
            }
        }
        PureFields::Tuple(types) => {
            for ty in types {
                if replace_type(ty, enum_name, trait_name, replacement) {
                    changes += 1;
                }
            }
        }
        PureFields::Unit => {}
    }

    changes
}

/// Add generic type parameter `T: TraitName` to generics
fn add_generic_param(generics: &mut PureGenerics, trait_name: &str) {
    // Check if T already exists
    let has_t = generics
        .params
        .iter()
        .any(|p| matches!(p, PureGenericParam::Type { name, .. } if name == "T"));

    if !has_t {
        generics.params.push(PureGenericParam::Type {
            name: "T".to_string(),
            bounds: vec![trait_name.to_string()],
        });
    }
}

/// Replace a type if it matches the enum name
fn replace_type(
    ty: &mut PureType,
    enum_name: &str,
    trait_name: &str,
    replacement: &TypeReplacement,
) -> bool {
    match ty {
        PureType::Path(path) => {
            let type_name = path.split("::").last().unwrap_or(path);

            // Check for exact match (e.g., "Filter")
            if type_name == enum_name || path == enum_name {
                *ty = match replacement {
                    TypeReplacement::BoxDyn => PureType::Path(format!("Box<dyn {}>", trait_name)),
                    TypeReplacement::ImplTrait => PureType::ImplTrait(vec![trait_name.to_string()]),
                    TypeReplacement::Generic => {
                        // Use generic type parameter (caller adds generics to container)
                        PureType::Path("T".to_string())
                    }
                };
                return true;
            }

            // Check for generic types containing the enum (e.g., "Option<Filter>", "Vec<Filter>")
            // Replace enum name within generic arguments
            if path.contains('<') && path.contains(enum_name) {
                let replacement_str = match replacement {
                    TypeReplacement::BoxDyn => format!("Box<dyn {}>", trait_name),
                    TypeReplacement::ImplTrait => format!("impl {}", trait_name),
                    TypeReplacement::Generic => "T".to_string(),
                };

                // Simple replacement: replace "EnumName" with the replacement type
                // This handles cases like Option<Filter> -> Option<Box<dyn Filter>>
                let new_path = replace_type_in_generic_path(path, enum_name, &replacement_str);
                if new_path != *path {
                    *path = new_path;
                    return true;
                }
            }

            false
        }
        PureType::Ref { ty: inner, .. } => replace_type(inner, enum_name, trait_name, replacement),
        PureType::Tuple(types) => {
            let mut changed = false;
            for t in types {
                if replace_type(t, enum_name, trait_name, replacement) {
                    changed = true;
                }
            }
            changed
        }
        PureType::Array { ty: inner, .. } => {
            replace_type(inner, enum_name, trait_name, replacement)
        }
        PureType::Slice(inner) => replace_type(inner, enum_name, trait_name, replacement),
        PureType::Fn { params, ret } => {
            let mut changed = false;
            for p in params {
                if replace_type(p, enum_name, trait_name, replacement) {
                    changed = true;
                }
            }
            if let Some(ref mut r) = ret {
                if replace_type(r, enum_name, trait_name, replacement) {
                    changed = true;
                }
            }
            changed
        }
        _ => false,
    }
}

/// Replace enum type within a generic path string
/// e.g., "Option<Filter>" -> "Option<Box<dyn Filter>>"
fn replace_type_in_generic_path(path: &str, enum_name: &str, replacement: &str) -> String {
    // Find positions where enum_name appears as a type argument
    // We need to be careful to only replace complete type names, not substrings
    let mut result = String::new();
    let chars = path.chars().peekable();
    let mut current_word = String::new();

    for c in chars {
        if c.is_alphanumeric() || c == '_' {
            current_word.push(c);
        } else {
            // Check if current_word matches enum_name
            if current_word == enum_name {
                result.push_str(replacement);
            } else {
                result.push_str(&current_word);
            }
            current_word.clear();
            result.push(c);
        }
    }

    // Handle trailing word
    if current_word == enum_name {
        result.push_str(replacement);
    } else {
        result.push_str(&current_word);
    }

    result
}

/// Count match expressions on the enum (for warning purposes)
fn count_match_expressions(ctx: &ASTMutationContext, enum_name: &str) -> usize {
    let mut count = 0;

    let fn_ids: Vec<_> = ctx
        .symbol_registry
        .iter()
        .filter(|(id, _)| matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Function)))
        .map(|(id, _)| id)
        .collect();

    for fn_id in fn_ids {
        if let Some(PureItem::Fn(func)) = ctx.ast_registry.get(fn_id) {
            count += count_matches_in_block(&func.body, enum_name);
        }
    }

    count
}

fn count_matches_in_block(block: &PureBlock, enum_name: &str) -> usize {
    let mut count = 0;
    for stmt in &block.stmts {
        count += count_matches_in_stmt(stmt, enum_name);
    }
    count
}

fn count_matches_in_stmt(stmt: &PureStmt, enum_name: &str) -> usize {
    match stmt {
        PureStmt::Local { init, .. } => {
            if let Some(expr) = init {
                count_matches_in_expr(expr, enum_name)
            } else {
                0
            }
        }
        PureStmt::Semi(expr) | PureStmt::Expr(expr) => count_matches_in_expr(expr, enum_name),
        PureStmt::Item(_) => 0,
    }
}

fn count_matches_in_expr(expr: &PureExpr, enum_name: &str) -> usize {
    match expr {
        PureExpr::Match {
            expr: scrutinee,
            arms,
        } => {
            let mut count = count_matches_in_expr(scrutinee, enum_name);

            // Check if any arm pattern matches our enum
            for arm in arms {
                if pattern_references_enum(&arm.pattern, enum_name) {
                    count += 1;
                    break; // Count this match once
                }
            }

            // Recurse into arm bodies
            for arm in arms {
                count += count_matches_in_expr(&arm.body, enum_name);
            }
            count
        }
        PureExpr::If {
            cond,
            then_branch,
            else_branch,
        } => {
            let mut count = count_matches_in_expr(cond, enum_name);
            count += count_matches_in_block(then_branch, enum_name);
            if let Some(else_expr) = else_branch {
                count += count_matches_in_expr(else_expr, enum_name);
            }
            count
        }
        PureExpr::Block { block, .. } => count_matches_in_block(block, enum_name),
        PureExpr::Call { func, args, .. } => {
            let mut count = count_matches_in_expr(func, enum_name);
            for arg in args {
                count += count_matches_in_expr(arg, enum_name);
            }
            count
        }
        PureExpr::MethodCall { receiver, args, .. } => {
            let mut count = count_matches_in_expr(receiver, enum_name);
            for arg in args {
                count += count_matches_in_expr(arg, enum_name);
            }
            count
        }
        PureExpr::Closure { body, .. } => count_matches_in_expr(body, enum_name),
        PureExpr::Loop { body: block, .. } => count_matches_in_block(block, enum_name),
        PureExpr::While { cond, body, .. } => {
            count_matches_in_expr(cond, enum_name) + count_matches_in_block(body, enum_name)
        }
        PureExpr::For { expr, body, .. } => {
            count_matches_in_expr(expr, enum_name) + count_matches_in_block(body, enum_name)
        }
        _ => 0,
    }
}

fn pattern_references_enum(pattern: &PurePattern, enum_name: &str) -> bool {
    match pattern {
        PurePattern::Path(path) => path.starts_with(&format!("{}::", enum_name)),
        PurePattern::Struct { path, .. } => path.starts_with(&format!("{}::", enum_name)),
        PurePattern::Tuple(elements) | PurePattern::Slice(elements) => elements
            .iter()
            .any(|p| pattern_references_enum(p, enum_name)),
        PurePattern::Or(patterns) => patterns
            .iter()
            .any(|p| pattern_references_enum(p, enum_name)),
        PurePattern::Ref { pattern: inner, .. } => pattern_references_enum(inner, enum_name),
        _ => false,
    }
}

/// Replace all usages of EnumName::VariantName with VariantName in expressions
fn replace_enum_usages(
    ctx: &mut ASTMutationContext,
    enum_name: &str,
    variant_names: &[String],
) -> usize {
    let mut changes = 0;

    // Collect all function symbols to iterate
    let fn_ids: Vec<_> = ctx
        .symbol_registry
        .iter()
        .filter(|(id, _)| matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Function)))
        .map(|(id, _)| id)
        .collect();

    for fn_id in fn_ids {
        if let Some(PureItem::Fn(mut func)) = ctx.ast_registry.get(fn_id).cloned() {
            let fn_changes = replace_in_block(&mut func.body, enum_name, variant_names);
            if fn_changes > 0 {
                ctx.set_ast(fn_id, PureItem::Fn(func));
                changes += fn_changes;
            }
        }
    }

    changes
}

fn replace_in_block(block: &mut PureBlock, enum_name: &str, variant_names: &[String]) -> usize {
    let mut changes = 0;
    for stmt in &mut block.stmts {
        changes += replace_in_stmt(stmt, enum_name, variant_names);
    }
    changes
}

fn replace_in_stmt(stmt: &mut PureStmt, enum_name: &str, variant_names: &[String]) -> usize {
    match stmt {
        PureStmt::Local { init, .. } => {
            if let Some(expr) = init {
                return replace_in_expr(expr, enum_name, variant_names);
            }
            0
        }
        PureStmt::Semi(expr) | PureStmt::Expr(expr) => {
            replace_in_expr(expr, enum_name, variant_names)
        }
        PureStmt::Item(_) => 0,
    }
}

fn replace_in_expr(expr: &mut PureExpr, enum_name: &str, variant_names: &[String]) -> usize {
    match expr {
        // Check for path expressions like Status::Running
        PureExpr::Path(path) => {
            // Check if path matches EnumName::VariantName pattern
            if path.starts_with(&format!("{}::", enum_name)) {
                let variant_part = path.strip_prefix(&format!("{}::", enum_name));
                if let Some(variant) = variant_part {
                    if variant_names.contains(&variant.to_string()) {
                        // Replace EnumName::VariantName with VariantName
                        *path = variant.to_string();
                        return 1;
                    }
                }
            }
            0
        }

        // Recurse into compound expressions
        PureExpr::Call { func, args, .. } => {
            let mut changes = replace_in_expr(func, enum_name, variant_names);
            for arg in args {
                changes += replace_in_expr(arg, enum_name, variant_names);
            }
            changes
        }
        PureExpr::MethodCall { receiver, args, .. } => {
            let mut changes = replace_in_expr(receiver, enum_name, variant_names);
            for arg in args {
                changes += replace_in_expr(arg, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Binary { left, right, .. } => {
            replace_in_expr(left, enum_name, variant_names)
                + replace_in_expr(right, enum_name, variant_names)
        }
        PureExpr::Unary { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        PureExpr::If {
            cond,
            then_branch,
            else_branch,
        } => {
            let mut changes = replace_in_expr(cond, enum_name, variant_names);
            changes += replace_in_block(then_branch, enum_name, variant_names);
            if let Some(else_expr) = else_branch {
                changes += replace_in_expr(else_expr, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Match { expr, arms } => {
            let mut changes = replace_in_expr(expr, enum_name, variant_names);
            for arm in arms {
                // Replace in pattern (match arms may have Status::Running patterns)
                changes += replace_in_pattern(&mut arm.pattern, enum_name, variant_names);
                changes += replace_in_expr(&mut arm.body, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Block { block, .. } => replace_in_block(block, enum_name, variant_names),
        PureExpr::Return(Some(v)) => replace_in_expr(v, enum_name, variant_names),
        PureExpr::Return(None) => 0,
        PureExpr::Struct { fields, .. } => {
            let mut changes = 0;
            for (_, field_expr) in fields {
                changes += replace_in_expr(field_expr, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Tuple(elements) => {
            let mut changes = 0;
            for elem in elements {
                changes += replace_in_expr(elem, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Array(elements) => {
            let mut changes = 0;
            for elem in elements {
                changes += replace_in_expr(elem, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Index { expr, index, .. } => {
            replace_in_expr(expr, enum_name, variant_names)
                + replace_in_expr(index, enum_name, variant_names)
        }
        PureExpr::Field { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        PureExpr::Ref { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        PureExpr::Try(inner) => replace_in_expr(inner, enum_name, variant_names),
        PureExpr::Await(inner) => replace_in_expr(inner, enum_name, variant_names),
        PureExpr::Closure { body, .. } => replace_in_expr(body, enum_name, variant_names),
        PureExpr::Loop { body, .. } => replace_in_block(body, enum_name, variant_names),
        PureExpr::While { cond, body, .. } => {
            replace_in_expr(cond, enum_name, variant_names)
                + replace_in_block(body, enum_name, variant_names)
        }
        PureExpr::For { expr, body, .. } => {
            replace_in_expr(expr, enum_name, variant_names)
                + replace_in_block(body, enum_name, variant_names)
        }
        PureExpr::Let { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        PureExpr::Range { start, end, .. } => {
            let mut changes = 0;
            if let Some(s) = start {
                changes += replace_in_expr(s, enum_name, variant_names);
            }
            if let Some(e) = end {
                changes += replace_in_expr(e, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Cast { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        // Literals, macros, and other expressions without sub-expressions
        _ => 0,
    }
}

use ryo_source::pure::PurePattern;

fn replace_in_pattern(
    pattern: &mut PurePattern,
    enum_name: &str,
    variant_names: &[String],
) -> usize {
    match pattern {
        // Struct pattern: `Status::Running { .. }` or `Status::Running`
        PurePattern::Struct { path, fields, .. } => {
            let mut changes = 0;
            if path.starts_with(&format!("{}::", enum_name)) {
                if let Some(variant) = path.strip_prefix(&format!("{}::", enum_name)) {
                    let base_variant = variant
                        .split(|c: char| !c.is_alphanumeric() && c != '_')
                        .next()
                        .unwrap_or(variant);
                    if variant_names.contains(&base_variant.to_string()) {
                        *path = variant.to_string();
                        changes += 1;
                    }
                }
            }
            // Recurse into field patterns
            for (_, field_pattern) in fields {
                changes += replace_in_pattern(field_pattern, enum_name, variant_names);
            }
            changes
        }
        // Tuple pattern: recurse into elements
        PurePattern::Tuple(elements) | PurePattern::Slice(elements) => {
            let mut changes = 0;
            for elem in elements {
                changes += replace_in_pattern(elem, enum_name, variant_names);
            }
            changes
        }
        // Path pattern: simple enum variant like `Status::Running`
        PurePattern::Path(path) => {
            if path.starts_with(&format!("{}::", enum_name)) {
                if let Some(variant) = path.strip_prefix(&format!("{}::", enum_name)) {
                    if variant_names.contains(&variant.to_string()) {
                        *path = variant.to_string();
                        return 1;
                    }
                }
            }
            0
        }
        // Reference pattern: recurse
        PurePattern::Ref { pattern: inner, .. } => {
            replace_in_pattern(inner, enum_name, variant_names)
        }
        // Or pattern: multiple alternatives
        PurePattern::Or(patterns) => {
            let mut changes = 0;
            for p in patterns {
                changes += replace_in_pattern(p, enum_name, variant_names);
            }
            changes
        }
        // Other patterns don't need replacement
        _ => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::ASTMutationEngine;
    use ryo_analysis::testing::ContextBuilder;

    #[test]
    fn test_v2_extract_trait() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
struct Foo {
    value: i32,
}

impl Foo {
    fn get_value(&self) -> i32 {
        self.value
    }

    fn set_value(&mut self, v: i32) {
        self.value = v;
    }

    fn helper(&self) {}
}
"#,
            )
            .build();

        // Find the inherent impl's SymbolId
        let impl_id = ctx
            .registry
            .iter()
            .find(|(id, _path)| {
                if !matches!(ctx.registry.kind(*id), Some(SymbolKind::Impl)) {
                    return false;
                }
                if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(*id) {
                    imp.trait_.is_none() && imp.self_ty == "Foo"
                } else {
                    false
                }
            })
            .map(|(id, _)| id)
            .expect("Should find impl Foo");

        let mutation = ExtractTraitMutation::new(impl_id, "ValueAccessor")
            .with_methods(vec!["get_value".to_string(), "set_value".to_string()]);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("ExtractTrait result: {:?}", result.result);
        // Should create trait + trait impl + update inherent impl
        assert!(result.result.changes >= 2, "Expected at least 2 changes");
    }

    #[test]
    fn test_v2_inline_trait() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
struct Foo;

trait Greet {
    fn greet(&self) -> String;
}

impl Greet for Foo {
    fn greet(&self) -> String {
        "Hello".to_string()
    }
}
"#,
            )
            .build();

        // Find the trait's SymbolId
        let trait_id = ctx
            .registry
            .iter()
            .find(|(id, _path)| matches!(ctx.registry.kind(*id), Some(SymbolKind::Trait)))
            .map(|(id, _)| id)
            .expect("Should find trait Greet");

        let mutation = InlineTraitMutation::new(trait_id, "Foo");
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("InlineTrait result: {:?}", result.result);
        // Should move method to inherent impl + remove trait impl + remove trait
        assert!(result.result.changes >= 2, "Expected at least 2 changes");
    }

    #[test]
    fn test_v2_inline_trait_keep_trait() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
struct Foo;

trait Greet {
    fn greet(&self) -> String;
}

impl Greet for Foo {
    fn greet(&self) -> String {
        "Hello".to_string()
    }
}
"#,
            )
            .build();

        // Find the trait's SymbolId
        let trait_id = ctx
            .registry
            .iter()
            .find(|(id, _path)| matches!(ctx.registry.kind(*id), Some(SymbolKind::Trait)))
            .map(|(id, _)| id)
            .expect("Should find trait Greet");

        let mutation = InlineTraitMutation::new(trait_id, "Foo").keep_trait();
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("InlineTrait (keep_trait) result: {:?}", result.result);
        // Should move method + remove trait impl, but keep trait definition
        assert!(result.result.changes >= 2, "Expected at least 2 changes");
    }

    #[test]
    fn test_v2_enum_to_trait_dynamic_strategy() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Status {
    Running,
    Stopped,
}

fn process(status: Status) -> Status {
    status
}

struct Config {
    current_status: Status,
}
"#,
            )
            .build();

        // Find the enum symbol id
        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Status" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Status' should exist");

        let mutation = EnumToTraitMutation::from_symbol_id(enum_id)
            .with_strategy(EnumToTraitStrategy::Dynamic);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("EnumToTrait (Dynamic) result: {:?}", result.result);
        // Should create: trait, 2 structs, 2 impls, type replacements, enum removal
        assert!(result.result.changes >= 5, "Expected at least 5 changes");
        assert!(
            result.result.description.contains("Box<dyn>"),
            "Should mention Box<dyn> strategy"
        );
    }

    #[test]
    fn test_v2_enum_to_trait_static_strategy() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Filter {
    Active,
    Inactive,
}

fn apply_filter(filter: Filter) {
    let _ = filter;
}
"#,
            )
            .build();

        // Find the enum symbol id
        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Filter" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Filter' should exist");

        let mutation =
            EnumToTraitMutation::from_symbol_id(enum_id).with_strategy(EnumToTraitStrategy::Static);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("EnumToTrait (Static) result: {:?}", result.result);
        // Should create: trait, 2 structs, 2 impls, type replacements, enum removal
        assert!(result.result.changes >= 5, "Expected at least 5 changes");
        assert!(
            result.result.description.contains("impl Trait"),
            "Should mention impl Trait strategy"
        );
    }

    #[test]
    fn test_v2_enum_to_trait_marker_only_strategy() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Mode {
    Fast,
    Slow,
}

fn get_mode() -> Mode {
    Mode::Fast
}
"#,
            )
            .build();

        // Find the enum symbol id
        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Mode" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Mode' should exist");

        let mutation = EnumToTraitMutation::from_symbol_id(enum_id)
            .with_strategy(EnumToTraitStrategy::MarkerOnly);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("EnumToTrait (MarkerOnly) result: {:?}", result.result);
        // Should create: trait, 2 structs, 2 impls, enum removal
        // But no type replacements
        assert!(result.result.changes >= 5, "Expected at least 5 changes");
        assert!(
            result.result.description.contains("marker only"),
            "Should mention marker only strategy"
        );
    }

    #[test]
    fn test_v2_enum_to_trait_generic_strategy() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Status {
    Running,
    Stopped,
}

fn process(status: Status) -> Status {
    status
}

struct Config {
    current_status: Status,
}
"#,
            )
            .build();

        // Find the enum symbol id
        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Status" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Status' should exist");

        let mutation = EnumToTraitMutation::from_symbol_id(enum_id)
            .with_strategy(EnumToTraitStrategy::Generic);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("EnumToTrait (Generic) result: {:?}", result.result);
        // Should create: trait, 2 structs, 2 impls, type replacements with generics, enum removal
        assert!(result.result.changes >= 5, "Expected at least 5 changes");
        assert!(
            result.result.description.contains("generics"),
            "Should mention generics strategy"
        );
    }
}