phpantom_lsp 0.7.0

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

use bumpalo::Bump;
use mago_span::HasSpan;
use mago_syntax::ast::*;
use std::collections::HashMap;
use std::sync::Arc;
use tower_lsp::lsp_types::*;

use crate::Backend;
use crate::code_actions::cursor_context::{CursorContext, MemberContext, find_cursor_context};
use crate::code_actions::{CodeActionData, make_code_action_data};
use crate::completion::phpdoc::generation::enrichment_plain;
use crate::completion::resolver::Loaders;
use crate::php_type::PhpType;
use crate::scope_collector::{
    FrameKind, ScopeMap, collect_function_scope, collect_function_scope_with_kind, collect_scope,
};
use crate::types::ClassInfo;
use crate::util::{find_class_at_offset, offset_to_position, position_to_byte_offset};

// ─── Statement boundary validation ─────────────────────────────────────────

/// Check whether the selected byte range `[start, end)` covers one or
/// more complete statements.
///
/// We parse the file and walk the AST to verify that every statement
/// whose span overlaps the selection is *fully* contained within it.
/// If any statement is only partially selected, the selection is
/// invalid for extraction.
fn selection_covers_complete_statements(content: &str, start: usize, end: usize) -> bool {
    let arena = Bump::new();
    let file_id = mago_database::file::FileId::new("extract_fn_validate");
    let program = mago_syntax::parser::parse_file_content(&arena, file_id, content);

    // Find the enclosing function/method body statements.
    let body_stmts = find_enclosing_body_statements(&program.statements, start as u32);
    if body_stmts.is_empty() {
        return false;
    }

    let mut found_any = false;
    for stmt in &body_stmts {
        let span = stmt.span();
        let stmt_start = span.start.offset as usize;
        let stmt_end = span.end.offset as usize;

        // Statement fully outside the selection — fine, skip it.
        if stmt_end <= start || stmt_start >= end {
            continue;
        }

        // Statement overlaps the selection — it must be fully contained.
        if stmt_start < start || stmt_end > end {
            return false;
        }

        found_any = true;
    }

    found_any
}

/// Collect references to top-level statements in the enclosing
/// function/method body that contains `offset`.
///
/// Returns byte ranges `(start, end)` for each direct child statement.
fn find_enclosing_body_statements<'a>(
    statements: &'a Sequence<'a, Statement<'a>>,
    offset: u32,
) -> Vec<&'a Statement<'a>> {
    for stmt in statements.iter() {
        match stmt {
            Statement::Function(func) => {
                let body_start = func.body.left_brace.start.offset;
                let body_end = func.body.right_brace.end.offset;
                if offset >= body_start && offset <= body_end {
                    return func.body.statements.iter().collect();
                }
            }
            Statement::Class(class) => {
                for member in class.members.iter() {
                    if let ClassLikeMember::Method(method) = member
                        && let MethodBody::Concrete(block) = &method.body
                    {
                        let body_start = block.left_brace.start.offset;
                        let body_end = block.right_brace.end.offset;
                        if offset >= body_start && offset <= body_end {
                            return block.statements.iter().collect();
                        }
                    }
                }
            }
            Statement::Trait(tr) => {
                for member in tr.members.iter() {
                    if let ClassLikeMember::Method(method) = member
                        && let MethodBody::Concrete(block) = &method.body
                    {
                        let body_start = block.left_brace.start.offset;
                        let body_end = block.right_brace.end.offset;
                        if offset >= body_start && offset <= body_end {
                            return block.statements.iter().collect();
                        }
                    }
                }
            }
            Statement::Enum(en) => {
                for member in en.members.iter() {
                    if let ClassLikeMember::Method(method) = member
                        && let MethodBody::Concrete(block) = &method.body
                    {
                        let body_start = block.left_brace.start.offset;
                        let body_end = block.right_brace.end.offset;
                        if offset >= body_start && offset <= body_end {
                            return block.statements.iter().collect();
                        }
                    }
                }
            }
            Statement::Namespace(ns) => {
                let result = find_enclosing_body_statements(ns.statements(), offset);
                if !result.is_empty() {
                    return result;
                }
            }
            _ => {}
        }
    }
    Vec::new()
}

// ─── Context detection ──────────────────────────────────────────────────────

/// Whether the extracted code should become a method or a standalone function.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExtractionTarget {
    /// Extract as a private method on the enclosing class.
    Method,
    /// Extract as a standalone function after the enclosing function.
    Function,
}

/// Information about the enclosing function/method for insertion purposes.
#[derive(Debug, Clone)]
struct EnclosingContext {
    /// Whether to extract as a method or function.
    target: ExtractionTarget,
    /// Byte offset of the closing `}` of the enclosing class (for method
    /// insertion) or the enclosing function (for function insertion).
    insert_offset: usize,
    /// The body's opening `{` offset — used to determine indentation.
    body_start: usize,
    /// Whether the enclosing method is static.
    is_static: bool,
    /// The name of the enclosing function/method (e.g. `"run"`, `"process"`).
    /// Used by name generation to produce contextual names like `runGuard`.
    enclosing_name: String,
    /// Method names that already exist in the enclosing class (for
    /// deduplication when extracting a method).  Empty when extracting
    /// a standalone function.
    sibling_method_names: Vec<String>,
}

/// Determine the extraction target and insertion point by walking the AST.
fn find_enclosing_context(content: &str, offset: u32, uses_this: bool) -> Option<EnclosingContext> {
    let arena = Bump::new();
    let file_id = mago_database::file::FileId::new("extract_fn_ctx");
    let program = mago_syntax::parser::parse_file_content(&arena, file_id, content);

    let ctx = find_cursor_context(&program.statements, offset);

    match ctx {
        CursorContext::InClassLike {
            member,
            all_members,
            ..
        } => {
            if let MemberContext::Method(method, true) = member {
                let is_static = method.modifiers.iter().any(|m| m.is_static());
                let enclosing_name = method.name.value.to_string();

                // Collect sibling method names for scoped deduplication.
                let sibling_method_names: Vec<String> = all_members
                    .iter()
                    .filter_map(|m| {
                        if let ClassLikeMember::Method(m) = m {
                            Some(m.name.value.to_string())
                        } else {
                            None
                        }
                    })
                    .collect();

                // For method extraction, insert before the closing `}` of the class.
                // Find the class closing brace by walking up from the method.
                let class_end = find_class_end_offset(&program.statements, offset);

                if let MethodBody::Concrete(block) = &method.body {
                    let body_start = block.left_brace.start.offset as usize;

                    if uses_this && is_static {
                        // $this in a static method — can't extract as method.
                        // Fall back to extracting as a function.
                        let func_end = block.right_brace.end.offset as usize;
                        return Some(EnclosingContext {
                            target: ExtractionTarget::Function,
                            insert_offset: find_after_class_end(&program.statements, offset)
                                .unwrap_or(func_end),
                            body_start,
                            is_static,
                            enclosing_name,
                            sibling_method_names: Vec::new(),
                        });
                    }

                    return Some(EnclosingContext {
                        target: ExtractionTarget::Method,
                        insert_offset: class_end.unwrap_or(block.right_brace.end.offset as usize),
                        body_start,
                        is_static,
                        enclosing_name,
                        sibling_method_names,
                    });
                }
            }
            None
        }
        CursorContext::InFunction(func, true) => {
            let body_start = func.body.left_brace.start.offset as usize;
            let func_end = func.body.right_brace.end.offset as usize;
            let enclosing_name = func.name.value.to_string();

            // For function extraction, insert after the enclosing function.
            // Find the end of the line containing the closing `}`.
            let insert_offset = find_line_end(content, func_end);

            Some(EnclosingContext {
                target: ExtractionTarget::Function,
                insert_offset,
                body_start,
                is_static: false,
                enclosing_name,
                sibling_method_names: Vec::new(),
            })
        }
        _ => None,
    }
}

/// Find the byte offset of the closing `}` of the class containing `offset`.
fn find_class_end_offset(statements: &Sequence<'_, Statement<'_>>, offset: u32) -> Option<usize> {
    for stmt in statements.iter() {
        match stmt {
            Statement::Class(class) => {
                let span = class.span();
                if offset >= span.start.offset && offset <= span.end.offset {
                    return Some(class.right_brace.start.offset as usize);
                }
            }
            Statement::Trait(tr) => {
                let span = tr.span();
                if offset >= span.start.offset && offset <= span.end.offset {
                    return Some(tr.right_brace.start.offset as usize);
                }
            }
            Statement::Enum(en) => {
                let span = en.span();
                if offset >= span.start.offset && offset <= span.end.offset {
                    return Some(en.right_brace.start.offset as usize);
                }
            }
            Statement::Namespace(ns) => {
                if let Some(offset) = find_class_end_offset(ns.statements(), offset) {
                    return Some(offset);
                }
            }
            _ => {}
        }
    }
    None
}

/// Find the byte offset after the closing `}` of the class containing `offset`.
fn find_after_class_end(statements: &Sequence<'_, Statement<'_>>, offset: u32) -> Option<usize> {
    for stmt in statements.iter() {
        match stmt {
            Statement::Class(class) => {
                let span = class.span();
                if offset >= span.start.offset && offset <= span.end.offset {
                    return Some(span.end.offset as usize);
                }
            }
            Statement::Trait(tr) => {
                let span = tr.span();
                if offset >= span.start.offset && offset <= span.end.offset {
                    return Some(span.end.offset as usize);
                }
            }
            Statement::Enum(en) => {
                let span = en.span();
                if offset >= span.start.offset && offset <= span.end.offset {
                    return Some(span.end.offset as usize);
                }
            }
            Statement::Namespace(ns) => {
                if let Some(end) = find_after_class_end(ns.statements(), offset) {
                    return Some(end);
                }
            }
            _ => {}
        }
    }
    None
}

// ─── Scope map building ─────────────────────────────────────────────────────

/// Build a `ScopeMap` for the enclosing function/method at `offset`.
fn build_scope_map(content: &str, offset: u32) -> ScopeMap {
    let arena = Bump::new();
    let file_id = mago_database::file::FileId::new("extract_fn_scope");
    let program = mago_syntax::parser::parse_file_content(&arena, file_id, content);

    for stmt in program.statements.iter() {
        if let Some(map) = try_build_scope_from_statement(stmt, offset) {
            return map;
        }
    }

    // Fallback: top-level scope.
    let body_end = content.len() as u32;
    collect_scope(program.statements.as_slice(), 0, body_end)
}

/// Recursively try to build a scope map from a statement.
fn try_build_scope_from_statement(stmt: &Statement<'_>, offset: u32) -> Option<ScopeMap> {
    match stmt {
        Statement::Function(func) => {
            let body_start = func.body.left_brace.start.offset;
            let body_end = func.body.right_brace.end.offset;
            if offset >= body_start && offset <= body_end {
                return Some(collect_function_scope(
                    &func.parameter_list,
                    func.body.statements.as_slice(),
                    body_start,
                    body_end,
                ));
            }
        }
        Statement::Class(class) => {
            for member in class.members.iter() {
                if let ClassLikeMember::Method(method) = member
                    && let MethodBody::Concrete(block) = &method.body
                {
                    let body_start = block.left_brace.start.offset;
                    let body_end = block.right_brace.end.offset;
                    if offset >= body_start && offset <= body_end {
                        return Some(collect_function_scope_with_kind(
                            &method.parameter_list,
                            block.statements.as_slice(),
                            body_start,
                            body_end,
                            FrameKind::Method,
                        ));
                    }
                }
            }
        }
        Statement::Trait(tr) => {
            for member in tr.members.iter() {
                if let ClassLikeMember::Method(method) = member
                    && let MethodBody::Concrete(block) = &method.body
                {
                    let body_start = block.left_brace.start.offset;
                    let body_end = block.right_brace.end.offset;
                    if offset >= body_start && offset <= body_end {
                        return Some(collect_function_scope_with_kind(
                            &method.parameter_list,
                            block.statements.as_slice(),
                            body_start,
                            body_end,
                            FrameKind::Method,
                        ));
                    }
                }
            }
        }
        Statement::Enum(en) => {
            for member in en.members.iter() {
                if let ClassLikeMember::Method(method) = member
                    && let MethodBody::Concrete(block) = &method.body
                {
                    let body_start = block.left_brace.start.offset;
                    let body_end = block.right_brace.end.offset;
                    if offset >= body_start && offset <= body_end {
                        return Some(collect_function_scope_with_kind(
                            &method.parameter_list,
                            block.statements.as_slice(),
                            body_start,
                            body_end,
                            FrameKind::Method,
                        ));
                    }
                }
            }
        }
        Statement::Namespace(ns) => {
            for inner in ns.statements().iter() {
                if let Some(map) = try_build_scope_from_statement(inner, offset) {
                    return Some(map);
                }
            }
        }
        _ => {}
    }
    None
}

// ─── Type resolution ────────────────────────────────────────────────────────

/// Resolve the type of a variable at a given offset using the hover
/// pipeline.
fn resolve_var_type(
    backend: &Backend,
    var_name: &str,
    content: &str,
    cursor_offset: u32,
    uri: &str,
) -> Option<PhpType> {
    let ctx = backend.file_context(uri);
    let class_loader = backend.class_loader(&ctx);
    let function_loader = backend.function_loader(&ctx);
    let constant_loader = backend.constant_loader();
    let loaders = Loaders {
        function_loader: Some(
            &function_loader as &dyn Fn(&str) -> Option<crate::types::FunctionInfo>,
        ),
        constant_loader: Some(&constant_loader),
    };

    let current_class = find_class_at_offset(&ctx.classes, cursor_offset);

    crate::hover::variable_type::resolve_variable_type(
        var_name,
        content,
        cursor_offset,
        current_class,
        &ctx.classes,
        &class_loader,
        loaders,
    )
}

// ─── Name generation ────────────────────────────────────────────────────────

/// Generate a unique function/method name that doesn't conflict with
/// existing members or functions.
/// Context passed to [`generate_function_name`] to produce meaningful names.
struct NamingContext<'a> {
    /// The enclosing function/method name (e.g. `"run"`, `"process"`).
    enclosing_name: &'a str,
    /// The return strategy chosen for the extraction.
    return_strategy: &'a ReturnStrategy,
    /// The selected body text (trimmed source of the extracted statements).
    body_text: &'a str,
    /// Names of return-value variables (written inside, read after).
    return_var_names: &'a [String],
    /// The trailing return type hint (e.g. `Collection`, `User`).
    trailing_return_type: &'a PhpType,
}

/// Generate a contextual name for the extracted function/method.
///
/// The naming follows these heuristics (first match wins):
///
/// 1. **Guard strategies** (`VoidGuards`, `UniformGuards`,
///    `NullGuardWithValue`): `{enclosing}Guard` — the user extracted
///    validation / precondition logic.
/// 2. **`SentinelNull`**: `try{Enclosing}` — a "try" pattern where
///    `null` signals failure.
/// 3. **`TrailingReturn` with `new ClassName`** in the body:
///    `create{ClassName}` — a factory pattern.
/// 4. **`TrailingReturn`** (other): `get{Enclosing}Result`.
/// 5. **Body is pure output** (every statement is `echo`/`print`/
///    `printf`/`var_dump`): `render{Enclosing}`.
/// 6. **Single return variable**: `compute{VarName}` — the user
///    extracted a calculation into its own function.
/// 7. **Body ends with output** (setup assignments followed by
///    `echo`/`print`): `render{Enclosing}`.
/// 8. **Single delegating call** (`$this->foo(…)`, `doWork(…)`):
///    the name of the called method/function.
/// 9. **Fallback**: `"extracted"`.
///
/// After choosing a base name, the function deduplicates against
/// existing names in the appropriate scope (class members for methods,
/// file-level `function` declarations for standalone functions).
fn generate_function_name(
    content: &str,
    enclosing_ctx: &EnclosingContext,
    naming: &NamingContext,
) -> String {
    let base = derive_base_name(naming);

    // Deduplicate against the right scope.
    deduplicate_name(&base, content, enclosing_ctx)
}

