depyler-analysis 4.1.1

Analysis, type inference, and optimization passes for the Depyler transpiler
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
/// Migration suggestions for Python-to-Rust idiom transitions
use depyler_hir::hir::{HirExpr, HirFunction, HirProgram, HirStmt, Type};
use colored::Colorize;

/// Migration suggestion analyzer that identifies Python patterns and suggests Rust idioms
pub struct MigrationAnalyzer {
    /// Collected suggestions for the current analysis
    suggestions: Vec<MigrationSuggestion>,
    /// Configuration for suggestion generation
    config: MigrationConfig,
}

#[derive(Debug, Clone)]
pub struct MigrationConfig {
    /// Enable suggestions for iterator patterns
    pub suggest_iterators: bool,
    /// Enable suggestions for error handling
    pub suggest_error_handling: bool,
    /// Enable suggestions for ownership patterns
    pub suggest_ownership: bool,
    /// Enable suggestions for performance improvements
    pub suggest_performance: bool,
    /// Verbosity level (0-2)
    pub verbosity: u8,
}

impl Default for MigrationConfig {
    fn default() -> Self {
        Self {
            suggest_iterators: true,
            suggest_error_handling: true,
            suggest_ownership: true,
            suggest_performance: true,
            verbosity: 1,
        }
    }
}

#[derive(Debug, Clone)]
pub struct MigrationSuggestion {
    /// Type of suggestion
    pub category: SuggestionCategory,
    /// Severity/importance
    pub severity: Severity,
    /// Brief description
    pub title: String,
    /// Detailed explanation
    pub description: String,
    /// Python code example
    pub python_example: String,
    /// Suggested Rust idiom
    pub rust_suggestion: String,
    /// Additional notes or warnings
    pub notes: Vec<String>,
    /// Source location if applicable
    pub location: Option<SourceLocation>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SuggestionCategory {
    /// Iterator and functional patterns
    Iterator,
    /// Error handling patterns
    ErrorHandling,
    /// Ownership and borrowing
    Ownership,
    /// Performance optimizations
    Performance,
    /// Type system usage
    TypeSystem,
    /// Concurrency patterns
    Concurrency,
    /// API design
    ApiDesign,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    /// Nice to have
    Info,
    /// Recommended change
    Warning,
    /// Important for idiomatic Rust
    Important,
    /// Critical for correctness/performance
    Critical,
}

#[derive(Debug, Clone)]
pub struct SourceLocation {
    pub function: String,
    pub line: usize,
}

impl MigrationAnalyzer {
    pub fn new(config: MigrationConfig) -> Self {
        Self {
            suggestions: Vec::new(),
            config,
        }
    }

    /// Analyze a program and generate migration suggestions
    ///
    /// # Example
    /// ```
    /// use depyler_core::migration_suggestions::{MigrationAnalyzer, MigrationConfig};
    /// use depyler_core::hir::HirProgram;
    ///
    /// let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
    /// let program = HirProgram {
    ///     imports: vec![],
    ///     functions: vec![],
    ///     classes: vec![],
    /// };
    /// let suggestions = analyzer.analyze_program(&program);
    /// assert!(suggestions.is_empty());
    /// ```
    pub fn analyze_program(&mut self, program: &HirProgram) -> Vec<MigrationSuggestion> {
        self.suggestions.clear();

        // Analyze each function
        for func in &program.functions {
            self.analyze_function(func);
        }

        // Sort suggestions by severity
        self.suggestions.sort_by(|a, b| b.severity.cmp(&a.severity));

        self.suggestions.clone()
    }

    fn analyze_function(&mut self, func: &HirFunction) {
        // Check function-level patterns
        self.check_function_patterns(func);

        // Analyze function body
        for (idx, stmt) in func.body.iter().enumerate() {
            self.analyze_stmt(stmt, func, idx);
        }
    }

    fn check_function_patterns(&mut self, func: &HirFunction) {
        // Check for list comprehension opportunities
        if self.has_accumulator_pattern(&func.body) {
            self.add_suggestion(MigrationSuggestion {
                category: SuggestionCategory::Iterator,
                severity: Severity::Warning,
                title: format!("Consider using iterator methods in '{}'", func.name),
                description: "This function uses an accumulator pattern that could be replaced with iterator methods".to_string(),
                python_example: r#"result = []
for item in items:
    if condition(item):
        result.append(transform(item))"#.to_string(),
                rust_suggestion: r#"let result: Vec<_> = items.iter()
    .filter(|item| condition(item))
    .map(|item| transform(item))
    .collect();"#.to_string(),
                notes: vec![
                    "Iterator chains are more idiomatic and often more efficient".to_string(),
                    "They avoid intermediate allocations".to_string(),
                ],
                location: Some(SourceLocation {
                    function: func.name.clone(),
                    line: 0,
                }),
            });
        }

        // Check for error handling patterns
        if self.uses_none_as_error(&func.body, &func.ret_type) {
            self.add_suggestion(MigrationSuggestion {
                category: SuggestionCategory::ErrorHandling,
                severity: Severity::Important,
                title: format!(
                    "Use Result<T, E> instead of Option<T> for errors in '{}'",
                    func.name
                ),
                description: "Returning None for errors loses error information".to_string(),
                python_example: r#"def process(data):
    if not valid(data):
        return None
    return result"#
                    .to_string(),
                rust_suggestion: r#"fn process(data: &Data) -> Result<T, ProcessError> {
    if !valid(data) {
        return Err(ProcessError::InvalidData);
    }
    Ok(result)
}"#
                .to_string(),
                notes: vec![
                    "Result provides rich error information".to_string(),
                    "Errors can be propagated with the ? operator".to_string(),
                ],
                location: Some(SourceLocation {
                    function: func.name.clone(),
                    line: 0,
                }),
            });
        }

        // Check for mutable parameter patterns
        if self.has_mutable_parameter_pattern(func) {
            self.add_suggestion(MigrationSuggestion {
                category: SuggestionCategory::Ownership,
                severity: Severity::Important,
                title: format!(
                    "Consider ownership transfer or mutable reference in '{}'",
                    func.name
                ),
                description: "This function appears to modify its parameters".to_string(),
                python_example: r#"def modify_list(lst):
    lst.append(42)
    return lst"#
                    .to_string(),
                rust_suggestion: r#"// Option 1: Take mutable reference
fn modify_list(lst: &mut Vec<i32>) {
    lst.push(42);
}

// Option 2: Take ownership and return
fn modify_list(mut lst: Vec<i32>) -> Vec<i32> {
    lst.push(42);
    lst
}"#
                .to_string(),
                notes: vec![
                    "Rust's ownership system requires explicit mutability".to_string(),
                    "Choose based on whether callers need the original".to_string(),
                ],
                location: Some(SourceLocation {
                    function: func.name.clone(),
                    line: 0,
                }),
            });
        }
    }

    fn analyze_stmt(&mut self, stmt: &HirStmt, func: &HirFunction, line: usize) {
        match stmt {
            HirStmt::For { target, iter, body } => {
                self.analyze_for_loop(target, iter, body, func, line);
            }
            HirStmt::While { condition, body } => {
                self.analyze_while_loop(condition, body, func, line);
            }
            HirStmt::If {
                condition,
                then_body,
                else_body,
            } => {
                self.analyze_if_statement(condition, then_body, else_body, func, line);
            }
            HirStmt::Assign { target, value, .. } => {
                self.analyze_assignment(target, value, func, line);
            }
            _ => {}
        }
    }