/// Pick a base name from the naming context (before deduplication).
fn derive_base_name(ctx: &NamingContext) -> String {
    let enc = ctx.enclosing_name;

    // 1. Guard strategies → {enclosing}Guard
    match ctx.return_strategy {
        ReturnStrategy::VoidGuards
        | ReturnStrategy::UniformGuards(_)
        | ReturnStrategy::NullGuardWithValue(_) => {
            if !enc.is_empty() {
                return format!("{}Guard", enc);
            }
            return "guard".to_string();
        }

        // 2. SentinelNull → try{Enclosing}
        ReturnStrategy::SentinelNull => {
            if !enc.is_empty() {
                return format!("try{}", capitalise(enc));
            }
            return "tryExtract".to_string();
        }

        // 3–4. TrailingReturn
        ReturnStrategy::TrailingReturn => {
            // 3. Factory: body contains `new ClassName` → create{ClassName}
            if let Some(class_name) = detect_factory_pattern(ctx.body_text) {
                return format!("create{}", class_name);
            }
            // 4. Generic trailing return
            if !enc.is_empty() {
                // If there's a return type, use it for a more descriptive name
                if !ctx.trailing_return_type.is_empty() {
                    // Only use the return type if it's a class name (starts uppercase)
                    if let Some(name) = ctx.trailing_return_type.base_name() {
                        return format!("get{}", name);
                    }
                }
                return format!("get{}Result", capitalise(enc));
            }
        }

        ReturnStrategy::None | ReturnStrategy::Unsafe => {}
    }

    // 5. Pure output → render{Enclosing}
    if is_pure_output(ctx.body_text) && !enc.is_empty() {
        return format!("render{}", capitalise(enc));
    }

    // 6. Single return variable → compute{VarName}
    if ctx.return_var_names.len() == 1 {
        let var = ctx.return_var_names[0].trim_start_matches('$');
        if !var.is_empty() {
            return format!("compute{}", capitalise(var));
        }
    }

    // 7. Ends with output (setup + echo/print) → render{Enclosing}
    if ends_with_output(ctx.body_text) && !enc.is_empty() {
        return format!("render{}", capitalise(enc));
    }

    // 8. Single method/function call → {calledName}
    if let Some(name) = detect_single_call(ctx.body_text)
        && !name.is_empty()
    {
        return name;
    }

    // 9. Fallback
    "extracted".to_string()
}

/// Capitalise the first character of a string (ASCII).
fn capitalise(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) => {
            let upper: String = c.to_uppercase().collect();
            format!("{}{}", upper, chars.as_str())
        }
        None => String::new(),
    }
}

/// Detect if the body text is a factory pattern: the extracted code
/// constructs an object and returns it.
///
/// Returns a name suitable for `create{Name}`.
///
/// When the body assigns `$var = new X(…)` and later returns `$var`,
/// the variable name is used (e.g. `$users` → `"Users"`).  This
/// produces `createUsers` rather than `createCollection`, which
/// matches how developers think about the domain object.
///
/// When the body does `return new ClassName(…)` directly, the class
/// name is used instead (there is no variable to take a hint from).
fn detect_factory_pattern(body: &str) -> Option<String> {
    let mut returned_class: Option<String> = None;
    let mut returned_var: Option<String> = None;
    let mut assigned_var: Option<String> = None;
    let mut assigned_class: Option<String> = None;

    for line in body.lines() {
        let trimmed = line.trim();
        // Check for `return new ClassName(…)` — direct return.
        if let Some(after_return) = trimmed.strip_prefix("return ")
            && let Some(name) = extract_new_class_name(after_return.trim_start())
        {
            returned_class = Some(name);
        }
        // Check for `return $var;` — returning a variable.
        if let Some(after_return) = trimmed.strip_prefix("return ") {
            let var = after_return.trim().trim_end_matches(';').trim();
            if var.starts_with('$') && var[1..].chars().all(|c| c.is_alphanumeric() || c == '_') {
                returned_var = Some(var.to_string());
            }
        }
        // Check for `$var = new ClassName(…)` (direct assignment).
        if let Some(eq_pos) = trimmed.find('=') {
            // Make sure it's `=` not `==` / `===` / `!=` etc.
            let before_eq = &trimmed[..eq_pos];
            let after_eq = &trimmed[eq_pos + 1..];
            let var_name = before_eq.trim();
            if var_name.starts_with('$')
                && !after_eq.starts_with('=')
                && !before_eq.ends_with('!')
                && !before_eq.ends_with('<')
                && !before_eq.ends_with('>')
                && let Some(class_name) = extract_new_class_name(after_eq.trim_start())
            {
                assigned_var = Some(var_name.to_string());
                assigned_class = Some(class_name);
            }
        }
    }

    // Best case: `$var = new X(…); ... return $var;` — use the
    // variable name because it carries domain meaning (e.g. `$users`
    // → `createUsers`).  Fall back to the class name when the variable
    // is too short to be meaningful (`$u`, `$x`, etc.).
    if let Some(ref ret_var) = returned_var
        && let Some(ref asgn_var) = assigned_var
        && ret_var == asgn_var
    {
        let var_clean = ret_var.trim_start_matches('$');
        if var_clean.len() > 2 {
            return Some(capitalise(var_clean));
        }
        // Short variable — prefer the class name.
        if let Some(ref name) = assigned_class {
            let short = name.rsplit('\\').next().unwrap_or(name);
            return Some(short.to_string());
        }
    }

    // `return new ClassName(…)` — use the class name.
    if let Some(name) = returned_class {
        let short = name.rsplit('\\').next().unwrap_or(&name);
        return Some(short.to_string());
    }

    // `$var = new ClassName(…)` without an explicit return — use the
    // variable name if long enough, otherwise the class name.
    if let Some(ref var) = assigned_var {
        let var_clean = var.trim_start_matches('$');
        if var_clean.len() > 2 {
            return Some(capitalise(var_clean));
        }
    }
    if let Some(name) = assigned_class {
        let short = name.rsplit('\\').next().unwrap_or(&name);
        return Some(short.to_string());
    }

    None
}

/// Extract a class name from text starting with `new ClassName`.
///
/// Returns `None` if the text doesn't start with `new ` followed by
/// an uppercase identifier.
fn extract_new_class_name(text: &str) -> Option<String> {
    let rest = text.strip_prefix("new ")?;
    let name: String = rest
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '\\')
        .collect();
    if !name.is_empty() && name.starts_with(|c: char| c.is_ascii_uppercase()) {
        Some(name)
    } else {
        None
    }
}

/// Output-statement prefixes shared by the pure/trailing output checks.
const OUTPUT_PREFIXES: &[&str] = &[
    "echo ",
    "echo(",
    "echo \"",
    "echo '",
    "print ",
    "print(",
    "printf(",
    "var_dump(",
    "print_r(",
    "var_export(",
];

/// Returns `true` when `line` (trimmed, without trailing `;`) looks
/// like an output statement.
fn is_output_line(line: &str) -> bool {
    OUTPUT_PREFIXES.iter().any(|p| line.starts_with(p))
}

/// Check whether every statement in the body is a pure output statement
/// (`echo`, `print`, `printf`, `var_dump`, `print_r`, `var_export`).
fn is_pure_output(body: &str) -> bool {
    let trimmed = body.trim();
    if trimmed.is_empty() {
        return false;
    }

    for line in trimmed.lines() {
        let line = line.trim().trim_end_matches(';').trim();
        if line.is_empty() || line.starts_with("//") || line.starts_with('#') {
            continue;
        }
        if !is_output_line(line) {
            return false;
        }
    }

    true
}

/// Check whether the body *ends* with one or more output statements
/// but also contains non-output setup lines (assignments, calls, etc.).
///
/// This catches the common "compute then display" pattern:
/// ```php
/// $first = $users->first();
/// echo $first->name;
/// ```
fn ends_with_output(body: &str) -> bool {
    let trimmed = body.trim();
    if trimmed.is_empty() {
        return false;
    }

    let lines: Vec<&str> = trimmed
        .lines()
        .map(|l| l.trim().trim_end_matches(';').trim())
        .filter(|l| !l.is_empty() && !l.starts_with("//") && !l.starts_with('#'))
        .collect();

    if lines.len() < 2 {
        return false;
    }

    // The last line must be output.
    if !is_output_line(lines[lines.len() - 1]) {
        return false;
    }

    // At least one earlier line must NOT be output (otherwise
    // `is_pure_output` already matched).
    lines[..lines.len() - 1].iter().any(|l| !is_output_line(l))
}

/// Detect when the body is a single method call or function call
/// statement (no assignment, no return).  Returns a name derived from
/// the called method/function.
///
/// Examples:
/// - `$this->execute($fn)` → `"execute"`
/// - `self::validate($x)`  → `"validate"`
/// - `doSomething($x)`     → `"doSomething"`
fn detect_single_call(body: &str) -> Option<String> {
    let trimmed = body.trim();

    // Must be a single non-comment line.
    let lines: Vec<&str> = trimmed
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.is_empty() && !l.starts_with("//") && !l.starts_with('#'))
        .collect();
    if lines.len() != 1 {
        return None;
    }

    let line = lines[0].strip_suffix(';').unwrap_or(lines[0]).trim();

    // Must not be an assignment.
    if line.contains('=') {
        // Allow `==`, `!=`, `===`, `!==`, `>=`, `<=` inside expressions,
        // but reject bare `$var = ...` assignments.
        if let Some(eq_pos) = line.find('=') {
            let before = &line[..eq_pos];
            let after = &line[eq_pos + 1..];
            if before.trim().starts_with('$')
                && !after.starts_with('=')
                && !before.ends_with('!')
                && !before.ends_with('<')
                && !before.ends_with('>')
            {
                return None;
            }
        }
    }

    // Extract the method/function name from the call.
    // `$this->foo(...)` or `$var->foo(...)`
    if let Some(arrow_pos) = line.rfind("->") {
        let after = &line[arrow_pos + 2..];
        let name: String = after
            .chars()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect();
        if !name.is_empty() && after[name.len()..].starts_with('(') {
            return Some(name);
        }
    }
    // `self::foo(...)` or `static::foo(...)` or `ClassName::foo(...)`
    if let Some(colon_pos) = line.rfind("::") {
        let after = &line[colon_pos + 2..];
        let name: String = after
            .chars()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect();
        if !name.is_empty() && after[name.len()..].starts_with('(') {
            return Some(name);
        }
    }
    // `functionName(...)` — bare function call
    let name: String = line
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '\\')
        .collect();
    if !name.is_empty()
        && name.starts_with(|c: char| c.is_ascii_lowercase() || c == '\\')
        && line[name.len()..].starts_with('(')
    {
        // Use the short name (after last backslash).
        let short = name.rsplit('\\').next().unwrap_or(&name);
        return Some(short.to_string());
    }

    None
}

/// Deduplicate a base name against existing names in the appropriate scope.
///
/// For methods, checks against sibling method names in the class.
/// For functions, checks against `function <name>` patterns in the file.
fn deduplicate_name(base: &str, content: &str, ctx: &EnclosingContext) -> String {
    let mut name = base.to_string();
    let mut counter = 1u32;

    match ctx.target {
        ExtractionTarget::Method => {
            // Check against sibling method names in the class.
            loop {
                if !ctx.sibling_method_names.contains(&name) {
                    break;
                }
                counter += 1;
                name = format!("{}{}", base, counter);
            }
        }
        ExtractionTarget::Function => {
            // Check against function declarations in the file.
            loop {
                let pattern_fn = format!("function {}", name);
                if !content.contains(&pattern_fn) {
                    break;
                }
                counter += 1;
                name = format!("{}{}", base, counter);
            }
        }
    }

    name
}

// ─── Selection trimming ────────────────────────────────────────────────────

/// Trim the selection to exclude leading/trailing whitespace and ensure
/// it starts/ends on statement boundaries.
///
/// Returns `(trimmed_start, trimmed_end)` or `None` if the trimmed
/// selection is empty.
fn trim_selection(content: &str, start: usize, end: usize) -> Option<(usize, usize)> {
    if start >= end || end > content.len() {
        return None;
    }

    let selected = &content[start..end];
    let trimmed = selected.trim();
    if trimmed.is_empty() {
        return None;
    }

    let trim_start = start + (selected.len() - selected.trim_start().len());
    let trim_end = end - (selected.len() - selected.trim_end().len());

    if trim_start >= trim_end {
        return None;
    }

    Some((trim_start, trim_end))
}

// ─── Indentation helpers ────────────────────────────────────────────────────

/// Detect the indentation of the line containing the given offset.
///
/// Returns only the leading whitespace of that line, without adding
/// an extra indent level.
fn detect_line_indent(content: &str, offset: usize) -> String {
    let before = &content[..offset];
    let line_start = before.rfind('\n').map_or(0, |p| p + 1);
    let line = &content[line_start..offset];
    line.chars().take_while(|c| c.is_whitespace()).collect()
}

/// Detect whether the file uses tabs or spaces (and how many spaces).
fn detect_indent_unit(content: &str) -> &str {
    for line in content.lines() {
        if line.starts_with('\t') {
            return "\t";
        }
        let spaces: usize = line.chars().take_while(|c| *c == ' ').count();
        if spaces >= 2 {
            if spaces.is_multiple_of(4) {
                return "    ";
            }
            return "  ";
        }
    }
    "    "
}

/// Find the end of the line containing `offset` (after the `\n`).
fn find_line_end(content: &str, offset: usize) -> usize {
    match content[offset..].find('\n') {
        Some(pos) => offset + pos + 1,
        None => content.len(),
    }
}

/// Find the start of the line containing `offset`.
fn find_line_start(content: &str, offset: usize) -> usize {
    content[..offset].rfind('\n').map_or(0, |p| p + 1)
}

/// Extract the indentation (leading whitespace) of the line at `offset`.
fn indent_at(content: &str, offset: usize) -> String {
    let line_start = find_line_start(content, offset);
    let rest = &content[line_start..];
    rest.chars().take_while(|c| c.is_whitespace()).collect()
}

// ─── Code generation ────────────────────────────────────────────────────────

/// Information gathered for code generation.
struct ExtractionInfo {
    /// The name of the new function/method.
    name: String,
    /// Parameters: `(var_name_with_dollar, cleaned_type_hint)`.
    params: Vec<(String, PhpType)>,
    /// Return values: `(var_name_with_dollar, cleaned_type_hint)`.
    returns: Vec<(String, PhpType)>,
    /// The selected statements as source text.
    body: String,
    /// Whether to extract as method or function.
    target: ExtractionTarget,
    /// Whether the enclosing method is static.
    is_static: bool,
    /// Indentation of the member level (for methods) or top level (for functions).
    member_indent: String,
    /// Indentation of the body inside the new function/method.
    body_indent: String,
    /// How return statements in the selection are handled.
    return_strategy: ReturnStrategy,
    /// Return type hint for the trailing return (resolved from the
    /// enclosing function's return type or the return expression).
    trailing_return_type: PhpType,
    /// Pre-computed PHPDoc block (including `/**` … `*/\n`) to prepend
    /// before the function definition, or empty if no enrichment needed.
    docblock: String,
}

/// Build a PHPDoc block for the extracted function when types need enrichment.
///
/// Each parameter is a triple `(var_name, cleaned_type, raw_type)` where
/// `cleaned_type` is the native PHP hint (generics stripped) and
/// `raw_type` is the full resolved type as a [`PhpType`] (e.g.
/// `Collection<User>`).
///
/// When `raw_type` already contains concrete generic arguments,
/// it is used verbatim as the docblock type.  Otherwise we fall back to
/// `enrichment_plain` which reconstructs template parameters from the
/// class definition (yielding placeholder names like `T`).
///
/// A `@return` tag follows the same logic: if `raw_return_type` carries
/// concrete generics, use it; otherwise try enrichment.
///
/// Returns an empty string when no enrichment is needed.
fn build_docblock_for_extraction(
    params: &[(String, PhpType, PhpType)],
    return_type_hint: &PhpType,
    raw_return_type: &PhpType,
    member_indent: &str,
    class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> String {
    let mut tags: Vec<String> = Vec::new();

    // Collect @param tags that need enrichment.
    for (name, type_hint, raw) in params {
        let has_native_hint = type_hint.to_native_hint().is_some_and(|s| !s.is_empty());
        if !has_native_hint && raw.is_empty() {
            continue;
        }
        // Prefer the raw resolved type when it carries concrete generics.
        if raw.has_type_structure() {
            tags.push(format!("@param {} {}", raw, name));
            continue;
        }
        let type_for_enrichment = if has_native_hint { type_hint } else { raw };
        if let Some(enriched) = enrichment_plain(Some(type_for_enrichment), class_loader) {
            tags.push(format!("@param {} {}", enriched, name));
        }
    }

    // Collect @return tag if the return type needs enrichment.
    if !return_type_hint.is_empty() || !raw_return_type.is_empty() {
        if raw_return_type.has_type_structure() {
            tags.push(format!("@return {}", raw_return_type));
        } else {
            let hint = if return_type_hint.is_empty() {
                raw_return_type
            } else {
                return_type_hint
            };
            if let Some(enriched) = enrichment_plain(Some(hint), class_loader) {
                tags.push(format!("@return {}", enriched));
            }
        }
    }

    if tags.is_empty() {
        return String::new();
    }

    // Align @param tag types for readability.
    // Find the max type width among @param tags.
    let param_tags: Vec<(&str, &str)> = tags
        .iter()
        .filter_map(|t| {
            let rest = t.strip_prefix("@param ")?;
            // Split on `$` — PHP param names always start with `$`,
            // and the type string may contain spaces (e.g. `(Closure(): mixed)`).
            let dollar_pos = rest.find('$')?;
            let type_str = rest[..dollar_pos].trim_end();
            let name_str = &rest[dollar_pos..];
            Some((type_str, name_str))
        })
        .collect();

    let max_type_len = param_tags.iter().map(|(t, _)| t.len()).max().unwrap_or(0);

    let mut out = String::new();
    out.push_str(member_indent);
    out.push_str("/**\n");

    for tag in &tags {
        out.push_str(member_indent);
        out.push_str(" * ");
        if let Some(rest) = tag.strip_prefix("@param ") {
            if let Some(dollar_pos) = rest.find('$') {
                let type_str = rest[..dollar_pos].trim_end();
                let name_str = &rest[dollar_pos..];
                out.push_str("@param ");
                out.push_str(type_str);
                // Pad to align parameter names.
                for _ in 0..(max_type_len.saturating_sub(type_str.len())) {
                    out.push(' ');
                }
                out.push(' ');
                out.push_str(name_str);
            } else {
                out.push_str(tag);
            }
        } else {
            out.push_str(tag);
        }
        out.push('\n');
    }

    out.push_str(member_indent);
    out.push_str(" */\n");

    out
}

/// Build the definition text of the extracted function or method.
fn build_extracted_definition(info: &ExtractionInfo) -> String {
    let mut out = String::new();

    // Blank line before the new definition.
    out.push('\n');

    // Prepend PHPDoc block if types need enrichment.
    if !info.docblock.is_empty() {
        out.push_str(&info.docblock);
    }

    let param_list = build_param_list(&info.params);
    let return_type = build_return_type(info);

    match info.target {
        ExtractionTarget::Method => {
            out.push_str(&info.member_indent);
            out.push_str("private ");
            if info.is_static {
                out.push_str("static ");
            }
            out.push_str("function ");
            out.push_str(&info.name);
            out.push('(');
            out.push_str(&param_list);
            out.push(')');
            if !return_type.is_empty() {
                out.push_str(": ");
                out.push_str(&return_type);
            }
            out.push('\n');
            out.push_str(&info.member_indent);
            out.push_str("{\n");
        }
        ExtractionTarget::Function => {
            out.push_str(&info.member_indent);
            out.push_str("function ");
            out.push_str(&info.name);
            out.push('(');
            out.push_str(&param_list);
            out.push(')');
            if !return_type.is_empty() {
                out.push_str(": ");
                out.push_str(&return_type);
            }
            out.push('\n');
            out.push_str(&info.member_indent);
            out.push_str("{\n");
        }
    }

    // Rewrite guard returns in the body if needed.
    let body_text = match &info.return_strategy {
        ReturnStrategy::VoidGuards => {
            // Bare `return;` → `return false;` (false = early exit).
            rewrite_guard_returns(&info.body, None)
        }
        ReturnStrategy::UniformGuards(value) => {
            let lower = value.to_lowercase();
            if lower == "false" || lower == "true" {
                // Already boolean — the body's returns are correct as-is.
                info.body.clone()
            } else {
                // Non-boolean uniform value (e.g. `null`, `0`, `'error'`):
                // rewrite `return <value>;` → `return false;`.
                rewrite_guard_returns(&info.body, Some(value))
            }
        }
        ReturnStrategy::NullGuardWithValue(void_guards) if *void_guards => {
            // Bare `return;` → `return null;` so the extracted
            // function returns null on guard-fire.
            rewrite_void_returns_to_null(&info.body)
        }
        _ => info.body.clone(),
    };

    // Re-indent the body to match the new function's body indentation.
    let body_lines = body_text.lines().collect::<Vec<_>>();
    let min_indent = body_lines
        .iter()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start().len())
        .min()
        .unwrap_or(0);

    for line in &body_lines {
        if line.trim().is_empty() {
            out.push('\n');
        } else {
            out.push_str(&info.body_indent);
            if line.len() > min_indent {
                out.push_str(&line[min_indent..]);
            }
            out.push('\n');
        }
    }

    // Add return/sentinel after the body based on the strategy.
    match &info.return_strategy {
        ReturnStrategy::TrailingReturn => {
            // Body already ends with `return` — nothing to add.
        }
        ReturnStrategy::VoidGuards => {
            // All guards are bare `return;`.  Add `return true;` as the
            // fall-through (meaning "no early exit, keep going").
            out.push_str(&info.body_indent);
            out.push_str("return true;\n");
        }
        ReturnStrategy::UniformGuards(value) => {
            // All guards return the same value.  The extracted function
            // uses bool: guards become `return false;` (exit), and
            // fall-through is `return true;` (continue).
            // But the body already has the original returns — we need
            // to add the sentinel.  The body's returns stay as-is and
            // get rewritten below by `rewrite_guard_returns_to_bool`.
            // Here we just add the fall-through sentinel.
            let lower = value.to_lowercase();
            let sentinel = if lower == "false" {
                "true"
            } else if lower == "true" {
                "false"
            } else {
                // Non-boolean uniform value: use `true` = continue.
                "true"
            };
            out.push_str(&info.body_indent);
            out.push_str("return ");
            out.push_str(sentinel);
            out.push_str(";\n");
        }
        ReturnStrategy::SentinelNull => {
            // Different non-null values — null = "no early exit".
            out.push_str(&info.body_indent);
            out.push_str("return null;\n");
        }
        ReturnStrategy::NullGuardWithValue(_) => {
            // Guards return null (or were rewritten from bare return;),
            // and we also compute a value.  The fall-through returns
            // the computed variable.
            if info.returns.len() == 1 {
                out.push_str(&info.body_indent);
                out.push_str("return ");
                out.push_str(&info.returns[0].0);
                out.push_str(";\n");
            }
        }
        ReturnStrategy::None | ReturnStrategy::Unsafe => {
            // Normal extraction: add return for captured variables.
            if info.returns.len() == 1 {
                out.push_str(&info.body_indent);
                out.push_str("return ");
                out.push_str(&info.returns[0].0);
                out.push_str(";\n");
            } else if info.returns.len() > 1 {
                out.push_str(&info.body_indent);
                out.push_str("return [");
                let names: Vec<&str> = info.returns.iter().map(|(n, _)| n.as_str()).collect();
                out.push_str(&names.join(", "));
                out.push_str("];\n");
            }
        }
    }

    out.push_str(&info.member_indent);
    out.push_str("}\n");

    out
}

/// Rewrite guard-clause return statements in the body text.
///
/// For `VoidGuards` (`uniform_value` is `None`): bare `return;` becomes
/// `return false;`.
///
/// For `UniformGuards` with a non-boolean value (`uniform_value` is
/// `Some`): `return <value>;` becomes `return false;`.
///
/// This operates on source text rather than AST to keep things simple.
/// It matches `return` followed by optional whitespace and either `;`
/// (void) or the uniform value and `;`.
///
/// See also [`rewrite_void_returns_to_null`] for the
/// `NullGuardWithValue(true)` case.
fn rewrite_guard_returns(body: &str, uniform_value: Option<&str>) -> String {
    match uniform_value {
        None => {
            // VoidGuards: rewrite bare `return;` to `return false;`.
            // We need to be careful not to match `return $x;` etc.
            // Strategy: find `return` followed by optional whitespace
            // then `;`, with no expression in between.
            let mut result = String::with_capacity(body.len());
            let mut remaining = body;
            while let Some(pos) = remaining.find("return") {
                // Check that this is a keyword boundary (not part of
                // `$returnValue` etc.).
                let before_ok = pos == 0
                    || !remaining.as_bytes()[pos - 1].is_ascii_alphanumeric()
                        && remaining.as_bytes()[pos - 1] != b'_'
                        && remaining.as_bytes()[pos - 1] != b'$';
                if !before_ok {
                    result.push_str(&remaining[..pos + 6]);
                    remaining = &remaining[pos + 6..];
                    continue;
                }
                let after = &remaining[pos + 6..];
                let trimmed = after.trim_start();
                if trimmed.starts_with(';') {
                    // Bare `return;` → `return false;`
                    result.push_str(&remaining[..pos]);
                    result.push_str("return false");
                    // Skip past `return` + whitespace, keep the `;`.
                    let ws_len = after.len() - trimmed.len();
                    remaining = &remaining[pos + 6 + ws_len..];
                } else {
                    result.push_str(&remaining[..pos + 6]);
                    remaining = &remaining[pos + 6..];
                }
            }
            result.push_str(remaining);
            result
        }
        Some(value) => {
            // UniformGuards with non-boolean value: rewrite
            // `return <value>;` to `return false;`.
            let mut result = String::with_capacity(body.len());
            let mut remaining = body;
            while let Some(pos) = remaining.find("return") {
                let before_ok = pos == 0
                    || !remaining.as_bytes()[pos - 1].is_ascii_alphanumeric()
                        && remaining.as_bytes()[pos - 1] != b'_'
                        && remaining.as_bytes()[pos - 1] != b'$';
                if !before_ok {
                    result.push_str(&remaining[..pos + 6]);
                    remaining = &remaining[pos + 6..];
                    continue;
                }
                let after = &remaining[pos + 6..];
                let trimmed = after.trim_start();
                // Check if the return expression matches the uniform
                // value (case-insensitive for keywords like `null`).
                let value_trimmed = value.trim();
                if trimmed.len() >= value_trimmed.len() {
                    let candidate = &trimmed[..value_trimmed.len()];
                    let after_value = trimmed[value_trimmed.len()..].trim_start();
                    if candidate.eq_ignore_ascii_case(value_trimmed) && after_value.starts_with(';')
                    {
                        // `return <value>;` → `return false;`
                        result.push_str(&remaining[..pos]);
                        result.push_str("return false");
                        // Skip past `return <ws> <value> <ws>`, keep `;`.
                        let consumed = (trimmed.as_ptr() as usize - after.as_ptr() as usize)
                            + value_trimmed.len()
                            + (after_value.as_ptr() as usize
                                - trimmed[value_trimmed.len()..].as_ptr() as usize);
                        remaining = &remaining[pos + 6 + consumed..];
                        continue;
                    }
                }
                result.push_str(&remaining[..pos + 6]);
                remaining = &remaining[pos + 6..];
            }
            result.push_str(remaining);
            result
        }
    }
}

/// Rewrite bare `return;` to `return null;` in the body text.
///
/// Used by `NullGuardWithValue(true)` — void guard clauses that are
/// extracted alongside a computed value.  The extracted function must
/// return `null` (not void) to signal "guard fired" to the caller.
fn rewrite_void_returns_to_null(body: &str) -> String {
    let mut result = String::with_capacity(body.len());
    let mut remaining = body;
    while let Some(pos) = remaining.find("return") {
        let before_ok = pos == 0
            || !remaining.as_bytes()[pos - 1].is_ascii_alphanumeric()
                && remaining.as_bytes()[pos - 1] != b'_'
                && remaining.as_bytes()[pos - 1] != b'$';
        if !before_ok {
            result.push_str(&remaining[..pos + 6]);
            remaining = &remaining[pos + 6..];
            continue;
        }
        let after = &remaining[pos + 6..];
        let trimmed = after.trim_start();
        if trimmed.starts_with(';') {
            // Bare `return;` → `return null;`
            result.push_str(&remaining[..pos]);
            result.push_str("return null");
            let ws_len = after.len() - trimmed.len();
            remaining = &remaining[pos + 6 + ws_len..];
        } else {
            result.push_str(&remaining[..pos + 6]);
            remaining = &remaining[pos + 6..];
        }
    }
    result.push_str(remaining);
    result
}