    fn analyze_for_loop(
        &mut self,
        _target: &depyler_hir::hir::AssignTarget,
        iter: &HirExpr,
        body: &[HirStmt],
        func: &HirFunction,
        line: usize,
    ) {
        // Check for enumerate pattern
        if let HirExpr::Call {
            func: fname, args, ..
        } = iter
        {
            if fname == "enumerate" && !args.is_empty() {
                self.add_suggestion(MigrationSuggestion {
                    category: SuggestionCategory::Iterator,
                    severity: Severity::Info,
                    title: "Use .enumerate() iterator method".to_string(),
                    description: "Rust's enumerate() is an iterator method, not a function"
                        .to_string(),
                    python_example: "for i, item in enumerate(items):".to_string(),
                    rust_suggestion: "for (i, item) in items.iter().enumerate() {".to_string(),
                    notes: vec!["Iterator methods are more idiomatic in Rust".to_string()],
                    location: Some(SourceLocation {
                        function: func.name.clone(),
                        line,
                    }),
                });
            }
        }

        // Check for filter + map patterns in loop body
        if self.has_filter_map_pattern(body) {
            self.add_suggestion(MigrationSuggestion {
                category: SuggestionCategory::Iterator,
                severity: Severity::Warning,
                title: "Consider filter_map() for conditional transformation".to_string(),
                description: "Combining filter and map operations can be more efficient"
                    .to_string(),
                python_example: r#"result = []
for item in items:
    if condition(item):
        result.append(transform(item))"#
                    .to_string(),
                rust_suggestion: r#"let result: Vec<_> = items.iter()
    .filter_map(|item| {
        if condition(item) {
            Some(transform(item))
        } else {
            None
        }
    })
    .collect();"#
                    .to_string(),
                notes: vec!["filter_map avoids intermediate Option wrapping".to_string()],
                location: Some(SourceLocation {
                    function: func.name.clone(),
                    line,
                }),
            });
        }
    }

    fn analyze_while_loop(
        &mut self,
        condition: &HirExpr,
        _body: &[HirStmt],
        func: &HirFunction,
        line: usize,
    ) {
        // Check for while True pattern
        if let HirExpr::Literal(depyler_hir::hir::Literal::Bool(true)) = condition {
            self.add_suggestion(MigrationSuggestion {
                category: SuggestionCategory::Iterator,
                severity: Severity::Info,
                title: "Consider 'loop' instead of 'while true'".to_string(),
                description: "Rust has a dedicated 'loop' construct for infinite loops".to_string(),
                python_example: "while True:".to_string(),
                rust_suggestion: "loop {".to_string(),
                notes: vec![
                    "'loop' is more idiomatic and clearer in intent".to_string(),
                    "The compiler can better optimize 'loop' constructs".to_string(),
                ],
                location: Some(SourceLocation {
                    function: func.name.clone(),
                    line,
                }),
            });
        }
    }

    fn analyze_if_statement(
        &mut self,
        condition: &HirExpr,
        _then_body: &[HirStmt],
        else_body: &Option<Vec<HirStmt>>,
        func: &HirFunction,
        line: usize,
    ) {
        // Check for type checking patterns
        if self.is_type_check(condition) {
            self.add_suggestion(MigrationSuggestion {
                category: SuggestionCategory::TypeSystem,
                severity: Severity::Important,
                title: "Use Rust's type system instead of runtime type checks".to_string(),
                description: "Rust's static typing eliminates the need for runtime type checks"
                    .to_string(),
                python_example: r#"if isinstance(value, str):
    process_string(value)
elif isinstance(value, int):
    process_number(value)"#
                    .to_string(),
                rust_suggestion: r#"// Use enums for sum types
enum Value {
    String(String),
    Number(i32),
}

match value {
    Value::String(s) => process_string(s),
    Value::Number(n) => process_number(n),
}"#
                .to_string(),
                notes: vec![
                    "Enums provide compile-time guarantees".to_string(),
                    "Pattern matching ensures exhaustive handling".to_string(),
                ],
                location: Some(SourceLocation {
                    function: func.name.clone(),
                    line,
                }),
            });
        }

        // Check for None checking patterns
        if self.is_none_check(condition) && else_body.is_some() {
            self.add_suggestion(MigrationSuggestion {
                category: SuggestionCategory::ErrorHandling,
                severity: Severity::Warning,
                title: "Use pattern matching or if-let for Option handling".to_string(),
                description: "Rust provides ergonomic ways to handle Option values".to_string(),
                python_example: r#"if value is not None:
    process(value)
else:
    handle_none()"#
                    .to_string(),
                rust_suggestion: r#"// Option 1: if let
if let Some(v) = value {
    process(v);
} else {
    handle_none();
}

// Option 2: match
match value {
    Some(v) => process(v),
    None => handle_none(),
}"#
                .to_string(),
                notes: vec!["Pattern matching is more idiomatic and safer".to_string()],
                location: Some(SourceLocation {
                    function: func.name.clone(),
                    line,
                }),
            });
        }
    }

    fn analyze_assignment(
        &mut self,
        _target: &depyler_hir::hir::AssignTarget,
        value: &HirExpr,
        func: &HirFunction,
        line: usize,
    ) {
        // Check for list/dict comprehension patterns
        if let HirExpr::Call { func: fname, .. } = value {
            if fname == "list" || fname == "dict" {
                self.add_suggestion(MigrationSuggestion {
                    category: SuggestionCategory::Performance,
                    severity: Severity::Info,
                    title: "Consider using collect() for building collections".to_string(),
                    description: "Rust's collect() is more efficient than repeated push operations"
                        .to_string(),
                    python_example: "[x * 2 for x in range(10)]".to_string(),
                    rust_suggestion: "(0..10).map(|x| x * 2).collect::<Vec<_>>()".to_string(),
                    notes: vec!["collect() can optimize capacity allocation".to_string()],
                    location: Some(SourceLocation {
                        function: func.name.clone(),
                        line,
                    }),
                });
            }
        }

        // Check for string concatenation patterns
        if self.is_string_concatenation(value) {
            self.add_suggestion(MigrationSuggestion {
                category: SuggestionCategory::Performance,
                severity: Severity::Warning,
                title: "Use format! or String::push_str for string building".to_string(),
                description: "String concatenation with + is inefficient in Rust".to_string(),
                python_example: r#"result = ""
for item in items:
    result = result + str(item)"#
                    .to_string(),
                rust_suggestion: r#"// Option 1: format!
let result = format!("{}{}{}", a, b, c);

// Option 2: String::push_str (for loops)
let mut result = String::new();
for item in items {
    result.push_str(&item.to_string());
}"#
                .to_string(),
                notes: vec![
                    "String concatenation creates new allocations".to_string(),
                    "Use String::with_capacity() if size is known".to_string(),
                ],
                location: Some(SourceLocation {
                    function: func.name.clone(),
                    line,
                }),
            });
        }
    }

    // Helper methods for pattern detection