/// Build the parameter list string for the function signature.
fn build_param_list(params: &[(String, PhpType)]) -> String {
    params
        .iter()
        .map(|(name, type_hint)| {
            let hint_str = type_hint.to_native_hint().unwrap_or_default();
            if hint_str.is_empty() {
                name.clone()
            } else {
                format!("{} {}", hint_str, name)
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// Build the return type annotation string.
fn build_return_type(info: &ExtractionInfo) -> String {
    match &info.return_strategy {
        ReturnStrategy::TrailingReturn => {
            // Use the enclosing function's return type — already a PhpType,
            // no need to re-parse.
            if let Some(cleaned) = clean_type_for_signature_typed(&info.trailing_return_type) {
                return cleaned.to_string();
            }
            String::new()
        }
        ReturnStrategy::VoidGuards | ReturnStrategy::UniformGuards(_) => {
            // Guard strategies use bool: true = continue, false = exit.
            "bool".to_string()
        }
        ReturnStrategy::SentinelNull => {
            // Sentinel-null: the return type is nullable.  Try to
            // derive it from the trailing_return_type if available,
            // otherwise leave untyped.
            if let Some(cleaned) = clean_type_for_signature_typed(&info.trailing_return_type)
                && !cleaned.is_null()
                && !cleaned.is_mixed()
                && !matches!(cleaned, PhpType::Nullable(_))
            {
                return PhpType::Nullable(Box::new(cleaned)).to_string();
            }
            // Can't determine a useful nullable type.
            String::new()
        }
        ReturnStrategy::NullGuardWithValue(_) => {
            // The return type is the computed value's type made nullable.
            if info.returns.len() == 1 {
                let type_hint = &info.returns[0].1;
                if let Some(cleaned) = clean_type_for_signature_typed(type_hint) {
                    if !cleaned.is_null()
                        && !cleaned.is_mixed()
                        && !matches!(cleaned, PhpType::Nullable(_))
                    {
                        return PhpType::Nullable(Box::new(cleaned)).to_string();
                    }
                    // Already nullable or mixed — use as-is.
                    return cleaned.to_string();
                }
            }
            String::new()
        }
        ReturnStrategy::None | ReturnStrategy::Unsafe => {
            // Normal extraction — derive from return variables.
            if info.returns.is_empty() {
                return "void".to_string();
            }
            if info.returns.len() == 1 {
                let type_hint = &info.returns[0].1;
                let hint_str = type_hint.to_native_hint().unwrap_or_default();
                if hint_str.is_empty() {
                    return String::new();
                }
                return hint_str;
            }
            // Multiple return values → return as array.
            "array".to_string()
        }
    }
}

/// Build the call-site text that replaces the selected statements.
fn build_call_site(info: &ExtractionInfo, call_indent: &str) -> String {
    let mut out = String::new();

    let args: Vec<&str> = info.params.iter().map(|(n, _)| n.as_str()).collect();
    let arg_list = args.join(", ");

    // Build the function/method call expression.
    let call_expr = match info.target {
        ExtractionTarget::Method => {
            if info.is_static {
                format!("self::{}({})", info.name, arg_list)
            } else {
                format!("$this->{}({})", info.name, arg_list)
            }
        }
        ExtractionTarget::Function => {
            format!("{}({})", info.name, arg_list)
        }
    };

    match &info.return_strategy {
        ReturnStrategy::TrailingReturn => {
            // The body ends with `return expr;` — the call site passes
            // the return value through.
            out.push_str(call_indent);
            out.push_str("return ");
            out.push_str(&call_expr);
            out.push_str(";\n");
        }
        ReturnStrategy::VoidGuards => {
            // Extracted function returns bool (true = continue).
            // Call site: `if (!extracted(…)) return;`
            out.push_str(call_indent);
            out.push_str("if (!");
            out.push_str(&call_expr);
            out.push_str(") return;\n");
        }
        ReturnStrategy::UniformGuards(value) => {
            // Extracted function returns bool (true = continue).
            // Call site: `if (!extracted(…)) return <value>;`
            out.push_str(call_indent);
            out.push_str("if (!");
            out.push_str(&call_expr);
            out.push_str(") return ");
            out.push_str(value);
            out.push_str(";\n");
        }
        ReturnStrategy::SentinelNull => {
            // Extracted function returns null on fall-through, or the
            // actual value on early exit.
            // Call site:
            //   $result = extracted(…);
            //   if ($result !== null) return $result;
            out.push_str(call_indent);
            out.push_str("$result = ");
            out.push_str(&call_expr);
            out.push_str(";\n");
            out.push_str(call_indent);
            out.push_str("if ($result !== null) return $result;\n");
        }
        ReturnStrategy::NullGuardWithValue(void_guards) => {
            // Guards return null (or were void), the function also
            // computes a value.
            // Call site:
            //   $var = extracted(…);
            //   if ($var === null) return null;  // or `return;`
            if info.returns.len() == 1 {
                out.push_str(call_indent);
                out.push_str(&info.returns[0].0);
                out.push_str(" = ");
                out.push_str(&call_expr);
                out.push_str(";\n");
                out.push_str(call_indent);
                out.push_str("if (");
                out.push_str(&info.returns[0].0);
                if *void_guards {
                    out.push_str(" === null) return;\n");
                } else {
                    out.push_str(" === null) return null;\n");
                }
            }
        }
        ReturnStrategy::None | ReturnStrategy::Unsafe => {
            // Normal extraction.
            if info.returns.is_empty() {
                // No return values — just call the function.
                out.push_str(call_indent);
                out.push_str(&call_expr);
                out.push_str(";\n");
            } else if info.returns.len() == 1 {
                // Single return value — assign it.
                out.push_str(call_indent);
                out.push_str(&info.returns[0].0);
                out.push_str(" = ");
                out.push_str(&call_expr);
                out.push_str(";\n");
            } else {
                // Multiple return values — destructure from array.
                let vars: Vec<&str> = info.returns.iter().map(|(n, _)| n.as_str()).collect();
                out.push_str(call_indent);
                out.push('[');
                out.push_str(&vars.join(", "));
                out.push_str("] = ");
                out.push_str(&call_expr);
                out.push_str(";\n");
            }
        }
    }

    out
}

// ─── Return statement analysis ──────────────────────────────────────────────

/// Analyse `return` statements within the selected range and determine
/// the extraction strategy.
///
/// The returned `ReturnStrategy` tells the code generator how to handle
/// early returns in the extracted code:
/// - `None` — no returns in the selection.
/// - `TrailingReturn` — last statement is `return`, call site uses
///   `return extracted(…)`.
/// - `VoidGuards` / `UniformGuards` / `SentinelNull` — guard-clause
///   patterns that can be safely extracted with special call sites.
/// - `Unsafe` — cannot safely extract.
///
/// `return_value_count` is the number of variables modified inside the
/// selection that are read after it (the scope classifier's
/// `return_values.len()`).  Most guard strategies are rejected when
/// this is non-zero, except `NullGuardWithValue` which handles exactly
/// one return value with all-null guards.
fn analyse_returns(
    content: &str,
    start: usize,
    end: usize,
    return_value_count: usize,
) -> ReturnStrategy {
    let arena = Bump::new();
    let file_id = mago_database::file::FileId::new("extract_fn_ret");
    let program = mago_syntax::parser::parse_file_content(&arena, file_id, content);

    let body_stmts = find_enclosing_body_statements(&program.statements, start as u32);

    // Collect the statements that fall inside the selection.
    let selected: Vec<&Statement<'_>> = body_stmts
        .iter()
        .filter(|stmt| {
            let span = stmt.span();
            let s = span.start.offset as usize;
            let e = span.end.offset as usize;
            s >= start && e <= end
        })
        .copied()
        .collect();

    if selected.is_empty() {
        return ReturnStrategy::None;
    }

    // Check whether the last selected statement is a `return`.
    let has_trailing_return = matches!(selected.last(), Some(Statement::Return(_)));

    // Check whether any statement in the selection contains a return
    // (at any nesting level).
    let any_return = selected.iter().any(|s| selection_stmt_contains_return(s));

    if !any_return {
        return ReturnStrategy::None;
    }

    // When the selection ends with `return`, the call site is
    // `return extracted(…)`, so every return path inside the
    // extracted function propagates correctly.
    if has_trailing_return {
        return ReturnStrategy::TrailingReturn;
    }

    // The selection contains returns but does NOT end with one.
    // Try to find a guard-clause strategy.
    classify_guard_returns(content, &selected, return_value_count)
}

/// Check whether a statement is or contains a `return` at any depth.
fn selection_stmt_contains_return(stmt: &Statement<'_>) -> bool {
    match stmt {
        Statement::Return(_) => true,
        Statement::If(if_stmt) => match &if_stmt.body {
            IfBody::Statement(body) => {
                selection_stmt_contains_return(body.statement)
                    || body
                        .else_if_clauses
                        .iter()
                        .any(|c| selection_stmt_contains_return(c.statement))
                    || body
                        .else_clause
                        .as_ref()
                        .is_some_and(|c| selection_stmt_contains_return(c.statement))
            }
            IfBody::ColonDelimited(body) => {
                body.statements
                    .iter()
                    .any(|s| selection_stmt_contains_return(s))
                    || body.else_if_clauses.iter().any(|c| {
                        c.statements
                            .iter()
                            .any(|s| selection_stmt_contains_return(s))
                    })
                    || body.else_clause.as_ref().is_some_and(|c| {
                        c.statements
                            .iter()
                            .any(|s| selection_stmt_contains_return(s))
                    })
            }
        },
        Statement::Foreach(f) => match &f.body {
            ForeachBody::Statement(s) => selection_stmt_contains_return(s),
            ForeachBody::ColonDelimited(b) => b
                .statements
                .iter()
                .any(|s| selection_stmt_contains_return(s)),
        },
        Statement::While(w) => match &w.body {
            WhileBody::Statement(s) => selection_stmt_contains_return(s),
            WhileBody::ColonDelimited(b) => b
                .statements
                .iter()
                .any(|s| selection_stmt_contains_return(s)),
        },
        Statement::DoWhile(dw) => selection_stmt_contains_return(dw.statement),
        Statement::For(f) => match &f.body {
            ForBody::Statement(s) => selection_stmt_contains_return(s),
            ForBody::ColonDelimited(b) => b
                .statements
                .iter()
                .any(|s| selection_stmt_contains_return(s)),
        },
        Statement::Switch(sw) => sw.body.cases().iter().any(|c| match c {
            SwitchCase::Expression(e) => e
                .statements
                .iter()
                .any(|s| selection_stmt_contains_return(s)),
            SwitchCase::Default(d) => d
                .statements
                .iter()
                .any(|s| selection_stmt_contains_return(s)),
        }),
        Statement::Try(t) => {
            t.block
                .statements
                .iter()
                .any(|s| selection_stmt_contains_return(s))
                || t.catch_clauses.iter().any(|c| {
                    c.block
                        .statements
                        .iter()
                        .any(|s| selection_stmt_contains_return(s))
                })
                || t.finally_clause.as_ref().is_some_and(|f| {
                    f.block
                        .statements
                        .iter()
                        .any(|s| selection_stmt_contains_return(s))
                })
        }
        Statement::Block(b) => b
            .statements
            .iter()
            .any(|s| selection_stmt_contains_return(s)),
        _ => false,
    }
}

// ─── Return strategy ────────────────────────────────────────────────────────

/// How to handle return statements in the extracted code.
///
/// When the selection contains `return` statements that are NOT the last
/// statement, naive extraction would break control flow.  This enum
/// describes the strategy for preserving the caller's early-exit
/// semantics.
#[derive(Debug, Clone, PartialEq, Eq)]
enum ReturnStrategy {
    /// No return statements in the selection.
    None,
    /// The last selected statement is a `return` — the call site becomes
    /// `return extracted(…)` and every return path propagates correctly.
    TrailingReturn,
    /// All returns are bare `return;` (void guards).  The extracted
    /// function returns `bool` (true = continue, false = exit early)
    /// and the call site is `if (!extracted(…)) return;`.
    VoidGuards,
    /// All returns return the same non-null literal value.  The
    /// extracted function returns `bool` and the call site is
    /// `if (!extracted(…)) return <value>;`.
    ///
    /// The string is the source text of the common return value.
    UniformGuards(String),
    /// Returns have different non-null values — use `null` as a
    /// sentinel for "no early exit."  The extracted function returns
    /// `?<type>` and the call site is:
    /// ```php
    /// $result = extracted(…);
    /// if ($result !== null) return $result;
    /// ```
    SentinelNull,
    /// All guard returns are `null` (or bare `return;`) and the
    /// selection also computes exactly one return value.  The extracted
    /// function returns the computed value on success or `null` when a
    /// guard fires.  The call site assigns the result and checks for
    /// null:
    /// ```php
    /// $var = extracted(…);
    /// if ($var === null) return null;  // or `return;` for void guards
    /// ```
    ///
    /// The `bool` flag is `true` when the original guards were bare
    /// `return;` (void).  In that case the body's `return;` statements
    /// are rewritten to `return null;`, and the call site uses bare
    /// `return;` instead of `return null;`.
    NullGuardWithValue(bool),
    /// Cannot safely extract (e.g. returns null, or modified variables
    /// are used after the selection).
    Unsafe,
}

/// Collect the source text of every `return` expression in the selected
/// statements.
///
/// Bare `return;` is represented as `None`.  `return expr;` yields
/// `Some("expr")` with the expression's source text.
fn collect_return_expressions<'a>(
    content: &'a str,
    stmts: &[&Statement<'_>],
) -> Vec<Option<&'a str>> {
    let mut out = Vec::new();
    for stmt in stmts {
        collect_returns_from_stmt(content, stmt, &mut out);
    }
    out
}

/// Recursively collect return expressions from a single statement.
fn collect_returns_from_stmt<'a>(
    content: &'a str,
    stmt: &Statement<'_>,
    out: &mut Vec<Option<&'a str>>,
) {
    match stmt {
        Statement::Return(ret) => {
            let expr_text = ret.value.as_ref().map(|expr| {
                let s = expr.span().start.offset as usize;
                let e = expr.span().end.offset as usize;
                content[s..e].trim()
            });
            out.push(expr_text);
        }
        Statement::If(if_stmt) => match &if_stmt.body {
            IfBody::Statement(body) => {
                collect_returns_from_stmt(content, body.statement, out);
                for c in &body.else_if_clauses {
                    collect_returns_from_stmt(content, c.statement, out);
                }
                if let Some(c) = &body.else_clause {
                    collect_returns_from_stmt(content, c.statement, out);
                }
            }
            IfBody::ColonDelimited(body) => {
                for s in &body.statements {
                    collect_returns_from_stmt(content, s, out);
                }
                for c in &body.else_if_clauses {
                    for s in &c.statements {
                        collect_returns_from_stmt(content, s, out);
                    }
                }
                if let Some(c) = &body.else_clause {
                    for s in &c.statements {
                        collect_returns_from_stmt(content, s, out);
                    }
                }
            }
        },
        Statement::Foreach(f) => match &f.body {
            ForeachBody::Statement(s) => collect_returns_from_stmt(content, s, out),
            ForeachBody::ColonDelimited(b) => {
                for s in &b.statements {
                    collect_returns_from_stmt(content, s, out);
                }
            }
        },
        Statement::While(w) => match &w.body {
            WhileBody::Statement(s) => collect_returns_from_stmt(content, s, out),
            WhileBody::ColonDelimited(b) => {
                for s in &b.statements {
                    collect_returns_from_stmt(content, s, out);
                }
            }
        },
        Statement::DoWhile(dw) => collect_returns_from_stmt(content, dw.statement, out),
        Statement::For(f) => match &f.body {
            ForBody::Statement(s) => collect_returns_from_stmt(content, s, out),
            ForBody::ColonDelimited(b) => {
                for s in &b.statements {
                    collect_returns_from_stmt(content, s, out);
                }
            }
        },
        Statement::Switch(sw) => {
            for c in sw.body.cases().iter() {
                let stmts = match c {
                    SwitchCase::Expression(e) => &e.statements,
                    SwitchCase::Default(d) => &d.statements,
                };
                for s in stmts.iter() {
                    collect_returns_from_stmt(content, s, out);
                }
            }
        }
        Statement::Try(t) => {
            for s in &t.block.statements {
                collect_returns_from_stmt(content, s, out);
            }
            for c in &t.catch_clauses {
                for s in &c.block.statements {
                    collect_returns_from_stmt(content, s, out);
                }
            }
            if let Some(f) = &t.finally_clause {
                for s in &f.block.statements {
                    collect_returns_from_stmt(content, s, out);
                }
            }
        }
        Statement::Block(b) => {
            for s in &b.statements {
                collect_returns_from_stmt(content, s, out);
            }
        }
        _ => {}
    }
}

/// Classify the return strategy for a selection that contains return
/// statements but does NOT end with one.
///
/// This is called only when `has_unsafe_return` would have been `true`
/// under the old logic.  It inspects the actual return expressions to
/// decide whether a safe extraction pattern exists.
fn classify_guard_returns(
    content: &str,
    stmts: &[&Statement<'_>],
    return_value_count: usize,
) -> ReturnStrategy {
    let return_exprs = collect_return_expressions(content, stmts);
    if return_exprs.is_empty() {
        return ReturnStrategy::Unsafe;
    }

    // When the selection modifies variables that are used after it,
    // most guard strategies can't work — we'd need to return both
    // the sentinel and the modified variables.  The exception is
    // NullGuardWithValue: all guards return null (or bare return;),
    // exactly one return value, and the extracted function returns
    // the value or null.
    if return_value_count > 0 {
        if return_value_count != 1 {
            return ReturnStrategy::Unsafe;
        }
        // All bare `return;` → NullGuardWithValue(true) (void guards).
        if return_exprs.iter().all(|e| e.is_none()) {
            return ReturnStrategy::NullGuardWithValue(true);
        }
        // All `return null;` → NullGuardWithValue(false).
        if return_exprs.iter().any(|e| e.is_none()) {
            // Mix of bare and valued returns — can't handle.
            return ReturnStrategy::Unsafe;
        }
        let all_null = return_exprs
            .iter()
            .all(|e| e.unwrap().trim().eq_ignore_ascii_case("null"));
        if all_null {
            return ReturnStrategy::NullGuardWithValue(false);
        }
        return ReturnStrategy::Unsafe;
    }

    // Case 1: All returns are bare `return;` (void guards).
    if return_exprs.iter().all(|e| e.is_none()) {
        return ReturnStrategy::VoidGuards;
    }

    // If any return is bare but others aren't, we have a mix of void
    // and valued returns — can't handle this.
    if return_exprs.iter().any(|e| e.is_none()) {
        return ReturnStrategy::Unsafe;
    }

    // All returns have values.  Check if any returns null.
    let values: Vec<&str> = return_exprs.iter().map(|e| e.unwrap()).collect();
    let any_returns_null = values.iter().any(|v| {
        let lower = v.trim().to_lowercase();
        lower == "null"
    });

    // Case 2: All return the same value.
    let all_same = values.windows(2).all(|w| w[0].trim() == w[1].trim());
    if all_same {
        let value = values[0].trim().to_string();
        // If the uniform value is `true` or `false`, we can use the
        // inverse as the sentinel — the cleanest possible output.
        let lower = value.to_lowercase();
        if lower == "false" || lower == "true" {
            return ReturnStrategy::UniformGuards(value);
        }
        // If the uniform value is `null`, we can't use null as sentinel,
        // but we can still use bool: the extracted function returns bool,
        // and the call site does `if (!extracted()) return null;`.
        if lower == "null" {
            return ReturnStrategy::UniformGuards(value);
        }
        // For other uniform values, if it's not null, bool flag works.
        return ReturnStrategy::UniformGuards(value);
    }

    // Case 3: Different values, none are null — use null sentinel.
    if !any_returns_null {
        return ReturnStrategy::SentinelNull;
    }

    // Different values including null — can't use null as sentinel
    // and can't use bool flag either.
    ReturnStrategy::Unsafe
}

/// Resolve the return type of the enclosing function/method at `offset`.
///
/// Extracts the native return type hint from the function signature.
/// Extract the parameter names of the enclosing function/method in
/// declaration order.  Used to sort extracted-function parameters so
/// they mirror the original signature.
fn resolve_enclosing_param_order(content: &str, offset: u32) -> Vec<String> {
    let arena = Bump::new();
    let file_id = mago_database::file::FileId::new("extract_fn_pord");
    let program = mago_syntax::parser::parse_file_content(&arena, file_id, content);

    let ctx = find_cursor_context(&program.statements, offset);

    let param_list = match ctx {
        CursorContext::InClassLike { member, .. } => {
            if let MemberContext::Method(method, true) = member {
                Some(&method.parameter_list)
            } else {
                None
            }
        }
        CursorContext::InFunction(func, true) => Some(&func.parameter_list),
        _ => None,
    };

    match param_list {
        Some(pl) => pl
            .parameters
            .iter()
            .map(|p| p.variable.name.to_string())
            .collect(),
        None => Vec::new(),
    }
}

/// Sort extracted-function parameters so that variables matching the
/// enclosing function's signature come first (in their original order),
/// followed by any other variables in classification order.
fn sort_params_by_enclosing_order(
    mut params: Vec<(String, PhpType, PhpType)>,
    enclosing_order: &[String],
) -> Vec<(String, PhpType, PhpType)> {
    if enclosing_order.is_empty() {
        return params;
    }
    params.sort_by(|a, b| {
        let idx_a = enclosing_order.iter().position(|n| *n == a.0);
        let idx_b = enclosing_order.iter().position(|n| *n == b.0);
        match (idx_a, idx_b) {
            // Both are signature params → preserve signature order.
            (Some(ia), Some(ib)) => ia.cmp(&ib),
            // Signature params come before non-signature variables.
            (Some(_), None) => std::cmp::Ordering::Less,
            (None, Some(_)) => std::cmp::Ordering::Greater,
            // Neither is a signature param → preserve classification order.
            (None, None) => std::cmp::Ordering::Equal,
        }
    });
    params
}

fn resolve_enclosing_return_type(content: &str, offset: u32) -> PhpType {
    let arena = Bump::new();
    let file_id = mago_database::file::FileId::new("extract_fn_rtype");
    let program = mago_syntax::parser::parse_file_content(&arena, file_id, content);

    let ctx = find_cursor_context(&program.statements, offset);

    match ctx {
        CursorContext::InClassLike { member, .. } => {
            if let MemberContext::Method(method, true) = member {
                return method
                    .return_type_hint
                    .as_ref()
                    .map(|h| crate::parser::extract_hint_type(&h.hint))
                    .unwrap_or_else(PhpType::untyped);
            }
            PhpType::untyped()
        }
        CursorContext::InFunction(func, true) => func
            .return_type_hint
            .as_ref()
            .map(|h| crate::parser::extract_hint_type(&h.hint))
            .unwrap_or_else(PhpType::untyped),
        _ => PhpType::untyped(),
    }
}

// ─── Main code action collector ─────────────────────────────────────────────

impl Backend {
    /// Collect "Extract Function" / "Extract Method" code actions.
    ///
    /// This action is offered when the user has a non-empty selection
    /// that covers one or more complete statements inside a function or
    /// method body.
    ///
    /// Phase 1 performs lightweight validation only.  The expensive
    /// work (scope classification, type resolution, PHPDoc generation,
    /// edit building) is deferred to [`resolve_extract_function`]
    /// (Phase 2).
    pub(crate) fn collect_extract_function_actions(
        &self,
        uri: &str,
        content: &str,
        params: &CodeActionParams,
        out: &mut Vec<CodeActionOrCommand>,
    ) {
        // Only activate when the selection is non-empty.
        if params.range.start == params.range.end {
            return;
        }

        let start_offset = position_to_byte_offset(content, params.range.start);
        let end_offset = position_to_byte_offset(content, params.range.end);

        // Trim the selection to exclude leading/trailing whitespace.
        let (start, end) = match trim_selection(content, start_offset, end_offset) {
            Some(range) => range,
            None => return,
        };

        // Validate that the selection covers complete statements.
        if !selection_covers_complete_statements(content, start, end) {
            return;
        }

        // ── Determine method vs function for the title ──────────────
        // We only need to know whether `$this`/`self::`/`static::` is
        // referenced to pick "Extract method" vs "Extract function".
        // A simple text scan is sufficient for the title — the full
        // scope analysis happens in Phase 2.
        let selected_text = &content[start..end];
        let looks_like_method = selected_text.contains("$this")
            || selected_text.contains("self::")
            || selected_text.contains("static::")
            || selected_text.contains("parent::");

        let title = if looks_like_method {
            "Extract method".to_string()
        } else {
            "Extract function".to_string()
        };

        // Phase 1: emit a lightweight code action with no edit.
        // The full workspace edit is computed lazily in
        // `resolve_extract_function` (Phase 2) when the user picks
        // this action.
        out.push(CodeActionOrCommand::CodeAction(CodeAction {
            title,
            kind: Some(CodeActionKind::REFACTOR_EXTRACT),
            diagnostics: None,
            edit: None,
            command: None,
            is_preferred: Some(false),
            disabled: None,
            data: Some(make_code_action_data(
                "refactor.extractFunction",
                uri,
                &params.range,
                serde_json::json!({}),
            )),
        }));
    }

    /// Resolve types for a list of variable names at a given offset.
    ///
    /// Returns `(dollar_name, cleaned_type, raw_hint)` triples.
    /// `cleaned_type` has generics stripped for use in native PHP
    /// signatures.  `raw_hint` preserves the full resolved type
    /// (e.g. `Collection<User>`) for PHPDoc generation.
    fn resolve_param_types(
        &self,
        uri: &str,
        content: &str,
        offset: u32,
        var_names: &[String],
    ) -> Vec<(String, PhpType, PhpType)> {
        var_names
            .iter()
            .map(|name| {
                let dollar_name = if name.starts_with('$') {
                    name.clone()
                } else {
                    format!("${}", name)
                };
                let resolved_type = resolve_var_type(self, &dollar_name, content, offset, uri);
                let raw_type = resolved_type.clone().unwrap_or_else(PhpType::untyped);
                // Clean up the type for use in a signature — stays as PhpType.
                let cleaned = resolved_type
                    .as_ref()
                    .and_then(clean_type_for_signature_typed)
                    .unwrap_or_else(PhpType::untyped);
                (dollar_name, cleaned, raw_type)
            })
            .collect()
    }

    /// Resolve a deferred "Extract Function/Method" code action.
    ///
    /// This is **Phase 2** of the two-phase code-action model.  Phase 1
    /// (`collect_extract_function_actions`) already validated the
    /// selection and emitted a lightweight `CodeAction` with a title
    /// but no edit.  Here we re-run the full extraction logic from the
    /// selection range stored in `data` and produce the workspace edit.
    pub(crate) fn resolve_extract_function(
        &self,
        data: &CodeActionData,
        content: &str,
    ) -> Option<WorkspaceEdit> {
        let uri = &data.uri;
        let range = &data.range;

        // ── Re-validate the selection (content may have changed) ────
        let start_offset = position_to_byte_offset(content, range.start);
        let end_offset = position_to_byte_offset(content, range.end);

        let (start, end) = trim_selection(content, start_offset, end_offset)?;

        if !selection_covers_complete_statements(content, start, end) {
            return None;
        }

        // ── Scope map & classification ──────────────────────────────
        let scope_map = build_scope_map(content, start as u32);
        let classification = scope_map.classify_range(start as u32, end as u32);

        let return_value_count = classification.return_values.len();
        let return_strategy = analyse_returns(content, start, end, return_value_count);

        if return_strategy == ReturnStrategy::Unsafe {
            return None;
        }

        let uses_this = if scope_map.has_this_or_self {
            classification.uses_this
        } else {
            false
        };

        if scope_map.uses_reference_params() && !classification.reference_writes.is_empty() {
            return None;
        }

        if classification.return_values.len() > 4 {
            return None;
        }

        // ── Enclosing context ───────────────────────────────────────
        let enclosing = find_enclosing_context(content, start as u32, uses_this)?;

        // ── Naming ──────────────────────────────────────────────────
        let body_line_start_for_naming = find_line_start(content, start);
        let body_text_for_naming = &content[body_line_start_for_naming..end];
        let pre_trailing_return_type = if matches!(return_strategy, ReturnStrategy::TrailingReturn)
        {
            resolve_enclosing_return_type(content, start as u32)
        } else {
            PhpType::untyped()
        };
        let naming_ctx = NamingContext {
            enclosing_name: &enclosing.enclosing_name,
            return_strategy: &return_strategy,
            body_text: body_text_for_naming,
            return_var_names: &classification.return_values,
            trailing_return_type: &pre_trailing_return_type,
        };
        let fn_name = generate_function_name(content, &enclosing, &naming_ctx);

        // ── Type resolution ─────────────────────────────────────────
        let typed_params =
            self.resolve_param_types(uri, content, start as u32, &classification.parameters);
        let enclosing_param_order = resolve_enclosing_param_order(content, start as u32);
        let typed_params = sort_params_by_enclosing_order(typed_params, &enclosing_param_order);
        let typed_returns =
            self.resolve_param_types(uri, content, start as u32, &classification.return_values);

        // ── Indentation ─────────────────────────────────────────────
        let call_indent = indent_at(content, start);
        let (member_indent, body_indent) = match enclosing.target {
            ExtractionTarget::Method => {
                let member = detect_line_indent(content, enclosing.body_start);
                let unit = detect_indent_unit(content);
                let body = format!("{}{}", member, unit);
                (member, body)
            }
            ExtractionTarget::Function => {
                let member = String::new();
                let unit = detect_indent_unit(content);
                (member, unit.to_string())
            }
        };

        // ── Body text ───────────────────────────────────────────────
        let body_line_start = find_line_start(content, start);
        let body_text = content[body_line_start..end].to_string();

        // ── Return type resolution ──────────────────────────────────
        let trailing_return_type = if matches!(
            return_strategy,
            ReturnStrategy::TrailingReturn
                | ReturnStrategy::SentinelNull
                | ReturnStrategy::NullGuardWithValue(_)
        ) {
            resolve_enclosing_return_type(content, start as u32)
        } else {
            PhpType::untyped()
        };

        let enclosing_docblock_return: Option<PhpType> = if matches!(
            return_strategy,
            ReturnStrategy::TrailingReturn | ReturnStrategy::SentinelNull
        ) {
            crate::docblock::find_enclosing_return_type(content, start)
        } else {
            None
        };

        // ── PHPDoc generation ───────────────────────────────────────
        let return_type_for_docblock = build_return_type_hint_for_docblock(
            &return_strategy,
            &trailing_return_type,
            &typed_returns,
        );
        let raw_return_type_for_docblock = build_raw_return_type_for_docblock(
            &return_strategy,
            &trailing_return_type,
            enclosing_docblock_return.as_ref(),
            &typed_returns,
        );
        let ctx = self.file_context(uri);
        let class_loader = self.class_loader(&ctx);
        let docblock = build_docblock_for_extraction(
            &typed_params,
            &return_type_for_docblock,
            &raw_return_type_for_docblock,
            &member_indent,
            &class_loader,
        );

        // ── Build ExtractionInfo ────────────────────────────────────
        let params_for_info: Vec<(String, PhpType)> = typed_params
            .iter()
            .map(|(name, cleaned, _)| (name.clone(), cleaned.clone()))
            .collect();
        let returns_for_info: Vec<(String, PhpType)> = typed_returns
            .iter()
            .map(|(name, cleaned, _)| (name.clone(), cleaned.clone()))
            .collect();

        let info = ExtractionInfo {
            name: fn_name,
            params: params_for_info,
            returns: returns_for_info,
            body: body_text,
            target: enclosing.target,
            is_static: enclosing.is_static,
            member_indent,
            body_indent,
            return_strategy,
            trailing_return_type,
            docblock,
        };

        // ── Build edits ─────────────────────────────────────────────
        let definition = build_extracted_definition(&info);
        let call_site = build_call_site(&info, &call_indent);

        let doc_uri: Url = uri.parse().ok()?;

        let replace_start = find_line_start(content, start);
        let replace_end = find_line_end(content, end.saturating_sub(1).max(start));

        let replace_start_pos = offset_to_position(content, replace_start);
        let replace_end_pos = offset_to_position(content, replace_end);

        let insert_pos = offset_to_position(content, enclosing.insert_offset);

        let edits = vec![
            TextEdit {
                range: Range {
                    start: replace_start_pos,
                    end: replace_end_pos,
                },
                new_text: call_site,
            },
            TextEdit {
                range: Range {
                    start: insert_pos,
                    end: insert_pos,
                },
                new_text: definition,
            },
        ];

        let mut changes = HashMap::new();
        changes.insert(doc_uri, edits);

        Some(WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        })
    }
}

/// Clean a resolved type string for use in a function signature.
///
/// Removes generic parameters (PHP doesn't support them in signatures),
/// and simplifies union types that are too complex for type hints.
/// Compute the raw (un-cleaned) return type hint string for PHPDoc
/// enrichment purposes.  Unlike `build_return_type` (which strips
/// generics for native hints), this preserves the full type so that
/// `enrichment_plain` can detect whether a docblock `@return` tag is
/// warranted.
fn build_return_type_hint_for_docblock(
    strategy: &ReturnStrategy,
    trailing_return_type: &PhpType,
    returns: &[(String, PhpType, PhpType)],
) -> PhpType {
    match strategy {
        ReturnStrategy::TrailingReturn => trailing_return_type.clone(),
        ReturnStrategy::VoidGuards | ReturnStrategy::UniformGuards(_) => PhpType::bool(),
        ReturnStrategy::SentinelNull => {
            if !trailing_return_type.is_empty() {
                trailing_return_type.clone()
            } else {
                PhpType::untyped()
            }
        }
        ReturnStrategy::NullGuardWithValue(_) => {
            if returns.len() == 1 {
                if let Some(hint) = returns[0].1.to_native_hint_typed() {
                    return hint;
                }
                PhpType::untyped()
            } else {
                PhpType::untyped()
            }
        }
        ReturnStrategy::None | ReturnStrategy::Unsafe => {
            if returns.is_empty() {
                PhpType::void()
            } else if returns.len() == 1 {
                if let Some(hint) = returns[0].1.to_native_hint_typed() {
                    return hint;
                }
                PhpType::untyped()
            } else {
                PhpType::array()
            }
        }
    }
}

/// Like `build_return_type_hint_for_docblock` but returns the raw
/// (un-cleaned) type that preserves concrete generic arguments.
fn build_raw_return_type_for_docblock(
    strategy: &ReturnStrategy,
    trailing_return_type: &PhpType,
    enclosing_docblock_return: Option<&PhpType>,
    returns: &[(String, PhpType, PhpType)],
) -> PhpType {
    match strategy {
        ReturnStrategy::TrailingReturn => {
            // Prefer the docblock @return type when it carries concrete
            // generics (e.g. `Collection<User>`) over the native hint
            // (e.g. `Collection`).
            if let Some(edr) = enclosing_docblock_return
                && edr.has_type_parameters()
            {
                return edr.clone();
            }
            trailing_return_type.clone()
        }
        ReturnStrategy::VoidGuards | ReturnStrategy::UniformGuards(_) => PhpType::bool(),
        ReturnStrategy::SentinelNull => {
            if let Some(edr) = enclosing_docblock_return
                && edr.has_type_parameters()
            {
                return edr.clone();
            }
            if !trailing_return_type.is_empty() {
                trailing_return_type.clone()
            } else {
                PhpType::untyped()
            }
        }
        ReturnStrategy::NullGuardWithValue(_) => {
            // Use raw type (index 2) which preserves generics.
            if returns.len() == 1 && !returns[0].2.is_empty() {
                returns[0].2.clone()
            } else {
                PhpType::untyped()
            }
        }
        ReturnStrategy::None | ReturnStrategy::Unsafe => {
            if returns.is_empty() {
                PhpType::void()
            } else if returns.len() == 1 {
                // Use raw type (index 2) which preserves generics.
                returns[0].2.clone()
            } else {
                PhpType::array()
            }
        }
    }
}

#[cfg(test)]
fn clean_type_for_signature(type_str: &str) -> String {
    if type_str.is_empty() {
        return String::new();
    }

    let parsed = PhpType::parse(type_str);
    parsed.to_native_hint().unwrap_or_default()
}

/// Like [`clean_type_for_signature`] but accepts an already-parsed
/// [`PhpType`] and returns a structured [`PhpType`] instead of a
/// `String`, avoiding a redundant `PhpType::parse` round-trip.
fn clean_type_for_signature_typed(ty: &PhpType) -> Option<PhpType> {
    ty.to_native_hint_typed()
}

// ─── Tests ──────────────────────────────────────────────────────────────────

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

    // ── Enclosing return type resolution ────────────────────────────

    #[test]
    fn resolve_return_type_standalone_function() {
        let php = "<?php\nfunction classify(int $code): string\n{\n    if ($code < 0) return 'negative';\n    return 'ok';\n}\n";
        let offset = php.find("if ($code").unwrap() as u32;
        let result = resolve_enclosing_return_type(php, offset);
        assert_eq!(
            result,
            PhpType::parse("string"),
            "should resolve enclosing function return type"
        );
    }

    #[test]
    fn resolve_return_type_method() {
        let php = "<?php\nclass Foo {\n    public function bar(): int\n    {\n        return 42;\n    }\n}\n";
        let offset = php.find("return 42").unwrap() as u32;
        let result = resolve_enclosing_return_type(php, offset);
        assert_eq!(
            result,
            PhpType::parse("int"),
            "should resolve enclosing method return type"
        );
    }

    // ── Statement boundary validation ───────────────────────────────

    #[test]
    fn complete_statements_single() {
        let php = "<?php\nfunction foo() {\n    $x = 1;\n    $y = 2;\n}\n";
        // Select `$x = 1;`
        let start = php.find("$x = 1;").unwrap();
        let end = start + "$x = 1;".len();
        assert!(selection_covers_complete_statements(php, start, end));
    }

    #[test]
    fn complete_statements_multiple() {
        let php = "<?php\nfunction foo() {\n    $x = 1;\n    $y = 2;\n    $z = 3;\n}\n";
        let start = php.find("$x = 1;").unwrap();
        let end = php.find("$y = 2;").unwrap() + "$y = 2;".len();
        assert!(selection_covers_complete_statements(php, start, end));
    }

    #[test]
    fn incomplete_statement_rejected() {
        let php = "<?php\nfunction foo() {\n    $x = 1;\n}\n";
        // Select just `$x = ` (incomplete).
        let start = php.find("$x = 1;").unwrap();
        let end = start + "$x =".len();
        assert!(!selection_covers_complete_statements(php, start, end));
    }

    #[test]
    fn partial_if_rejected() {
        let php = "<?php\nfunction foo() {\n    if ($x) {\n        $y = 1;\n    }\n}\n";
        // Select just the body of the if without the if itself.
        let start = php.find("$y = 1;").unwrap();
        let end = start + "$y = 1;".len();
        // This is inside the if body — those ARE complete statements
        // within the if block, but they're not top-level statements in
        // the function body.  The validator checks against the function
        // body's direct children, so this should fail.
        assert!(!selection_covers_complete_statements(php, start, end));
    }

    #[test]
    fn complete_if_accepted() {
        let php =
            "<?php\nfunction foo() {\n    if ($x) {\n        $y = 1;\n    }\n    $z = 2;\n}\n";
        // Select the entire if statement.
        let start = php.find("if ($x)").unwrap();
        let end = php.find("    }\n    $z").unwrap() + "    }".len();
        assert!(selection_covers_complete_statements(php, start, end));
    }

    // ── Selection trimming ──────────────────────────────────────────

    #[test]
    fn trim_whitespace() {
        let content = "  hello world  ";
        let result = trim_selection(content, 0, content.len());
        assert_eq!(result, Some((2, 13)));
    }

    #[test]
    fn trim_empty_rejected() {
        let content = "   ";
        assert_eq!(trim_selection(content, 0, content.len()), None);
    }

    // ── Return detection ────────────────────────────────────────────

    #[test]
    fn detects_trailing_return() {
        let php = "<?php\nfunction foo() {\n    $x = 1;\n    return $x;\n}\n";
        let start = php.find("$x = 1;").unwrap();
        let end = php.find("return $x;").unwrap() + "return $x;".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(strategy, ReturnStrategy::TrailingReturn);
    }

    #[test]
    fn detects_unsafe_return_without_trailing() {
        // `return 1;` followed by `$x = 2;` — the return doesn't end
        // the selection, and the values are mixed (not guard clauses),
        // so this can use sentinel-null (1 is not null).
        let php = "<?php\nfunction foo() {\n    return 1;\n    $x = 2;\n}\n";
        let start = php.find("return 1;").unwrap();
        let end = php.find("$x = 2;").unwrap() + "$x = 2;".len();
        let strategy = analyse_returns(php, start, end, 0);
        // `$x = 2;` is NOT a return, but there IS a return in the
        // selection that doesn't end it.  The only return value is `1`
        // → uniform guards with value "1".
        assert_eq!(
            strategy,
            ReturnStrategy::UniformGuards("1".to_string()),
            "single non-null return value should use uniform guards"
        );
    }

    #[test]
    fn no_false_positive_on_return_in_identifier() {
        let php = "<?php\nfunction foo() {\n    $returnValue = 1;\n}\n";
        let start = php.find("$returnValue").unwrap();
        let end = start + "$returnValue = 1;".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(strategy, ReturnStrategy::None);
    }

    #[test]
    fn nested_return_safe_when_trailing_return_present() {
        // Guard clause pattern: `if (!$x) return 0;` followed by
        // a trailing `return $result;`.  Since the selection ends
        // with return, ALL returns are safe (call site will be
        // `return extracted(…)`).
        let php = "<?php\nfunction foo($x) {\n    if (!$x) return 0;\n    $r = $x * 2;\n    return $r;\n}\n";
        let start = php.find("if (!$x)").unwrap();
        let end = php.find("return $r;").unwrap() + "return $r;".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(strategy, ReturnStrategy::TrailingReturn);
    }

    #[test]
    fn nested_return_unsafe_without_trailing_return() {
        // Return inside an if, but the selection does NOT end with return.
        // The return value is `1` (not null) → uses sentinel-null since
        // there are no modified variables.
        let php = "<?php\nfunction foo($x) {\n    if ($x) {\n        return 1;\n    }\n    echo 'done';\n}\n";
        let start = php.find("if ($x)").unwrap();
        let end = php.find("echo 'done';").unwrap() + "echo 'done';".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(
            strategy,
            ReturnStrategy::UniformGuards("1".to_string()),
            "single non-null return should use uniform guards"
        );
    }

    // ── Guard return strategies ─────────────────────────────────────

    #[test]
    fn void_guards_strategy() {
        // All returns are bare `return;` → VoidGuards.
        let php = "<?php\nfunction foo($x, $y) {\n    if (!$x) return;\n    if (!$y) return;\n    echo 'ok';\n}\n";
        let start = php.find("if (!$x)").unwrap();
        let end = php.find("echo 'ok';").unwrap() + "echo 'ok';".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(strategy, ReturnStrategy::VoidGuards);
    }

    #[test]
    fn uniform_false_guards_strategy() {
        // All returns are `return false;` → UniformGuards("false").
        let php = "<?php\nfunction foo($x, $y) {\n    if (!$x) return false;\n    if (!$y) return false;\n    echo 'ok';\n}\n";
        let start = php.find("if (!$x)").unwrap();
        let end = php.find("echo 'ok';").unwrap() + "echo 'ok';".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(strategy, ReturnStrategy::UniformGuards("false".to_string()));
    }

    #[test]
    fn uniform_null_guards_strategy() {
        // All returns are `return null;` → UniformGuards("null").
        // This works because the bool-flag approach doesn't need null
        // as a sentinel.
        let php = "<?php\nfunction foo($id) {\n    if ($id <= 0) return null;\n    if (!$this->exists($id)) return null;\n    echo 'ok';\n}\n";
        let start = php.find("if ($id").unwrap();
        let end = php.find("echo 'ok';").unwrap() + "echo 'ok';".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(strategy, ReturnStrategy::UniformGuards("null".to_string()));
    }

    #[test]
    fn sentinel_null_strategy() {
        // Different non-null return values → SentinelNull.
        let php = "<?php\nfunction foo($x) {\n    if ($x < 0) return 'negative';\n    if ($x > 100) return 'overflow';\n    echo 'ok';\n}\n";
        let start = php.find("if ($x < 0)").unwrap();
        let end = php.find("echo 'ok';").unwrap() + "echo 'ok';".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(strategy, ReturnStrategy::SentinelNull);
    }

    #[test]
    fn mixed_null_and_other_values_is_unsafe() {
        // Returns include null AND other values → Unsafe (can't use
        // null as sentinel when null is also a valid return).
        let php = "<?php\nfunction foo($x) {\n    if ($x < 0) return null;\n    if ($x > 100) return 'overflow';\n    echo 'ok';\n}\n";
        let start = php.find("if ($x < 0)").unwrap();
        let end = php.find("echo 'ok';").unwrap() + "echo 'ok';".len();
        let strategy = analyse_returns(php, start, end, 0);
        assert_eq!(strategy, ReturnStrategy::Unsafe);
    }

    #[test]
    fn guard_with_return_values_is_unsafe() {
        // Selection has return values (modified variables read after
        // the selection) — can't use guard strategies unless all
        // guards return null and there's exactly 1 return value.
        let php = "<?php\nfunction foo($x) {\n    if (!$x) return false;\n    echo 'ok';\n}\n";
        let start = php.find("if (!$x)").unwrap();
        let end = php.find("echo 'ok';").unwrap() + "echo 'ok';".len();
        let strategy = analyse_returns(php, start, end, 1);
        assert_eq!(strategy, ReturnStrategy::Unsafe);
    }

    #[test]
    fn guard_with_multiple_return_values_is_unsafe() {
        // More than 1 return value — even null guards can't help.
        let php =
            "<?php\nfunction foo($x) {\n    if (!$x) return null;\n    $a = 1;\n    $b = 2;\n}\n";
        let start = php.find("if (!$x)").unwrap();
        let end = php.find("$b = 2;").unwrap() + "$b = 2;".len();
        let strategy = analyse_returns(php, start, end, 2);
        assert_eq!(strategy, ReturnStrategy::Unsafe);
    }

    #[test]
    fn null_guard_with_single_return_value() {
        // All guards return null, exactly 1 return value →
        // NullGuardWithValue(false).
        let php = "<?php\nfunction foo($obj) {\n    if (!$obj) return null;\n    $val = $obj->compute();\n}\n";
        let start = php.find("if (!$obj)").unwrap();
        let end = php.find("$val = $obj->compute();").unwrap() + "$val = $obj->compute();".len();
        let strategy = analyse_returns(php, start, end, 1);
        assert_eq!(strategy, ReturnStrategy::NullGuardWithValue(false));
    }

    #[test]
    fn void_guard_with_single_return_value() {
        // All guards are bare `return;`, exactly 1 return value →
        // NullGuardWithValue(true).
        let php =
            "<?php\nfunction foo($obj) {\n    if (!$obj) return;\n    $val = $obj->compute();\n}\n";
        let start = php.find("if (!$obj)").unwrap();
        let end = php.find("$val = $obj->compute();").unwrap() + "$val = $obj->compute();".len();
        let strategy = analyse_returns(php, start, end, 1);
        assert_eq!(strategy, ReturnStrategy::NullGuardWithValue(true));
    }

    #[test]
    fn non_null_guard_with_return_value_is_unsafe() {
        // Guards return false (not null) with a return value — can't
        // use NullGuardWithValue, and other strategies can't handle
        // return values.
        let php = "<?php\nfunction foo($obj) {\n    if (!$obj) return false;\n    $val = $obj->compute();\n}\n";
        let start = php.find("if (!$obj)").unwrap();
        let end = php.find("$val = $obj->compute();").unwrap() + "$val = $obj->compute();".len();
        let strategy = analyse_returns(php, start, end, 1);
        assert_eq!(strategy, ReturnStrategy::Unsafe);
    }

    // ── Type hint validation ────────────────────────────────────────

    #[test]
    fn clean_scalar_types() {
        assert_eq!(clean_type_for_signature("int"), "int");
        assert_eq!(clean_type_for_signature("string"), "string");
        assert_eq!(clean_type_for_signature("bool"), "bool");
        assert_eq!(clean_type_for_signature("float"), "float");
        assert_eq!(clean_type_for_signature("array"), "array");
        assert_eq!(clean_type_for_signature("void"), "void");
        assert_eq!(clean_type_for_signature("mixed"), "mixed");
    }

    #[test]
    fn clean_nullable_types() {
        assert_eq!(clean_type_for_signature("?int"), "?int");
        assert_eq!(clean_type_for_signature("?string"), "?string");
    }

    #[test]
    fn clean_class_types() {
        assert_eq!(clean_type_for_signature("Foo"), "Foo");
        assert_eq!(
            clean_type_for_signature("\\App\\Models\\User"),
            "\\App\\Models\\User"
        );
    }

    #[test]
    fn clean_union_types() {
        assert_eq!(clean_type_for_signature("int|string"), "int|string");
        assert_eq!(clean_type_for_signature("Foo|null"), "Foo|null");
    }

    #[test]
    fn clean_empty_and_unparseable() {
        assert_eq!(clean_type_for_signature(""), "");
    }

    #[test]
    fn clean_generic_stripped() {
        assert_eq!(clean_type_for_signature("array<string>"), "array");
        assert_eq!(
            clean_type_for_signature("Collection<int, string>"),
            "Collection"
        );
    }

    #[test]
    fn clean_callable_types() {
        assert_eq!(
            clean_type_for_signature("callable(int): string"),
            "callable"
        );
        assert_eq!(clean_type_for_signature("Closure(int): void"), "Closure");
    }

    #[test]
    fn clean_array_slice_syntax() {
        assert_eq!(clean_type_for_signature("int[]"), "array");
    }

    // ── Build param list ────────────────────────────────────────────

    #[test]
    fn param_list_empty() {
        assert_eq!(build_param_list(&[]), "");
    }

    #[test]
    fn param_list_untyped() {
        let params = vec![("$x".to_string(), PhpType::untyped())];
        assert_eq!(build_param_list(&params), "$x");
    }

    #[test]
    fn param_list_typed() {
        let params = vec![
            ("$x".to_string(), PhpType::parse("int")),
            ("$y".to_string(), PhpType::parse("string")),
        ];
        assert_eq!(build_param_list(&params), "int $x, string $y");
    }

    // ── Return type ─────────────────────────────────────────────────

    #[test]
    fn return_type_void() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "void");
    }

    #[test]
    fn return_type_single() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![("$x".to_string(), PhpType::parse("int"))],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "int");
    }

    #[test]
    fn return_type_multiple() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![
                ("$x".to_string(), PhpType::parse("int")),
                ("$y".to_string(), PhpType::parse("string")),
            ],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "array");
    }

    #[test]
    fn return_type_trailing_return() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::TrailingReturn,
            trailing_return_type: PhpType::parse("string"),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "string");
    }

    #[test]
    fn return_type_void_guards() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::VoidGuards,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "bool");
    }

    #[test]
    fn return_type_uniform_guards() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::UniformGuards("false".to_string()),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "bool");
    }

    #[test]
    fn return_type_sentinel_null_with_type() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::SentinelNull,
            trailing_return_type: PhpType::parse("string"),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "?string");
    }

    #[test]
    fn return_type_null_guard_with_value() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![("$sound".to_string(), PhpType::parse("string"))],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::NullGuardWithValue(false),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "?string");
    }

    #[test]
    fn return_type_null_guard_with_value_already_nullable() {
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![("$val".to_string(), PhpType::parse("?int"))],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::NullGuardWithValue(false),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "?int");
    }

    #[test]
    fn return_type_void_guard_with_value() {
        // Void guards with a computed value — return type is still
        // nullable (the extracted function returns null on guard-fire).
        let info = ExtractionInfo {
            name: String::new(),
            params: vec![],
            returns: vec![("$sound".to_string(), PhpType::parse("string"))],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::NullGuardWithValue(true),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        assert_eq!(build_return_type(&info), "?string");
    }

    // ── Name generation ──────────────────────────────────────────────

    #[test]
    fn generates_unique_name() {
        let content = "<?php\nfunction extracted() {}\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Function,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: String::new(),
            sibling_method_names: Vec::new(),
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "",
            return_strategy: &ReturnStrategy::None,
            body_text: "echo 'hello';",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "extracted2");
    }

    #[test]
    fn generates_base_name_when_no_conflict() {
        let content = "<?php\nfunction foo() {}\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Function,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: String::new(),
            sibling_method_names: Vec::new(),
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "",
            return_strategy: &ReturnStrategy::None,
            body_text: "$x = 1;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "extracted");
    }

    #[test]
    fn name_guard_from_void_guards() {
        let content = "<?php\nclass Foo { function run() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "run".to_string(),
            sibling_method_names: vec!["run".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "run",
            return_strategy: &ReturnStrategy::VoidGuards,
            body_text: "if (!$x) return;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "runGuard");
    }

    #[test]
    fn name_guard_dedup_against_class() {
        let content = "<?php\nclass Foo { function run() {} function runGuard() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "run".to_string(),
            sibling_method_names: vec!["run".to_string(), "runGuard".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "run",
            return_strategy: &ReturnStrategy::VoidGuards,
            body_text: "if (!$x) return;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "runGuard2");
    }

    #[test]
    fn name_try_from_sentinel_null() {
        let content = "<?php\nclass Foo { function fetch() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "fetch".to_string(),
            sibling_method_names: vec!["fetch".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "fetch",
            return_strategy: &ReturnStrategy::SentinelNull,
            body_text: "return $result;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "tryFetch");
    }

    #[test]
    fn name_factory_from_trailing_return() {
        let content = "<?php\nclass Foo { function build() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "build".to_string(),
            sibling_method_names: vec!["build".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "build",
            return_strategy: &ReturnStrategy::TrailingReturn,
            body_text: "$u = new User('Alice');\nreturn $u;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        // Variable `$u` is too short (≤2 chars) → falls back to class name
        assert_eq!(name, "createUser");
    }

    #[test]
    fn name_ends_with_output() {
        let content = "<?php\nclass Foo { function process() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "process".to_string(),
            sibling_method_names: vec!["process".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "process",
            return_strategy: &ReturnStrategy::None,
            body_text: "$first = $users->first();\necho $first->name;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "renderProcess");
    }

    #[test]
    fn name_single_method_call() {
        let content = "<?php\nclass Foo { function run() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "run".to_string(),
            sibling_method_names: vec!["run".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "run",
            return_strategy: &ReturnStrategy::None,
            body_text: "$this->execute($fn);",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "execute");
    }

    #[test]
    fn name_single_function_call() {
        let content = "<?php\nfunction foo() {}\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Function,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "foo".to_string(),
            sibling_method_names: Vec::new(),
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "foo",
            return_strategy: &ReturnStrategy::None,
            body_text: "doSomething($x);",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "doSomething");
    }

    #[test]
    fn name_single_call_with_assignment_is_not_detected() {
        // `$result = $this->execute($fn)` is an assignment, not a
        // pure delegation — should fall through.
        let content = "<?php\nclass Foo { function run() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "run".to_string(),
            sibling_method_names: vec!["run".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "run",
            return_strategy: &ReturnStrategy::None,
            body_text: "$result = $this->execute($fn);",
            return_var_names: &["$result".to_string()],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        // Single return var → computeResult (not "execute")
        assert_eq!(name, "computeResult");
    }

    #[test]
    fn name_factory_prefers_assigned_over_nested() {
        // `new User('Alice')` is an argument to ->add(), not the thing
        // being constructed.  The variable `$users` is what gets
        // returned, so the name should be `createUsers`.
        let content = "<?php\nclass Foo { function getUsers() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "getUsers".to_string(),
            sibling_method_names: vec!["getUsers".to_string()],
        };
        let trailing_rt = PhpType::parse("Collection");
        let naming = NamingContext {
            enclosing_name: "getUsers",
            return_strategy: &ReturnStrategy::TrailingReturn,
            body_text: "$users = new Collection();\n$users->add(new User('Alice'));\nreturn $users;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "createUsers");
    }

    #[test]
    fn name_factory_prefers_return_new_over_assignment() {
        // `return new Product(…)` is a direct return — no variable to
        // take a name from, so the class name is used.
        let content = "<?php\nclass Foo { function build() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "build".to_string(),
            sibling_method_names: vec!["build".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "build",
            return_strategy: &ReturnStrategy::TrailingReturn,
            body_text: "$tmp = new Builder();\nreturn new Product($tmp);",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "createProduct");
    }

    #[test]
    fn name_factory_direct_return_new_uses_class_name() {
        // `return new User(…)` with no variable — class name is used.
        let content = "<?php\nclass Foo { function make() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "make".to_string(),
            sibling_method_names: vec!["make".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "make",
            return_strategy: &ReturnStrategy::TrailingReturn,
            body_text: "return new User('Alice');",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "createUser");
    }

    #[test]
    fn name_render_from_pure_output() {
        let content = "<?php\nclass Foo { function show() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "show".to_string(),
            sibling_method_names: vec!["show".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "show",
            return_strategy: &ReturnStrategy::None,
            body_text: "echo $name;\necho $age;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "renderShow");
    }

    #[test]
    fn name_compute_from_single_return_var() {
        let content = "<?php\nfunction calc() {}\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Function,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "calc".to_string(),
            sibling_method_names: Vec::new(),
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "calc",
            return_strategy: &ReturnStrategy::None,
            body_text: "$total = $a + $b;",
            return_var_names: &["$total".to_string()],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "computeTotal");
    }

    #[test]
    fn name_method_dedup_scoped_to_class() {
        // "extracted" exists as a function elsewhere in the file, but
        // the class has no method called "extracted" → no dedup needed.
        let content = "<?php\nfunction extracted() {}\nclass Foo { function run() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 50,
            is_static: false,
            enclosing_name: String::new(),
            sibling_method_names: vec!["run".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "",
            return_strategy: &ReturnStrategy::None,
            body_text: "$x = 1;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "extracted");
    }

    #[test]
    fn name_trailing_return_with_return_type() {
        let content = "<?php\nclass Foo { function getUsers() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "getUsers".to_string(),
            sibling_method_names: vec!["getUsers".to_string()],
        };
        let trailing_rt = PhpType::parse("Collection");
        let naming = NamingContext {
            enclosing_name: "getUsers",
            return_strategy: &ReturnStrategy::TrailingReturn,
            body_text: "$users = query();\nreturn $users;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "getCollection");
    }

    #[test]
    fn name_uniform_guards() {
        let content = "<?php\nclass Foo { function validate() {} }\n";
        let ctx = EnclosingContext {
            target: ExtractionTarget::Method,
            insert_offset: content.len(),
            body_start: 20,
            is_static: false,
            enclosing_name: "validate".to_string(),
            sibling_method_names: vec!["validate".to_string()],
        };
        let trailing_rt = PhpType::untyped();
        let naming = NamingContext {
            enclosing_name: "validate",
            return_strategy: &ReturnStrategy::UniformGuards("false".to_string()),
            body_text: "if (!$x) return false;",
            return_var_names: &[],
            trailing_return_type: &trailing_rt,
        };
        let name = generate_function_name(content, &ctx, &naming);
        assert_eq!(name, "validateGuard");
    }

    // ── Call site generation ────────────────────────────────────────

    #[test]
    fn call_site_no_returns() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::parse("int"))],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "    ");
        assert_eq!(result, "    extracted($x);\n");
    }

    #[test]
    fn call_site_single_return() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::parse("int"))],
            returns: vec![("$result".to_string(), PhpType::parse("int"))],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: "    ".to_string(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "    ");
        assert_eq!(result, "    $result = extracted($x);\n");
    }

    #[test]
    fn call_site_multiple_returns() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![],
            returns: vec![
                ("$a".to_string(), PhpType::untyped()),
                ("$b".to_string(), PhpType::untyped()),
            ],
            body: String::new(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: String::new(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "    ");
        assert_eq!(result, "    [$a, $b] = extracted();\n");
    }

    #[test]
    fn call_site_method() {
        let info = ExtractionInfo {
            name: "runGuard".to_string(),
            params: vec![("$x".to_string(), PhpType::parse("int"))],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "        ");
        assert_eq!(result, "        $this->runGuard($x);\n");
    }

    #[test]
    fn call_site_static_method() {
        let info = ExtractionInfo {
            name: "computeTotal".to_string(),
            params: vec![],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Method,
            is_static: true,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "        ");
        assert_eq!(result, "        self::computeTotal();\n");
    }

    #[test]
    fn call_site_trailing_return() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::parse("int"))],
            returns: vec![],
            body: "return $x * 2;".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::TrailingReturn,
            trailing_return_type: PhpType::parse("int"),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "        ");
        assert_eq!(result, "        return $this->extracted($x);\n");
    }

    #[test]
    fn call_site_void_guards() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::untyped())],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::VoidGuards,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "        ");
        assert_eq!(result, "        if (!$this->extracted($x)) return;\n");
    }

    #[test]
    fn call_site_uniform_false_guards() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::untyped())],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::UniformGuards("false".to_string()),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "        ");
        assert_eq!(result, "        if (!$this->extracted($x)) return false;\n");
    }

    #[test]
    fn call_site_sentinel_null() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::untyped())],
            returns: vec![],
            body: String::new(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::SentinelNull,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "        ");
        assert_eq!(
            result,
            "        $result = $this->extracted($x);\n        if ($result !== null) return $result;\n"
        );
    }

    #[test]
    fn call_site_null_guard_with_value() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$obj".to_string(), PhpType::untyped())],
            returns: vec![("$sound".to_string(), PhpType::parse("string"))],
            body: String::new(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::NullGuardWithValue(false),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "        ");
        assert_eq!(
            result,
            "        $sound = $this->extracted($obj);\n        if ($sound === null) return null;\n"
        );
    }

    #[test]
    fn call_site_void_guard_with_value() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$obj".to_string(), PhpType::untyped())],
            returns: vec![("$sound".to_string(), PhpType::parse("string"))],
            body: String::new(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::NullGuardWithValue(true),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_call_site(&info, "        ");
        assert_eq!(
            result,
            "        $sound = $this->extracted($obj);\n        if ($sound === null) return;\n"
        );
    }

    // ── Definition generation ───────────────────────────────────────

    #[test]
    fn definition_method_no_params_void() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![],
            returns: vec![],
            body: "        echo 'hello';\n".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains("private function extracted(): void"),
            "got: {result}"
        );
        assert!(result.contains("echo 'hello';"), "got: {result}");
    }

    #[test]
    fn definition_function_with_params_and_return() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::parse("int"))],
            returns: vec![("$result".to_string(), PhpType::parse("string"))],
            body: "$result = strval($x);".to_string(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: "    ".to_string(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains("function extracted(int $x): string"),
            "got: {result}"
        );
        assert!(result.contains("return $result;"), "got: {result}");
    }

    #[test]
    fn definition_static_method() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::parse("int"))],
            returns: vec![],
            body: "        echo $x;\n".to_string(),
            target: ExtractionTarget::Method,
            is_static: true,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains("private static function extracted(int $x): void"),
            "got: {result}"
        );
    }

    #[test]
    fn definition_with_trailing_return() {
        let info = ExtractionInfo {
            name: "extracted".to_string(),
            params: vec![("$x".to_string(), PhpType::parse("int"))],
            returns: vec![],
            body: "        return $x * 2;\n".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::TrailingReturn,
            trailing_return_type: PhpType::parse("int"),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains("private function extracted(int $x): int"),
            "should carry enclosing return type: {result}"
        );
        // Body already contains the return — no extra return appended.
        assert!(
            result.contains("return $x * 2;"),
            "body should keep the return statement: {result}"
        );
        // Should not have a duplicate return.
        assert_eq!(
            result.matches("return").count(),
            1,
            "should have exactly one return: {result}"
        );
    }

    #[test]
    fn definition_void_guards_appends_return_true() {
        let info = ExtractionInfo {
            name: "validate".to_string(),
            params: vec![("$x".to_string(), PhpType::untyped())],
            returns: vec![],
            body: "if (!$x) return;".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::VoidGuards,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains(": bool"),
            "should have bool return type: {result}"
        );
        assert!(
            result.contains("return true;"),
            "should append return true as fall-through: {result}"
        );
    }

    #[test]
    fn definition_uniform_false_guards_appends_return_true() {
        let info = ExtractionInfo {
            name: "validate".to_string(),
            params: vec![("$x".to_string(), PhpType::untyped())],
            returns: vec![],
            body: "if (!$x) return false;".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::UniformGuards("false".to_string()),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains(": bool"),
            "should have bool return type: {result}"
        );
        assert!(
            result.contains("return true;"),
            "should append return true (inverse of false) as sentinel: {result}"
        );
    }

    #[test]
    fn definition_uniform_true_guards_appends_return_false() {
        let info = ExtractionInfo {
            name: "validate".to_string(),
            params: vec![("$x".to_string(), PhpType::untyped())],
            returns: vec![],
            body: "if (!$x) return true;".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::UniformGuards("true".to_string()),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains("return false;"),
            "should append return false (inverse of true) as sentinel: {result}"
        );
    }

    #[test]
    fn definition_sentinel_null_appends_return_null() {
        let info = ExtractionInfo {
            name: "classify".to_string(),
            params: vec![("$x".to_string(), PhpType::untyped())],
            returns: vec![],
            body: "if ($x < 0) return 'negative';".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::SentinelNull,
            trailing_return_type: PhpType::parse("string"),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains(": ?string"),
            "should have nullable return type: {result}"
        );
        assert!(
            result.contains("return null;"),
            "should append return null as sentinel: {result}"
        );
    }

    #[test]
    fn definition_null_guard_with_value_appends_return_variable() {
        let info = ExtractionInfo {
            name: "getSound".to_string(),
            params: vec![],
            returns: vec![("$sound".to_string(), PhpType::parse("string"))],
            body: "        if ($this->muted) return null;\n        $sound = $this->makeSound();\n"
                .to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::NullGuardWithValue(false),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains(": ?string"),
            "should have nullable return type: {result}"
        );
        assert!(
            result.contains("return $sound;"),
            "should append return $sound as fall-through: {result}"
        );
        assert!(
            result.contains("return null;"),
            "should keep the guard's return null: {result}"
        );
    }

    #[test]
    fn definition_void_guard_with_value_rewrites_returns() {
        // Void guards + return value: bare `return;` → `return null;`
        let info = ExtractionInfo {
            name: "getSound".to_string(),
            params: vec![],
            returns: vec![("$sound".to_string(), PhpType::parse("string"))],
            body: "        if ($this->muted) return;\n        $sound = $this->makeSound();\n"
                .to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::NullGuardWithValue(true),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains(": ?string"),
            "should have nullable return type: {result}"
        );
        assert!(
            result.contains("return $sound;"),
            "should append return $sound as fall-through: {result}"
        );
        // Bare `return;` should be rewritten to `return null;`.
        assert!(
            result.contains("return null;"),
            "void guard should be rewritten to return null: {result}"
        );
        // Should NOT contain bare `return;`.
        assert_eq!(
            result.matches("return;").count(),
            0,
            "should not contain bare return: {result}"
        );
    }

    // ── Void return rewriting ───────────────────────────────────────

    #[test]
    fn rewrite_void_returns_to_null_basic() {
        let body = "if (!$x) return;\nif (!$y) return;";
        let result = rewrite_void_returns_to_null(body);
        assert_eq!(result, "if (!$x) return null;\nif (!$y) return null;");
    }

    #[test]
    fn rewrite_void_returns_to_null_preserves_valued_returns() {
        let body = "if (!$x) return;\nreturn $result;";
        let result = rewrite_void_returns_to_null(body);
        assert_eq!(result, "if (!$x) return null;\nreturn $result;");
    }

    #[test]
    fn rewrite_void_returns_to_null_ignores_identifiers() {
        let body = "$returnValue = 1;\nif (!$x) return;";
        let result = rewrite_void_returns_to_null(body);
        assert_eq!(result, "$returnValue = 1;\nif (!$x) return null;");
    }

    // ── Guard return rewriting ──────────────────────────────────────

    #[test]
    fn rewrite_void_guards_to_false() {
        let body = "if (!$x) return;\nif (!$y) return;";
        let result = rewrite_guard_returns(body, None);
        assert_eq!(result, "if (!$x) return false;\nif (!$y) return false;");
    }

    #[test]
    fn rewrite_void_guards_preserves_non_bare_returns() {
        let body = "if (!$x) return;\nreturn $result;";
        let result = rewrite_guard_returns(body, None);
        assert_eq!(
            result, "if (!$x) return false;\nreturn $result;",
            "should only rewrite bare returns"
        );
    }

    #[test]
    fn rewrite_void_guards_ignores_return_in_identifiers() {
        let body = "$returnValue = 1;\nif (!$x) return;";
        let result = rewrite_guard_returns(body, None);
        assert_eq!(result, "$returnValue = 1;\nif (!$x) return false;");
    }

    #[test]
    fn rewrite_uniform_null_to_false() {
        let body = "if ($id <= 0) return null;\nif (!$org) return null;";
        let result = rewrite_guard_returns(body, Some("null"));
        assert_eq!(
            result,
            "if ($id <= 0) return false;\nif (!$org) return false;"
        );
    }

    #[test]
    fn rewrite_uniform_value_preserves_other_returns() {
        let body = "if ($id <= 0) return null;\nreturn $result;";
        let result = rewrite_guard_returns(body, Some("null"));
        assert_eq!(
            result, "if ($id <= 0) return false;\nreturn $result;",
            "should only rewrite matching return values"
        );
    }

    #[test]
    fn rewrite_uniform_numeric_to_false() {
        let body = "if ($x < 0) return 0;\nif ($x > 100) return 0;";
        let result = rewrite_guard_returns(body, Some("0"));
        assert_eq!(
            result,
            "if ($x < 0) return false;\nif ($x > 100) return false;"
        );
    }

    #[test]
    fn void_guards_definition_rewrites_body() {
        // End-to-end: the definition should contain `return false;`
        // for the guards and `return true;` for the fall-through.
        let info = ExtractionInfo {
            name: "validate".to_string(),
            params: vec![("$x".to_string(), PhpType::untyped())],
            returns: vec![],
            body: "if (!$x) return;\nif (!$y) return;".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::VoidGuards,
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains("return false;"),
            "guards should be rewritten to return false: {result}"
        );
        assert!(
            result.contains("return true;"),
            "fall-through should be return true: {result}"
        );
        // Should NOT contain bare `return;` (the original void return).
        let bare_return_count = result.matches("return;").count();
        assert_eq!(
            bare_return_count, 0,
            "should not contain bare return: {result}"
        );
    }

    #[test]
    fn uniform_null_definition_rewrites_body() {
        // `return null;` guards should become `return false;` in the
        // extracted function since the return type is bool.
        let info = ExtractionInfo {
            name: "validate".to_string(),
            params: vec![("$id".to_string(), PhpType::untyped())],
            returns: vec![],
            body: "if ($id <= 0) return null;\nif (!$this->exists($id)) return null;".to_string(),
            target: ExtractionTarget::Method,
            is_static: false,
            member_indent: "    ".to_string(),
            body_indent: "        ".to_string(),
            return_strategy: ReturnStrategy::UniformGuards("null".to_string()),
            trailing_return_type: PhpType::untyped(),
            docblock: String::new(),
        };
        let result = build_extracted_definition(&info);
        assert!(
            result.contains("return false;"),
            "null guards should be rewritten to return false: {result}"
        );
        assert!(
            result.contains("return true;"),
            "fall-through should be return true: {result}"
        );
        // Should NOT contain `return null;`.
        let null_return_count = result.matches("return null;").count();
        assert_eq!(
            null_return_count, 0,
            "should not contain return null: {result}"
        );
    }

    // ── Integration: code action on Backend ─────────────────────────

    #[test]
    fn extract_function_action_offered_for_complete_statements() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