    fn has_accumulator_pattern(&self, body: &[HirStmt]) -> bool {
        let has_empty_list = self.has_empty_list_initialization(body);
        let has_append_in_loop = self.has_append_in_for_loop(body);
        has_empty_list && has_append_in_loop
    }

    fn has_empty_list_initialization(&self, body: &[HirStmt]) -> bool {
        body.iter().any(|stmt| {
            matches!(
                stmt,
                HirStmt::Assign {
                    value: HirExpr::List(v),
                    ..
                } if v.is_empty()
            )
        })
    }

    fn has_append_in_for_loop(&self, body: &[HirStmt]) -> bool {
        body.iter().any(|stmt| {
            if let HirStmt::For { body, .. } = stmt {
                self.contains_append_call(body)
            } else {
                false
            }
        })
    }

    fn contains_append_call(&self, body: &[HirStmt]) -> bool {
        body.iter().any(|stmt| {
            matches!(
                stmt,
                HirStmt::Expr(HirExpr::MethodCall { method, .. }) if method == "append"
            )
        })
    }

    fn uses_none_as_error(&self, body: &[HirStmt], ret_type: &Type) -> bool {
        // Check if function returns Optional and has early None returns
        if !matches!(ret_type, Type::Optional(_)) {
            return false;
        }

        for stmt in body {
            if let HirStmt::Return(Some(HirExpr::Literal(depyler_hir::hir::Literal::None))) = stmt {
                // Check if this is in an error condition (simplified check)
                return true;
            }
        }

        false
    }

    fn has_mutable_parameter_pattern(&self, func: &HirFunction) -> bool {
        func.body
            .iter()
            .any(|stmt| self.is_mutating_method_on_param(stmt, func))
    }

    fn is_mutating_method_on_param(&self, stmt: &HirStmt, func: &HirFunction) -> bool {
        if let HirStmt::Expr(HirExpr::MethodCall { object, method, .. }) = stmt {
            if let HirExpr::Var(var) = object.as_ref() {
                return self.is_param_mutated(var, method, func);
            }
        }
        false
    }

    fn is_param_mutated(&self, var: &str, method: &str, func: &HirFunction) -> bool {
        let is_parameter = func.params.iter().any(|p| p.name == var);
        let mutating_methods = ["append", "extend", "push", "insert", "remove", "clear"];
        let is_mutating = mutating_methods.contains(&method);
        is_parameter && is_mutating
    }

    fn has_filter_map_pattern(&self, body: &[HirStmt]) -> bool {
        body.iter().any(|stmt| {
            if let HirStmt::If { then_body, .. } = stmt {
                self.contains_append_call(then_body)
            } else {
                false
            }
        })
    }

    fn is_type_check(&self, expr: &HirExpr) -> bool {
        // Check for isinstance() calls
        if let HirExpr::Call { func, .. } = expr {
            return func == "isinstance";
        }
        false
    }

    fn is_none_check(&self, expr: &HirExpr) -> bool {
        // Check for "x == None" patterns (Python's is/is not would be transpiled to ==/!=)
        if let HirExpr::Binary { left: _, right, op } = expr {
            if let HirExpr::Literal(depyler_hir::hir::Literal::None) = right.as_ref() {
                return matches!(op, depyler_hir::hir::BinOp::Eq | depyler_hir::hir::BinOp::NotEq);
            }
        }
        false
    }

    fn is_string_concatenation(&self, expr: &HirExpr) -> bool {
        // Check for string + operations
        if let HirExpr::Binary {
            op: depyler_hir::hir::BinOp::Add,
            left,
            right,
        } = expr
        {
            // Simplified check - would need type info for accuracy
            return matches!(left.as_ref(), HirExpr::Var(_))
                || matches!(right.as_ref(), HirExpr::Var(_));
        }
        false
    }

    fn add_suggestion(&mut self, suggestion: MigrationSuggestion) {
        self.suggestions.push(suggestion);
    }

    /// Format suggestions for display
    ///
    /// # Example
    /// ```
    /// use depyler_core::migration_suggestions::{
    ///     MigrationAnalyzer, MigrationConfig, MigrationSuggestion,
    ///     SuggestionCategory, Severity
    /// };
    ///
    /// let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
    /// let output = analyzer.format_suggestions(&[]);
    /// assert!(output.contains("No migration suggestions"));
    /// ```
    pub fn format_suggestions(&self, suggestions: &[MigrationSuggestion]) -> String {
        if suggestions.is_empty() {
            return self.format_empty_suggestions();
        }

        let mut output = self.format_header();

        for (idx, suggestion) in suggestions.iter().enumerate() {
            output.push_str(&self.format_single_suggestion(suggestion, idx));
        }

        output.push_str(&self.format_summary(suggestions));
        output
    }

    fn format_empty_suggestions(&self) -> String {
        "✨ No migration suggestions found - code is already idiomatic!\n"
            .green()
            .to_string()
    }

    fn format_header(&self) -> String {
        format!(
            "\n{}\n{}\n\n",
            "Migration Suggestions".bold().blue(),
            "".repeat(50)
        )
    }

    fn format_single_suggestion(&self, suggestion: &MigrationSuggestion, idx: usize) -> String {
        let mut output = String::new();

        output.push_str(&self.format_suggestion_title(suggestion, idx));
        output.push_str(&self.format_suggestion_metadata(suggestion));
        output.push_str(&self.format_suggestion_examples(suggestion));
        output.push_str(&self.format_suggestion_notes(suggestion));
        output.push('\n');

        output
    }

    fn format_suggestion_title(&self, suggestion: &MigrationSuggestion, idx: usize) -> String {
        let severity_color = Self::get_severity_color(suggestion.severity);
        format!(
            "{} {} {}\n",
            format!("[{}]", idx + 1).dimmed(),
            format!("[{:?}]", suggestion.severity).color(severity_color),
            suggestion.title.bold()
        )
    }