function foo() {
    $x = 1;
    $y = $x + 2;
    echo $y;
}
";
        // Select `$x = 1;\n    $y = $x + 2;`
        let start_line = 2; // `    $x = 1;`
        let end_line = 3; // `    $y = $x + 2;`

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(start_line, 4),
                end: Position::new(end_line, 16),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let extract_action = actions
            .iter()
            .find(|a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.starts_with("Extract function")));
        assert!(
            extract_action.is_some(),
            "should offer extract function action, got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn extract_function_not_offered_for_empty_selection() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
function foo() {
    $x = 1;
}
";
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 4),
                end: Position::new(2, 4), // empty selection
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let extract_actions: Vec<_> = actions
            .iter()
            .filter(|a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.starts_with("Extract function") || ca.title.starts_with("Extract method")))
            .collect();
        assert!(
            extract_actions.is_empty(),
            "should not offer extract for empty selection"
        );
    }

    #[test]
    fn extract_function_not_offered_for_partial_statement() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
function foo() {
    $x = 1 + 2;
}
";
        // Select just `1 + 2` — not a complete statement.
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 9),
                end: Position::new(2, 14),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let extract_actions: Vec<_> = actions
            .iter()
            .filter(|a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.starts_with("Extract function") || ca.title.starts_with("Extract method")))
            .collect();
        assert!(
            extract_actions.is_empty(),
            "should not offer extract for partial statement"
        );
    }

    #[test]
    fn extract_method_offered_when_using_this() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