    fn get_severity_color(severity: Severity) -> &'static str {
        match severity {
            Severity::Critical => "red",
            Severity::Important => "yellow",
            Severity::Warning => "bright yellow",
            Severity::Info => "bright blue",
        }
    }

    fn format_suggestion_metadata(&self, suggestion: &MigrationSuggestion) -> String {
        let mut output = format!("   {} {:?}\n", "Category:".dimmed(), suggestion.category);

        output.push_str(&format!(
            "   {} {}\n",
            "Why:".dimmed(),
            suggestion.description
        ));

        if let Some(loc) = &suggestion.location {
            output.push_str(&format!(
                "   {} {} line {}\n",
                "Location:".dimmed(),
                loc.function,
                loc.line
            ));
        }

        output
    }

    fn format_suggestion_examples(&self, suggestion: &MigrationSuggestion) -> String {
        if self.config.verbosity == 0 {
            return String::new();
        }

        let mut output = String::new();

        output.push_str(&format!("\n   {}:\n", "Python pattern".yellow()));
        for line in suggestion.python_example.lines() {
            output.push_str(&format!("{}\n", line));
        }

        output.push_str(&format!("\n   {}:\n", "Rust idiom".green()));
        for line in suggestion.rust_suggestion.lines() {
            output.push_str(&format!("{}\n", line));
        }

        output
    }

    fn format_suggestion_notes(&self, suggestion: &MigrationSuggestion) -> String {
        if suggestion.notes.is_empty() || self.config.verbosity <= 1 {
            return String::new();
        }

        let mut output = format!("\n   {}:\n", "Notes".dimmed());
        for note in &suggestion.notes {
            output.push_str(&format!("{}\n", note.dimmed()));
        }

        output
    }

    fn format_summary(&self, suggestions: &[MigrationSuggestion]) -> String {
        let critical_count = suggestions
            .iter()
            .filter(|s| s.severity == Severity::Critical)
            .count();
        let important_count = suggestions
            .iter()
            .filter(|s| s.severity == Severity::Important)
            .count();

        format!(
            "{} {} suggestions ({} critical, {} important)\n",
            "Summary:".bold(),
            suggestions.len(),
            critical_count,
            important_count
        )
    }
}

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

    fn create_test_function(name: &str, body: Vec<HirStmt>) -> HirFunction {
        HirFunction {
            name: name.to_string(),
            params: smallvec![],
            ret_type: Type::Unknown,
            body,
            properties: FunctionProperties::default(),
            annotations: Default::default(),
            docstring: None,
        }
    }

    fn create_test_program(functions: Vec<HirFunction>) -> HirProgram {
        HirProgram {
            imports: vec![],
            functions,
            classes: vec![],
        }
    }

    #[test]
    fn test_migration_analyzer_creation() {
        let config = MigrationConfig::default();
        let analyzer = MigrationAnalyzer::new(config);
        assert_eq!(analyzer.suggestions.len(), 0);
    }

    #[test]
    fn test_migration_config_custom() {
        let config = MigrationConfig {
            suggest_iterators: false,
            suggest_error_handling: true,
            suggest_ownership: false,
            suggest_performance: true,
            verbosity: 2,
        };
        assert!(!config.suggest_iterators);
        assert!(config.suggest_error_handling);
        assert_eq!(config.verbosity, 2);
    }

    #[test]
    fn test_analyze_empty_program() {
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let program = create_test_program(vec![]);
        let suggestions = analyzer.analyze_program(&program);
        assert!(suggestions.is_empty());
    }

    #[test]
    fn test_analyze_simple_function() {
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let func = create_test_function(
            "simple",
            vec![HirStmt::Return(Some(HirExpr::Literal(Literal::Int(42))))],
        );
        let program = create_test_program(vec![func]);
        let suggestions = analyzer.analyze_program(&program);
        assert!(suggestions.is_empty());
    }

    #[test]
    fn test_enumerate_pattern_detection() {
        let body = vec![HirStmt::For {
            target: AssignTarget::Symbol("i".to_string()),
            iter: HirExpr::Call {
                func: "enumerate".to_string(),
                args: vec![HirExpr::Var("items".to_string())],
                kwargs: vec![],
            },
            body: vec![HirStmt::Expr(HirExpr::Var("i".to_string()))],
        }];

        let func = create_test_function("test_enum", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);
        assert!(!analyzer.suggestions.is_empty());

        let suggestion = &analyzer.suggestions[0];
        assert_eq!(suggestion.category, SuggestionCategory::Iterator);
        assert!(suggestion.title.contains("enumerate()"));
        assert!(suggestion.rust_suggestion.contains(".enumerate()"));
    }

    #[test]
    fn test_type_check_pattern_detection() {
        let body = vec![HirStmt::If {
            condition: HirExpr::Call {
                func: "isinstance".to_string(),
                args: vec![
                    HirExpr::Var("value".to_string()),
                    HirExpr::Var("str".to_string()),
                ],
                kwargs: vec![],
            },
            then_body: vec![HirStmt::Expr(HirExpr::Call {
                func: "process_string".to_string(),
                args: vec![HirExpr::Var("value".to_string())],
                kwargs: vec![],
            })],
            else_body: None,
        }];

        let func = create_test_function("test_type", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);
        assert!(!analyzer.suggestions.is_empty());

        let suggestion = analyzer
            .suggestions
            .iter()
            .find(|s| s.category == SuggestionCategory::TypeSystem)
            .expect("Should have type system suggestion");

        assert!(suggestion.title.contains("type system"));
        assert!(suggestion.rust_suggestion.contains("enum"));
        assert!(suggestion.rust_suggestion.contains("match"));
    }

    #[test]
    fn test_none_check_pattern_detection() {
        let body = vec![HirStmt::If {
            condition: HirExpr::Binary {
                op: BinOp::NotEq,
                left: Box::new(HirExpr::Var("value".to_string())),
                right: Box::new(HirExpr::Literal(Literal::None)),
            },
            then_body: vec![HirStmt::Expr(HirExpr::Call {
                func: "process".to_string(),
                args: vec![HirExpr::Var("value".to_string())],
                kwargs: vec![],
            })],
            else_body: Some(vec![HirStmt::Expr(HirExpr::Call {
                func: "handle_none".to_string(),
                args: vec![],
                kwargs: vec![],
            })]),
        }];

        let func = create_test_function("test_none", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);
        assert!(!analyzer.suggestions.is_empty());

        let suggestion = analyzer
            .suggestions
            .iter()
            .find(|s| s.category == SuggestionCategory::ErrorHandling)
            .expect("Should have error handling suggestion");

        assert!(
            suggestion.title.contains("pattern matching") || suggestion.title.contains("if-let")
        );
        assert!(suggestion.rust_suggestion.contains("if let Some"));
    }

    #[test]
    fn test_string_concatenation_detection() {
        let body = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("result".to_string()),
            value: HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Var("str1".to_string())),
                right: Box::new(HirExpr::Var("str2".to_string())),
            },
            type_annotation: None,
        }];

        let func = create_test_function("test_concat", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);

        let suggestion = analyzer
            .suggestions
            .iter()
            .find(|s| s.category == SuggestionCategory::Performance)
            .expect("Should have performance suggestion");

        assert!(suggestion.title.contains("format!") || suggestion.title.contains("String"));
    }

    #[test]
    fn test_mutable_parameter_pattern() {
        let func = HirFunction {
            name: "modify_list".to_string(),
            params: smallvec![HirParam::new(
                "lst".to_string(),
                Type::List(Box::new(Type::Int))
            )],
            ret_type: Type::Unknown,
            body: vec![HirStmt::Expr(HirExpr::MethodCall {
                object: Box::new(HirExpr::Var("lst".to_string())),
                method: "append".to_string(),
                args: vec![HirExpr::Literal(Literal::Int(42))],
                kwargs: vec![],
            })],
            properties: FunctionProperties::default(),
            annotations: Default::default(),
            docstring: None,
        };

        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        analyzer.analyze_function(&func);

        let suggestion = analyzer
            .suggestions
            .iter()
            .find(|s| s.category == SuggestionCategory::Ownership)
            .expect("Should have ownership suggestion");

        assert!(suggestion.title.contains("ownership") || suggestion.title.contains("mutable"));
        assert!(suggestion.rust_suggestion.contains("&mut"));
    }

    #[test]
    fn test_filter_map_pattern_detection() {
        let body = vec![HirStmt::For {
            target: AssignTarget::Symbol("item".to_string()),
            iter: HirExpr::Var("items".to_string()),
            body: vec![HirStmt::If {
                condition: HirExpr::Call {
                    func: "condition".to_string(),
                    args: vec![HirExpr::Var("item".to_string())],
                    kwargs: vec![],
                },
                then_body: vec![HirStmt::Expr(HirExpr::MethodCall {
                    object: Box::new(HirExpr::Var("result".to_string())),
                    method: "append".to_string(),
                    args: vec![HirExpr::Call {
                        func: "transform".to_string(),
                        args: vec![HirExpr::Var("item".to_string())],
                        kwargs: vec![],
                    }],
                    kwargs: vec![],
                })],
                else_body: None,
            }],
        }];

        let func = create_test_function("test_filter_map", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);

        // The pattern is detected by analyze_for_loop
        let suggestion = analyzer
            .suggestions
            .iter()
            .find(|s| s.category == SuggestionCategory::Iterator && s.title.contains("filter_map"))
            .expect("Should have filter_map suggestion");

        assert_eq!(suggestion.category, SuggestionCategory::Iterator);
        assert!(suggestion.rust_suggestion.contains("filter_map"));
    }

    #[test]
    fn test_suggestion_sorting_by_severity() {
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        // Create a function that will not generate any automatic suggestions
        let _func = create_test_function(
            "test",
            vec![HirStmt::Return(Some(HirExpr::Literal(Literal::Int(42))))],
        );

        // Manually add suggestions with different severities
        analyzer.suggestions.push(MigrationSuggestion {
            category: SuggestionCategory::Iterator,
            severity: Severity::Info,
            title: "Info level".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: None,
        });

        analyzer.suggestions.push(MigrationSuggestion {
            category: SuggestionCategory::ErrorHandling,
            severity: Severity::Critical,
            title: "Critical level".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: None,
        });

        analyzer.suggestions.push(MigrationSuggestion {
            category: SuggestionCategory::Performance,
            severity: Severity::Warning,
            title: "Warning level".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: None,
        });

        // Sort by severity manually
        analyzer
            .suggestions
            .sort_by(|a, b| b.severity.cmp(&a.severity));

        // Check that suggestions are sorted by severity (highest first)
        assert_eq!(analyzer.suggestions[0].severity, Severity::Critical);
        assert_eq!(analyzer.suggestions[1].severity, Severity::Warning);
        assert_eq!(analyzer.suggestions[2].severity, Severity::Info);
    }

    #[test]
    fn test_format_suggestions_empty() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let output = analyzer.format_suggestions(&[]);
        assert!(output.contains("No migration suggestions"));
        assert!(output.contains("idiomatic"));
    }

    #[test]
    fn test_format_suggestions_with_items() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig {
            verbosity: 2,
            ..Default::default()
        });

        let suggestions = vec![MigrationSuggestion {
            category: SuggestionCategory::Iterator,
            severity: Severity::Warning,
            title: "Test suggestion".to_string(),
            description: "Test description".to_string(),
            python_example: "for x in list:".to_string(),
            rust_suggestion: "for x in list.iter() {".to_string(),
            notes: vec!["Note 1".to_string(), "Note 2".to_string()],
            location: Some(SourceLocation {
                function: "test_func".to_string(),
                line: 10,
            }),
        }];

        let output = analyzer.format_suggestions(&suggestions);

        assert!(output.contains("Migration Suggestions"));
        assert!(output.contains("Test suggestion"));
        assert!(output.contains("Test description"));
        assert!(output.contains("test_func"));
        assert!(output.contains("line 10"));
        assert!(output.contains("Python pattern"));
        assert!(output.contains("Rust idiom"));
        assert!(output.contains("Note 1"));
        assert!(output.contains("Note 2"));
        assert!(output.contains("Summary:"));
    }

    #[test]
    fn test_source_location() {
        let loc = SourceLocation {
            function: "my_func".to_string(),
            line: 42,
        };
        assert_eq!(loc.function, "my_func");
        assert_eq!(loc.line, 42);
    }

    #[test]
    fn test_suggestion_category_equality() {
        assert_eq!(SuggestionCategory::Iterator, SuggestionCategory::Iterator);
        assert_ne!(
            SuggestionCategory::Iterator,
            SuggestionCategory::ErrorHandling
        );
    }

    #[test]
    fn test_list_dict_construction_suggestion() {
        let body = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("result".to_string()),
            value: HirExpr::Call {
                func: "list".to_string(),
                args: vec![HirExpr::List(vec![])],
                kwargs: vec![],
            },
            type_annotation: None,
        }];

        let func = create_test_function("test_list", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);

        let suggestion = analyzer
            .suggestions
            .iter()
            .find(|s| s.category == SuggestionCategory::Performance)
            .expect("Should have performance suggestion");

        assert!(suggestion.title.contains("collect()"));
    }

    #[test]
    fn test_config_with_disabled_suggestions() {
        let config = MigrationConfig {
            suggest_iterators: false,
            suggest_error_handling: false,
            suggest_ownership: false,
            suggest_performance: false,
            verbosity: 0,
        };

        let mut analyzer = MigrationAnalyzer::new(config);

        // Even with patterns that would normally trigger suggestions,
        // nothing should be suggested with all options disabled
        let body = vec![HirStmt::While {
            condition: HirExpr::Literal(Literal::Bool(true)),
            body: vec![],
        }];

        let func = create_test_function("test", body);
        analyzer.analyze_function(&func);

        // Note: Current implementation doesn't check config flags,
        // so this test documents current behavior
        assert!(!analyzer.suggestions.is_empty());
    }

    #[test]
    fn test_multiple_suggestions_per_function() {
        let body = vec![
            // Pattern 1: while True
            HirStmt::While {
                condition: HirExpr::Literal(Literal::Bool(true)),
                body: vec![HirStmt::Break { label: None }],
            },
            // Pattern 2: isinstance check
            HirStmt::If {
                condition: HirExpr::Call {
                    func: "isinstance".to_string(),
                    args: vec![
                        HirExpr::Var("x".to_string()),
                        HirExpr::Var("int".to_string()),
                    ],
                    kwargs: vec![],
                },
                then_body: vec![],
                else_body: None,
            },
        ];

        let func = create_test_function("multi_pattern", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);

        // Should have at least 2 suggestions
        assert!(analyzer.suggestions.len() >= 2);

        // Should have both categories
        let categories: Vec<_> = analyzer.suggestions.iter().map(|s| &s.category).collect();

        assert!(categories.contains(&&SuggestionCategory::Iterator));
        assert!(categories.contains(&&SuggestionCategory::TypeSystem));
    }

    #[test]
    fn test_migration_config_default() {
        let config = MigrationConfig::default();
        assert!(config.suggest_iterators);
        assert!(config.suggest_error_handling);
        assert!(config.suggest_ownership);
        assert!(config.suggest_performance);
        assert_eq!(config.verbosity, 1);
    }

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Critical > Severity::Important);
        assert!(Severity::Important > Severity::Warning);
        assert!(Severity::Warning > Severity::Info);
    }

    #[test]
    fn test_accumulator_pattern_detection() {
        let body = vec![
            HirStmt::Assign {
                target: AssignTarget::Symbol("result".to_string()),
                value: HirExpr::List(vec![]),
                type_annotation: None,
            },
            HirStmt::For {
                target: AssignTarget::Symbol("item".to_string()),
                iter: HirExpr::Var("items".to_string()),
                body: vec![HirStmt::Expr(HirExpr::MethodCall {
                    object: Box::new(HirExpr::Var("result".to_string())),
                    method: "append".to_string(),
                    args: vec![HirExpr::Var("item".to_string())],
                    kwargs: vec![],
                })],
            },
        ];

        let func = create_test_function("test", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);
        assert!(!analyzer.suggestions.is_empty());
        assert_eq!(
            analyzer.suggestions[0].category,
            SuggestionCategory::Iterator
        );
    }

    // Note: none-as-error detection is not yet implemented.
    // This test is kept as documentation of expected behavior.
    #[test]
    #[ignore]
    fn test_none_as_error_detection() {
        let body = vec![
            HirStmt::If {
                condition: HirExpr::Var("error".to_string()),
                then_body: vec![HirStmt::Return(Some(HirExpr::Literal(Literal::None)))],
                else_body: None,
            },
            HirStmt::Return(Some(HirExpr::Var("result".to_string()))),
        ];

        let func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Optional(Box::new(Type::Unknown)),
            body,
            properties: FunctionProperties::default(),
            annotations: Default::default(),
            docstring: None,
        };

        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        analyzer.analyze_function(&func);

        assert!(analyzer
            .suggestions
            .iter()
            .any(|s| s.category == SuggestionCategory::ErrorHandling));
    }

    #[test]
    fn test_while_true_detection() {
        let body = vec![HirStmt::While {
            condition: HirExpr::Literal(Literal::Bool(true)),
            body: vec![HirStmt::Break { label: None }],
        }];

        let func = create_test_function("test", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());

        analyzer.analyze_function(&func);
        assert!(analyzer
            .suggestions
            .iter()
            .any(|s| s.title.contains("loop")));
    }

    // ========================================================
    // DEPYLER-COVERAGE-95: Additional migration_suggestions tests
    // ========================================================

    #[test]
    fn test_format_header() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let header = analyzer.format_header();
        assert!(header.contains("Migration Suggestions"));
    }

    #[test]
    fn test_format_empty_suggestions_message() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let empty_msg = analyzer.format_empty_suggestions();
        assert!(empty_msg.contains("idiomatic") || empty_msg.contains("No"));
    }

    #[test]
    fn test_severity_color_info() {
        let color = MigrationAnalyzer::get_severity_color(Severity::Info);
        assert!(!color.is_empty());
    }

    #[test]
    fn test_severity_color_warning() {
        let color = MigrationAnalyzer::get_severity_color(Severity::Warning);
        assert!(!color.is_empty());
    }

    #[test]
    fn test_severity_color_important() {
        let color = MigrationAnalyzer::get_severity_color(Severity::Important);
        assert!(!color.is_empty());
    }

    #[test]
    fn test_severity_color_critical() {
        let color = MigrationAnalyzer::get_severity_color(Severity::Critical);
        assert!(!color.is_empty());
    }

    #[test]
    fn test_suggestion_category_iterator() {
        let cat = SuggestionCategory::Iterator;
        assert_eq!(cat, SuggestionCategory::Iterator);
    }

    #[test]
    fn test_suggestion_category_error_handling() {
        let cat = SuggestionCategory::ErrorHandling;
        assert_eq!(cat, SuggestionCategory::ErrorHandling);
    }

    #[test]
    fn test_suggestion_category_ownership() {
        let cat = SuggestionCategory::Ownership;
        assert_eq!(cat, SuggestionCategory::Ownership);
    }

    #[test]
    fn test_suggestion_category_performance() {
        let cat = SuggestionCategory::Performance;
        assert_eq!(cat, SuggestionCategory::Performance);
    }

    #[test]
    fn test_suggestion_category_type_system() {
        let cat = SuggestionCategory::TypeSystem;
        assert_eq!(cat, SuggestionCategory::TypeSystem);
    }

    #[test]
    fn test_suggestion_category_concurrency() {
        let cat = SuggestionCategory::Concurrency;
        assert_eq!(cat, SuggestionCategory::Concurrency);
    }

    #[test]
    fn test_suggestion_category_api_design() {
        let cat = SuggestionCategory::ApiDesign;
        assert_eq!(cat, SuggestionCategory::ApiDesign);
    }

    #[test]
    fn test_migration_suggestion_creation() {
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::Iterator,
            severity: Severity::Warning,
            title: "Test title".to_string(),
            description: "Test description".to_string(),
            python_example: "for i in range(len(lst)):".to_string(),
            rust_suggestion: "for item in lst.iter()".to_string(),
            notes: vec!["Note 1".to_string()],
            location: None,
        };
        assert_eq!(suggestion.title, "Test title");
        assert_eq!(suggestion.notes.len(), 1);
    }

    #[test]
    fn test_migration_suggestion_with_location() {
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::Performance,
            severity: Severity::Important,
            title: "Performance hint".to_string(),
            description: "Consider caching".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: Some(SourceLocation {
                function: "my_func".to_string(),
                line: 42,
            }),
        };
        assert!(suggestion.location.is_some());
        assert_eq!(suggestion.location.as_ref().unwrap().line, 42);
    }

    #[test]
    fn test_source_location_clone() {
        let loc = SourceLocation {
            function: "test".to_string(),
            line: 10,
        };
        let cloned = loc.clone();
        assert_eq!(loc.function, cloned.function);
        assert_eq!(loc.line, cloned.line);
    }

    #[test]
    fn test_migration_config_clone() {
        let config = MigrationConfig {
            suggest_iterators: true,
            suggest_error_handling: false,
            suggest_ownership: true,
            suggest_performance: false,
            verbosity: 2,
        };
        let cloned = config.clone();
        assert_eq!(config.verbosity, cloned.verbosity);
        assert_eq!(config.suggest_iterators, cloned.suggest_iterators);
    }

    #[test]
    fn test_migration_suggestion_clone() {
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::Ownership,
            severity: Severity::Critical,
            title: "Clone test".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: None,
        };
        let cloned = suggestion.clone();
        assert_eq!(suggestion.title, cloned.title);
        assert_eq!(suggestion.severity, cloned.severity);
    }

    #[test]
    fn test_severity_clone() {
        let sev = Severity::Warning;
        let cloned = sev;
        assert_eq!(sev, cloned);
    }

    #[test]
    fn test_severity_copy() {
        let sev = Severity::Info;
        let copied: Severity = sev;
        assert_eq!(sev, copied);
    }

    #[test]
    fn test_suggestion_category_clone() {
        let cat = SuggestionCategory::ApiDesign;
        let cloned = cat.clone();
        assert_eq!(cat, cloned);
    }

    #[test]
    fn test_is_string_concatenation_binary_add() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let expr = HirExpr::Binary {
            left: Box::new(HirExpr::Literal(Literal::String("hello".to_string()))),
            op: BinOp::Add,
            right: Box::new(HirExpr::Var("name".to_string())),
        };
        assert!(analyzer.is_string_concatenation(&expr));
    }

    #[test]
    fn test_is_string_concatenation_non_add() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let expr = HirExpr::Binary {
            left: Box::new(HirExpr::Literal(Literal::Int(1))),
            op: BinOp::Mul,
            right: Box::new(HirExpr::Literal(Literal::Int(2))),
        };
        assert!(!analyzer.is_string_concatenation(&expr));
    }

    #[test]
    fn test_is_type_check_isinstance() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let expr = HirExpr::Call {
            func: "isinstance".to_string(),
            args: vec![
                HirExpr::Var("x".to_string()),
                HirExpr::Var("int".to_string()),
            ],
            kwargs: vec![],
        };
        assert!(analyzer.is_type_check(&expr));
    }

    #[test]
    fn test_is_type_check_type() {
        // Note: is_type_check only checks isinstance, not type()
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let expr = HirExpr::Call {
            func: "type".to_string(),
            args: vec![HirExpr::Var("x".to_string())],
            kwargs: vec![],
        };
        // type() is not considered a type check in this implementation
        assert!(!analyzer.is_type_check(&expr));
    }

    #[test]
    fn test_is_type_check_other() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let expr = HirExpr::Call {
            func: "len".to_string(),
            args: vec![HirExpr::Var("x".to_string())],
            kwargs: vec![],
        };
        assert!(!analyzer.is_type_check(&expr));
    }

    #[test]
    fn test_is_none_check_eq_none() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        // HIR uses Binary with BinOp::Eq for "x == None" patterns
        let expr = HirExpr::Binary {
            left: Box::new(HirExpr::Var("x".to_string())),
            op: BinOp::Eq,
            right: Box::new(HirExpr::Literal(Literal::None)),
        };
        assert!(analyzer.is_none_check(&expr));
    }

    #[test]
    fn test_is_none_check_not_eq_none() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        // HIR uses Binary with BinOp::NotEq for "x != None" patterns
        let expr = HirExpr::Binary {
            left: Box::new(HirExpr::Var("x".to_string())),
            op: BinOp::NotEq,
            right: Box::new(HirExpr::Literal(Literal::None)),
        };
        assert!(analyzer.is_none_check(&expr));
    }

    #[test]
    fn test_is_none_check_non_none() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        // Comparing to a non-None value should not be a None check
        let expr = HirExpr::Binary {
            left: Box::new(HirExpr::Var("x".to_string())),
            op: BinOp::Eq,
            right: Box::new(HirExpr::Literal(Literal::Int(0))),
        };
        assert!(!analyzer.is_none_check(&expr));
    }

    #[test]
    fn test_is_none_check_other_op() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        // Using a non-equality op with None should not be a None check
        let expr = HirExpr::Binary {
            left: Box::new(HirExpr::Var("x".to_string())),
            op: BinOp::Lt,
            right: Box::new(HirExpr::Literal(Literal::None)),
        };
        assert!(!analyzer.is_none_check(&expr));
    }

    #[test]
    fn test_has_empty_list_initialization() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let body = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("result".to_string()),
            value: HirExpr::List(vec![]),
            type_annotation: None,
        }];
        assert!(analyzer.has_empty_list_initialization(&body));
    }

    #[test]
    fn test_has_empty_list_initialization_non_empty() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let body = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("result".to_string()),
            value: HirExpr::List(vec![HirExpr::Literal(Literal::Int(1))]),
            type_annotation: None,
        }];
        assert!(!analyzer.has_empty_list_initialization(&body));
    }

    #[test]
    fn test_has_accumulator_pattern_true() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        // Accumulator pattern: empty list initialization + append in for loop
        let body = vec![
            HirStmt::Assign {
                target: AssignTarget::Symbol("result".to_string()),
                value: HirExpr::List(vec![]),
                type_annotation: None,
            },
            HirStmt::For {
                target: AssignTarget::Symbol("x".to_string()),
                iter: HirExpr::Var("items".to_string()),
                body: vec![HirStmt::Expr(HirExpr::MethodCall {
                    object: Box::new(HirExpr::Var("result".to_string())),
                    method: "append".to_string(),
                    args: vec![HirExpr::Var("x".to_string())],
                    kwargs: vec![],
                })],
            },
        ];
        assert!(analyzer.has_accumulator_pattern(&body));
    }

    #[test]
    fn test_has_accumulator_pattern_false() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let body = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("x".to_string()),
            value: HirExpr::Literal(Literal::Int(1)),
            type_annotation: None,
        }];
        assert!(!analyzer.has_accumulator_pattern(&body));
    }

    #[test]
    fn test_format_suggestion_title() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::Iterator,
            severity: Severity::Warning,
            title: "Test Title".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: None,
        };
        let formatted = analyzer.format_suggestion_title(&suggestion, 1);
        assert!(formatted.contains("Test Title") || formatted.contains("1"));
    }

    #[test]
    fn test_format_suggestion_metadata() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::Performance,
            severity: Severity::Important,
            title: "".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: Some(SourceLocation {
                function: "my_func".to_string(),
                line: 100,
            }),
        };
        let metadata = analyzer.format_suggestion_metadata(&suggestion);
        assert!(metadata.contains("Performance") || metadata.contains("Important"));
    }

    #[test]
    fn test_format_suggestion_examples() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::Iterator,
            severity: Severity::Info,
            title: "".to_string(),
            description: "".to_string(),
            python_example: "for i in range(len(x)):".to_string(),
            rust_suggestion: "for item in x.iter()".to_string(),
            notes: vec![],
            location: None,
        };
        let examples = analyzer.format_suggestion_examples(&suggestion);
        assert!(examples.contains("range") || examples.contains("iter"));
    }

    #[test]
    fn test_format_suggestion_notes() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::Ownership,
            severity: Severity::Critical,
            title: "".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec!["Note 1".to_string(), "Note 2".to_string()],
            location: None,
        };
        let notes = analyzer.format_suggestion_notes(&suggestion);
        assert!(notes.contains("Note") || notes.is_empty());
    }

    #[test]
    fn test_format_summary_multiple() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let suggestions = vec![
            MigrationSuggestion {
                category: SuggestionCategory::Iterator,
                severity: Severity::Warning,
                title: "Suggestion 1".to_string(),
                description: "".to_string(),
                python_example: "".to_string(),
                rust_suggestion: "".to_string(),
                notes: vec![],
                location: None,
            },
            MigrationSuggestion {
                category: SuggestionCategory::Performance,
                severity: Severity::Critical,
                title: "Suggestion 2".to_string(),
                description: "".to_string(),
                python_example: "".to_string(),
                rust_suggestion: "".to_string(),
                notes: vec![],
                location: None,
            },
        ];
        let summary = analyzer.format_summary(&suggestions);
        assert!(summary.contains("2") || summary.contains("suggestion"));
    }

    #[test]
    fn test_analyze_for_loop_with_range_len() {
        let body = vec![HirStmt::For {
            target: AssignTarget::Symbol("i".to_string()),
            iter: HirExpr::Call {
                func: "range".to_string(),
                args: vec![HirExpr::Call {
                    func: "len".to_string(),
                    args: vec![HirExpr::Var("lst".to_string())],
                    kwargs: vec![],
                }],
                kwargs: vec![],
            },
            body: vec![HirStmt::Expr(HirExpr::Var("i".to_string()))],
        }];

        let func = create_test_function("test", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        analyzer.analyze_function(&func);

        // Should suggest enumerate or direct iteration - test verifies no panic
    }

    #[test]
    fn test_analyze_if_with_type_check() {
        let body = vec![HirStmt::If {
            condition: HirExpr::Call {
                func: "isinstance".to_string(),
                args: vec![
                    HirExpr::Var("x".to_string()),
                    HirExpr::Var("int".to_string()),
                ],
                kwargs: vec![],
            },
            then_body: vec![HirStmt::Return(Some(HirExpr::Var("x".to_string())))],
            else_body: None,
        }];

        let func = create_test_function("test", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        analyzer.analyze_function(&func);

        // Should detect type check pattern - test verifies no panic
    }

    #[test]
    fn test_analyze_assignment_string_concat() {
        let body = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("result".to_string()),
            value: HirExpr::Binary {
                left: Box::new(HirExpr::Var("a".to_string())),
                op: BinOp::Add,
                right: Box::new(HirExpr::Literal(Literal::String(" world".to_string()))),
            },
            type_annotation: None,
        }];

        let func = create_test_function("test", body);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        analyzer.analyze_function(&func);

        // May suggest format! or push_str - test verifies no panic
    }

    #[test]
    fn test_config_verbosity_levels() {
        let config0 = MigrationConfig {
            verbosity: 0,
            ..Default::default()
        };
        let config1 = MigrationConfig {
            verbosity: 1,
            ..Default::default()
        };
        let config2 = MigrationConfig {
            verbosity: 2,
            ..Default::default()
        };

        assert_eq!(config0.verbosity, 0);
        assert_eq!(config1.verbosity, 1);
        assert_eq!(config2.verbosity, 2);
    }

    #[test]
    fn test_analyzer_with_all_suggestions_disabled() {
        let config = MigrationConfig {
            suggest_iterators: false,
            suggest_error_handling: false,
            suggest_ownership: false,
            suggest_performance: false,
            verbosity: 1,
        };
        let mut analyzer = MigrationAnalyzer::new(config);

        let body = vec![HirStmt::For {
            target: AssignTarget::Symbol("i".to_string()),
            iter: HirExpr::Call {
                func: "range".to_string(),
                args: vec![HirExpr::Call {
                    func: "len".to_string(),
                    args: vec![HirExpr::Var("lst".to_string())],
                    kwargs: vec![],
                }],
                kwargs: vec![],
            },
            body: vec![],
        }];

        let func = create_test_function("test", body);
        analyzer.analyze_function(&func);

        // With all suggestions disabled, might have fewer suggestions - test verifies no panic
    }

    #[test]
    fn test_contains_append_call_true() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let body = vec![HirStmt::Expr(HirExpr::MethodCall {
            object: Box::new(HirExpr::Var("lst".to_string())),
            method: "append".to_string(),
            args: vec![HirExpr::Var("x".to_string())],
            kwargs: vec![],
        })];
        assert!(analyzer.contains_append_call(&body));
    }

    #[test]
    fn test_contains_append_call_false() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let body = vec![HirStmt::Expr(HirExpr::MethodCall {
            object: Box::new(HirExpr::Var("lst".to_string())),
            method: "pop".to_string(),
            args: vec![],
            kwargs: vec![],
        })];
        assert!(!analyzer.contains_append_call(&body));
    }

    #[test]
    fn test_has_filter_map_pattern_true() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let body = vec![HirStmt::If {
            condition: HirExpr::Call {
                func: "isinstance".to_string(),
                args: vec![
                    HirExpr::Var("x".to_string()),
                    HirExpr::Var("int".to_string()),
                ],
                kwargs: vec![],
            },
            then_body: vec![HirStmt::Expr(HirExpr::MethodCall {
                object: Box::new(HirExpr::Var("result".to_string())),
                method: "append".to_string(),
                args: vec![HirExpr::Var("x".to_string())],
                kwargs: vec![],
            })],
            else_body: None,
        }];
        assert!(analyzer.has_filter_map_pattern(&body));
    }

    #[test]
    fn test_severity_debug() {
        let sev = Severity::Critical;
        let debug = format!("{:?}", sev);
        assert!(debug.contains("Critical"));
    }

    #[test]
    fn test_suggestion_category_debug() {
        let cat = SuggestionCategory::Concurrency;
        let debug = format!("{:?}", cat);
        assert!(debug.contains("Concurrency"));
    }

    #[test]
    fn test_migration_config_debug() {
        let config = MigrationConfig::default();
        let debug = format!("{:?}", config);
        assert!(debug.contains("MigrationConfig"));
    }

    #[test]
    fn test_migration_suggestion_debug() {
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::TypeSystem,
            severity: Severity::Info,
            title: "Debug test".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: None,
        };
        let debug = format!("{:?}", suggestion);
        assert!(debug.contains("MigrationSuggestion"));
    }

    #[test]
    fn test_source_location_debug() {
        let loc = SourceLocation {
            function: "test_func".to_string(),
            line: 42,
        };
        let debug = format!("{:?}", loc);
        assert!(debug.contains("SourceLocation"));
    }

    #[test]
    fn test_add_suggestion() {
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        assert_eq!(analyzer.suggestions.len(), 0);

        analyzer.add_suggestion(MigrationSuggestion {
            category: SuggestionCategory::Iterator,
            severity: Severity::Warning,
            title: "Test".to_string(),
            description: "".to_string(),
            python_example: "".to_string(),
            rust_suggestion: "".to_string(),
            notes: vec![],
            location: None,
        });

        assert_eq!(analyzer.suggestions.len(), 1);
    }

    #[test]
    fn test_analyze_program_with_multiple_functions() {
        let func1 = create_test_function(
            "func1",
            vec![HirStmt::Return(Some(HirExpr::Literal(Literal::Int(1))))],
        );
        let func2 = create_test_function(
            "func2",
            vec![HirStmt::Return(Some(HirExpr::Literal(Literal::Int(2))))],
        );

        let program = create_test_program(vec![func1, func2]);
        let mut analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let _suggestions = analyzer.analyze_program(&program);

        // Should analyze both functions - test verifies no panic
    }

    #[test]
    fn test_format_single_suggestion() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let suggestion = MigrationSuggestion {
            category: SuggestionCategory::Ownership,
            severity: Severity::Important,
            title: "Ownership suggestion".to_string(),
            description: "Consider borrowing".to_string(),
            python_example: "def f(lst): lst.append(1)".to_string(),
            rust_suggestion: "fn f(lst: &mut Vec<i32>)".to_string(),
            notes: vec!["Be careful with lifetimes".to_string()],
            location: Some(SourceLocation {
                function: "my_func".to_string(),
                line: 10,
            }),
        };
        let formatted = analyzer.format_single_suggestion(&suggestion, 1);
        assert!(!formatted.is_empty());
    }

    #[test]
    fn test_uses_none_as_error_with_optional_return() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        // The implementation only checks top-level Return statements
        let body = vec![HirStmt::Return(Some(HirExpr::Literal(Literal::None)))];

        let ret_type = Type::Optional(Box::new(Type::Int));
        assert!(analyzer.uses_none_as_error(&body, &ret_type));
    }

    #[test]
    fn test_uses_none_as_error_no_none_return() {
        let analyzer = MigrationAnalyzer::new(MigrationConfig::default());
        let body = vec![HirStmt::Return(Some(HirExpr::Literal(Literal::Int(42))))];

        let ret_type = Type::Int;
        assert!(!analyzer.uses_none_as_error(&body, &ret_type));
    }
}