class Foo {
    private int $value = 0;

    public function bar() {
        $x = $this->value;
        echo $x;
    }
}
";
        // Select `$x = $this->value;\n        echo $x;`
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(5, 8),
                end: Position::new(6, 16),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let extract_method = actions
            .iter()
            .find(|a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.starts_with("Extract method")));
        assert!(
            extract_method.is_some(),
            "should offer extract method when $this is used, got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn extract_function_offered_for_trailing_return() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
function foo() {
    $x = 1;
    return $x;
}
";
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 4),
                end: Position::new(3, 14),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let extract_action = actions.iter().find(|a| {
            matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.starts_with("Extract function") || ca.title.starts_with("Extract method"))
        });
        assert!(
            extract_action.is_some(),
            "should offer extract when return is the last selected statement"
        );
    }

    #[test]
    fn extract_function_offered_for_guard_clause_return() {
        // Non-trailing returns that form guard clauses should now be
        // offered with the appropriate guard strategy.
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
function foo($x) {
    if ($x) {
        return 1;
    }
    echo 'done';
}
";
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 4),
                end: Position::new(5, 17),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let extract_action = actions.iter().find(|a| {
            matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.starts_with("Extract function") || ca.title.starts_with("Extract method"))
        });
        assert!(
            extract_action.is_some(),
            "should offer extract for guard clause return pattern, got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    // ── Indent detection ────────────────────────────────────────────

    #[test]
    fn detect_indent_unit_spaces() {
        let content = "<?php\n    function foo() {\n        $x = 1;\n    }\n";
        assert_eq!(detect_indent_unit(content), "    ");
    }

    #[test]
    fn detect_indent_unit_tabs() {
        let content = "<?php\n\tfunction foo() {\n\t\t$x = 1;\n\t}\n";
        assert_eq!(detect_indent_unit(content), "\t");
    }

    #[test]
    fn indent_at_line() {
        let content = "<?php\n    $x = 1;\n";
        let offset = content.find("$x").unwrap();
        assert_eq!(indent_at(content, offset), "    ");
    }

    #[test]
    fn detect_line_indent_method() {
        let content =
            "<?php\nclass Foo {\n    public function bar() {\n        $x = 1;\n    }\n}\n";
        // body_start is the `{` after `bar()`
        let offset = content.find("{\n        $x").unwrap();
        assert_eq!(detect_line_indent(content, offset), "    ");
    }

    // ── Extraction context ──────────────────────────────────────────

    #[test]
    fn detects_function_context() {
        let content = "<?php\nfunction foo() {\n    $x = 1;\n}\n";
        let offset = content.find("$x").unwrap() as u32;
        let ctx = find_enclosing_context(content, offset, false);
        assert!(ctx.is_some());
        let ctx = ctx.unwrap();
        assert_eq!(ctx.target, ExtractionTarget::Function);
    }

    #[test]
    fn detects_method_context() {
        let content =
            "<?php\nclass Foo {\n    public function bar() {\n        $x = 1;\n    }\n}\n";
        let offset = content.find("$x").unwrap() as u32;
        let ctx = find_enclosing_context(content, offset, false);
        assert!(ctx.is_some());
        let ctx = ctx.unwrap();
        assert_eq!(ctx.target, ExtractionTarget::Method);
    }

    #[test]
    fn detects_method_context_with_this() {
        let content =
            "<?php\nclass Foo {\n    public function bar() {\n        $this->baz();\n    }\n}\n";
        let offset = content.find("$this").unwrap() as u32;
        let ctx = find_enclosing_context(content, offset, true);
        assert!(ctx.is_some());
        let ctx = ctx.unwrap();
        assert_eq!(ctx.target, ExtractionTarget::Method);
    }

    // ── PHPDoc generation on extracted method ───────────────────────

    fn no_classes(_name: &str) -> Option<Arc<ClassInfo>> {
        None
    }

    #[test]
    fn docblock_not_generated_for_scalar_types() {
        let params = vec![
            (
                "$x".to_string(),
                PhpType::parse("int"),
                PhpType::parse("int"),
            ),
            (
                "$y".to_string(),
                PhpType::parse("string"),
                PhpType::parse("string"),
            ),
        ];
        let result = build_docblock_for_extraction(
            &params,
            &PhpType::parse("void"),
            &PhpType::parse("void"),
            "    ",
            &no_classes,
        );
        assert!(
            result.is_empty(),
            "scalar types should not trigger docblock, got: {result}"
        );
    }

    #[test]
    fn docblock_generated_for_array_param() {
        let params = vec![(
            "$items".to_string(),
            PhpType::parse("array"),
            PhpType::parse("array"),
        )];
        let result = build_docblock_for_extraction(
            &params,
            &PhpType::parse("void"),
            &PhpType::parse("void"),
            "    ",
            &no_classes,
        );
        assert!(
            result.contains("@param"),
            "array param should trigger @param enrichment, got: {result}"
        );
        assert!(result.contains("$items"));
        assert!(result.starts_with("    /**"));
        assert!(result.contains("     */"));
    }

    #[test]
    fn docblock_generated_for_callable_param() {
        let params = vec![(
            "$fn".to_string(),
            PhpType::parse("Closure"),
            PhpType::parse("Closure"),
        )];
        let result = build_docblock_for_extraction(
            &params,
            &PhpType::parse("void"),
            &PhpType::parse("void"),
            "    ",
            &no_classes,
        );
        assert!(
            result.contains("@param"),
            "Closure param should trigger @param enrichment, got: {result}"
        );
        assert!(result.contains("$fn"));
    }

    #[test]
    fn docblock_not_generated_for_empty_types() {
        let params = vec![("$x".to_string(), PhpType::untyped(), PhpType::untyped())];
        let result = build_docblock_for_extraction(
            &params,
            &PhpType::untyped(),
            &PhpType::untyped(),
            "",
            &no_classes,
        );
        assert!(
            result.is_empty(),
            "empty types should not trigger docblock, got: {result}"
        );
    }

    #[test]
    fn docblock_aligns_param_names() {
        let params = vec![
            (
                "$items".to_string(),
                PhpType::parse("array"),
                PhpType::parse("array<string, User>"),
            ),
            (
                "$x".to_string(),
                PhpType::parse("Closure"),
                PhpType::parse("Closure"),
            ),
        ];
        let result = build_docblock_for_extraction(
            &params,
            &PhpType::parse("void"),
            &PhpType::parse("void"),
            "",
            &no_classes,
        );
        // Both @param tags should be present.
        let param_lines: Vec<&str> = result.lines().filter(|l| l.contains("@param")).collect();
        assert_eq!(
            param_lines.len(),
            2,
            "expected 2 @param lines, got: {result}"
        );
        // The $-names should be aligned (both start at the same column).
        let dollar_positions: Vec<usize> =
            param_lines.iter().map(|l| l.find('$').unwrap()).collect();
        assert_eq!(
            dollar_positions[0], dollar_positions[1],
            "param names should be aligned, got: {result}"
        );
    }

    #[test]
    fn docblock_return_type_hint_for_docblock_trailing() {
        let result = build_return_type_hint_for_docblock(
            &ReturnStrategy::TrailingReturn,
            &PhpType::parse("string"),
            &[],
        );
        assert_eq!(result, PhpType::parse("string"));
    }

    #[test]
    fn docblock_return_type_hint_for_docblock_void_guards() {
        let result = build_return_type_hint_for_docblock(
            &ReturnStrategy::VoidGuards,
            &PhpType::untyped(),
            &[],
        );
        assert_eq!(result, PhpType::parse("bool"));
    }

    #[test]
    fn docblock_return_type_hint_for_docblock_none_void() {
        let result =
            build_return_type_hint_for_docblock(&ReturnStrategy::None, &PhpType::untyped(), &[]);
        assert_eq!(result, PhpType::parse("void"));
    }

    #[test]
    fn docblock_return_type_hint_for_docblock_single_return() {
        let returns = vec![(
            "$x".to_string(),
            PhpType::parse("array"),
            PhpType::parse("array"),
        )];
        let result = build_return_type_hint_for_docblock(
            &ReturnStrategy::None,
            &PhpType::untyped(),
            &returns,
        );
        assert_eq!(result, PhpType::parse("array"));
    }

    #[test]
    fn definition_includes_docblock_for_array_param() {
        let info = ExtractionInfo {
            name: "process".to_string(),
            params: vec![("$items".to_string(), PhpType::parse("array"))],
            returns: vec![],
            body: "foreach ($items as $item) {}".to_string(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: "    ".to_string(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: build_docblock_for_extraction(
                &[(
                    "$items".to_string(),
                    PhpType::parse("array"),
                    PhpType::parse("array"),
                )],
                &PhpType::parse("void"),
                &PhpType::parse("void"),
                "",
                &no_classes,
            ),
        };
        let def = build_extracted_definition(&info);
        assert!(
            def.contains("/**"),
            "definition should include docblock for array param, got:\n{def}"
        );
        assert!(
            def.contains("@param"),
            "definition should include @param tag, got:\n{def}"
        );
        // Docblock should appear before the function keyword.
        let doc_pos = def.find("/**").unwrap();
        let fn_pos = def.find("function").unwrap();
        assert!(doc_pos < fn_pos, "docblock should precede function keyword");
    }

    #[test]
    fn definition_no_docblock_for_scalar_params() {
        let info = ExtractionInfo {
            name: "add".to_string(),
            params: vec![
                ("$a".to_string(), PhpType::parse("int")),
                ("$b".to_string(), PhpType::parse("int")),
            ],
            returns: vec![("$sum".to_string(), PhpType::parse("int"))],
            body: "$sum = $a + $b;".to_string(),
            target: ExtractionTarget::Function,
            is_static: false,
            member_indent: String::new(),
            body_indent: "    ".to_string(),
            return_strategy: ReturnStrategy::None,
            trailing_return_type: PhpType::untyped(),
            docblock: build_docblock_for_extraction(
                &[
                    (
                        "$a".to_string(),
                        PhpType::parse("int"),
                        PhpType::parse("int"),
                    ),
                    (
                        "$b".to_string(),
                        PhpType::parse("int"),
                        PhpType::parse("int"),
                    ),
                ],
                &PhpType::parse("int"),
                &PhpType::parse("int"),
                "",
                &no_classes,
            ),
        };
        let def = build_extracted_definition(&info);
        assert!(
            !def.contains("/**"),
            "definition should NOT include docblock for scalar types, got:\n{def}"
        );
    }

    // ── Disabled code action with rejection reason ──────────────────

    #[test]
    fn unsafe_returns_resolve_produces_no_edit() {
        // Phase 1 no longer emits disabled actions (validation is
        // deferred to resolve).  Instead it offers a normal action
        // and resolve returns None when the return strategy is unsafe.
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
function foo() {
    if ($a) return 1;
    if ($b) return null;
    echo 'done';
}
";
        backend
            .open_files
            .write()
            .insert(uri.to_string(), std::sync::Arc::new(content.to_string()));

        // Select the three statements (mixed return values including
        // null → Unsafe strategy).
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 4),
                end: Position::new(4, 17),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let extract = actions.iter().find_map(|a| match a {
            CodeActionOrCommand::CodeAction(ca)
                if ca.kind == Some(CodeActionKind::REFACTOR_EXTRACT)
                    && ca.title.contains("Extract") =>
            {
                Some(ca)
            }
            _ => None,
        });
        assert!(
            extract.is_some(),
            "Phase 1 should still offer the action (validation deferred to resolve)"
        );

        let action = extract.unwrap();
        assert!(action.edit.is_none(), "Phase 1 should not have an edit");
        assert!(
            action.data.is_some(),
            "Phase 1 should have data for resolve"
        );

        // Phase 2: resolve should produce no edit because the return
        // strategy is unsafe.
        let (resolved, _) = backend.resolve_code_action(action.clone());
        assert!(
            resolved.edit.is_none(),
            "resolve should produce no edit for unsafe returns"
        );
    }

    #[test]
    fn no_disabled_action_for_empty_selection() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
function foo() {
    $x = 1;
}
";
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 4),
                end: Position::new(2, 4), // empty selection
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let disabled_extract = actions.iter().find(|a| {
            matches!(a, CodeActionOrCommand::CodeAction(ca)
                if ca.disabled.is_some()
                    && ca.kind == Some(CodeActionKind::REFACTOR_EXTRACT)
                    && ca.title.contains("Extract"))
        });
        assert!(
            disabled_extract.is_none(),
            "should NOT emit a disabled extract action for empty selection"
        );
    }

    #[test]
    fn no_disabled_action_for_partial_statement() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "\
<?php
function foo() {
    $x = some_function($a, $b);
}
";
        // Select partial statement (just the function call, not the assignment).
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 9),
                end: Position::new(2, 30),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: WorkDoneProgressParams {
                work_done_token: None,
            },
            partial_result_params: PartialResultParams {
                partial_result_token: None,
            },
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let disabled_extract = actions.iter().find(|a| {
            matches!(a, CodeActionOrCommand::CodeAction(ca)
                if ca.disabled.is_some()
                    && ca.kind == Some(CodeActionKind::REFACTOR_EXTRACT)
                    && ca.title.contains("Extract"))
        });
        assert!(
            disabled_extract.is_none(),
            "should NOT emit a disabled extract action for partial statement"
        );
    }
}