ty_site_packages 0.0.10

This is an internal component crate of Ruff
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
//! Utilities for finding the `site-packages` directory,
//! into which third-party packages are installed.
//!
//! The routines exposed by this module have different behaviour depending
//! on the platform of the *host machine*, which may be
//! different from the *target platform for type checking*. (A user
//! might be running ty on a Windows machine, but might
//! reasonably ask us to type-check code assuming that the code runs
//! on Linux.)

mod version;

use std::hash::{Hash, Hasher};
use std::io;
use std::num::NonZeroUsize;
use std::ops::Deref;
use std::str::FromStr;
use std::{fmt, sync::Arc};

use annotate_snippets::{AnnotationKind, Level, Renderer, Snippet};
use camino::Utf8Component;
use indexmap::IndexSet;
use ruff_db::system::{System, SystemPath, SystemPathBuf};
use ruff_python_ast::PythonVersion;
use ruff_python_trivia::Cursor;
use ruff_source_file::{LineIndex, OneIndexed, SourceCode};
use ruff_text_size::{TextLen, TextRange};
use strum::IntoEnumIterator;
use ty_static::EnvVars;
pub use version::{PythonVersionFileSource, PythonVersionSource, PythonVersionWithSource};

type SitePackagesDiscoveryResult<T> = Result<T, SitePackagesDiscoveryError>;
type StdlibDiscoveryResult<T> = Result<T, StdlibDiscoveryError>;

/// An ordered, deduplicated set of `site-packages` search paths.
///
/// Most environments will only have one `site-packages` directory.
/// Some virtual environments created with `--system-site-packages`
/// will also have the system installation's `site-packages` packages
/// available, however. Ephemeral environments created with `uv` in
/// `uv run --with` invocations, meanwhile, "extend" a parent environment
/// (which could be another virtual environment or a system installation,
/// and which could itself have multiple `site-packages` directories).
///
/// We use an `IndexSet` here to guard against the (very remote)
/// possibility that an environment might somehow be marked as being
/// both a `--system-site-packages` virtual environment *and* an
/// ephemeral environment that extends the system environment. If this
/// were the case, the system environment's `site-packages` directory
/// *might* be added to the `SitePackagesPaths` twice, but we wouldn't
/// want duplicates to appear in this set.
#[derive(Debug, PartialEq, Eq, Default)]
pub struct SitePackagesPaths(IndexSet<SitePackagesPath>);

#[derive(Debug, Clone)]
struct SitePackagesPath {
    /// The resolved `site-packages` or `dist-packages` directory.
    path: SystemPathBuf,
    /// A file to use when anchoring diagnostics for settings inferred from this path.
    settings_diagnostic_path: Option<SystemPathBuf>,
}

impl SitePackagesPath {
    fn new(path: SystemPathBuf, settings_diagnostic_path: Option<SystemPathBuf>) -> Self {
        Self {
            path,
            settings_diagnostic_path,
        }
    }

    fn into_path(self) -> SystemPathBuf {
        self.path
    }
}

impl PartialEq for SitePackagesPath {
    fn eq(&self, other: &Self) -> bool {
        // The diagnostic anchor is metadata for this path, not part of the path's set identity.
        self.path == other.path
    }
}

impl Eq for SitePackagesPath {}

impl Hash for SitePackagesPath {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.path.hash(state);
    }
}

impl SitePackagesPaths {
    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    fn insert_with_settings_diagnostic_path(
        &mut self,
        path: SystemPathBuf,
        settings_diagnostic_path: Option<SystemPathBuf>,
    ) {
        self.0
            .insert(SitePackagesPath::new(path, settings_diagnostic_path));
    }

    fn extend(&mut self, other: Self) {
        self.0.extend(other.0);
    }

    /// Concatenate two instances of [`SitePackagesPaths`].
    #[must_use]
    pub fn concatenate(mut self, other: Self) -> Self {
        for path in other.0 {
            self.0.insert(path);
        }
        self
    }

    /// Tries to detect the version from the layout of the `site-packages` directory.
    pub fn python_version_from_layout(&self) -> Option<PythonVersionWithSource> {
        if cfg!(windows) {
            // The path to `site-packages` on Unix is
            // `<sys.prefix>/lib/pythonX.Y/site-packages`,
            // but on Windows it's `<sys.prefix>/Lib/site-packages`.
            return None;
        }

        let primary_site_packages = self.0.first()?;

        let mut site_packages_ancestor_components = primary_site_packages
            .path
            .components()
            .rev()
            .skip(1)
            .map(|c| {
                // This should have all been validated in `site_packages.rs`
                // when we resolved the search paths for the project.
                debug_assert!(
                    matches!(c, Utf8Component::Normal(_)),
                    "Unexpected component in site-packages path `{c:?}` \
                    (expected `site-packages` to be an absolute path \
                    with symlinks resolved, located at \
                    `<sys.prefix>/lib/pythonX.Y/site-packages`)"
                );

                c.as_str()
            });

        let parent_component = site_packages_ancestor_components.next()?;

        if site_packages_ancestor_components.next()? != UnixLibDir::Lib {
            return None;
        }

        let version = parent_component
            .strip_prefix("python")
            .or_else(|| parent_component.strip_prefix("pypy"))?
            .trim_end_matches('t');

        let version = PythonVersion::from_str(version).ok()?;
        let source = PythonVersionSource::InstallationDirectoryLayout {
            site_packages_parent_dir: Box::from(parent_component),
            source: primary_site_packages
                .settings_diagnostic_path
                .clone()
                .map(|path| PythonVersionFileSource::new(Arc::new(path), None)),
        };

        Some(PythonVersionWithSource { version, source })
    }

    pub fn into_vec(self) -> Vec<SystemPathBuf> {
        self.into_iter().collect()
    }
}

impl fmt::Display for SitePackagesPaths {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.0.iter().map(|path| &path.path))
            .finish()
    }
}

/// Return a [`SystemPathBuf`] to use for anchoring settings diagnostics surfaced while analyzing
/// the interpreter at the given `sys.prefix`.
fn settings_diagnostic_path_from_sys_prefix(
    sys_prefix: &SystemPath,
    system: &dyn System,
) -> Option<SystemPathBuf> {
    let pyvenv_cfg = sys_prefix.join("pyvenv.cfg");
    if system.is_file(&pyvenv_cfg) {
        return Some(pyvenv_cfg);
    }

    let bin_dir = if cfg!(windows) {
        sys_prefix.to_path_buf()
    } else {
        sys_prefix.join("bin")
    };

    for candidate in [
        bin_dir.join("python3"),
        bin_dir.join("python"),
        bin_dir.join("pypy3"),
        bin_dir.join("pypy"),
    ] {
        if system.is_file(&candidate) {
            return Some(candidate);
        }
    }

    let entries = system.read_directory(&bin_dir).ok()?;
    for entry in entries.flatten() {
        if entry.file_type().is_directory() {
            continue;
        }

        let path = entry.into_path();
        if let Some(file_name) = path.file_name()
            && is_versioned_interpreter_path(file_name)
        {
            return Some(path);
        }
    }

    None
}

/// Returns `true` if the file name appears to be that of a versioned interpreter
/// (e.g., `python3.15`).
fn is_versioned_interpreter_path(file_name: &str) -> bool {
    matches!(
        PythonInterpreterLayout::from_file_name(file_name),
        Some(PythonInterpreterLayout {
            version: Some(_),
            ..
        })
    )
}

impl<const N: usize> From<[SystemPathBuf; N]> for SitePackagesPaths {
    fn from(paths: [SystemPathBuf; N]) -> Self {
        Self(
            paths
                .into_iter()
                .map(|path| SitePackagesPath::new(path, None))
                .collect(),
        )
    }
}

impl IntoIterator for SitePackagesPaths {
    type Item = SystemPathBuf;
    type IntoIter = std::vec::IntoIter<SystemPathBuf>;

    fn into_iter(self) -> Self::IntoIter {
        self.0
            .into_iter()
            .map(SitePackagesPath::into_path)
            .collect::<Vec<_>>()
            .into_iter()
    }
}

impl PartialEq<&[SystemPathBuf]> for SitePackagesPaths {
    fn eq(&self, other: &&[SystemPathBuf]) -> bool {
        self.0.iter().map(|path| &path.path).eq(other.iter())
    }
}

#[derive(Debug)]
pub enum PythonEnvironment {
    Virtual(VirtualEnvironment),
    System(SystemEnvironment),
}

impl PythonEnvironment {
    /// Discover the python environment using the following priorities:
    ///
    /// 1. activated virtual environment
    /// 2. conda (child)
    /// 3. project virtual environment, when a project root is provided
    /// 4. conda (base)
    pub fn discover(
        project_root: Option<&SystemPath>,
        system: &dyn System,
    ) -> Result<Option<Self>, SitePackagesDiscoveryError> {
        fn resolve_environment(
            system: &dyn System,
            path: &SystemPath,
            origin: SysPrefixPathOrigin,
        ) -> Result<PythonEnvironment, SitePackagesDiscoveryError> {
            tracing::debug!("Resolving {origin}: {path}");
            PythonEnvironment::new(path, origin, system)
        }

        if let Ok(virtual_env) = system.env_var(EnvVars::VIRTUAL_ENV) {
            return resolve_environment(
                system,
                SystemPath::new(&virtual_env),
                SysPrefixPathOrigin::VirtualEnvVar,
            )
            .map(Some);
        }

        if let Some(conda_env) = conda_environment_from_env(system, CondaEnvironmentKind::Child) {
            return resolve_environment(system, &conda_env, SysPrefixPathOrigin::CondaPrefixVar)
                .map(Some);
        }

        if let Some(project_root) = project_root {
            tracing::debug!("Discovering virtual environment in `{project_root}`");
            let virtual_env_directory = project_root.join(".venv");

            match PythonEnvironment::new(
                &virtual_env_directory,
                SysPrefixPathOrigin::LocalVenv,
                system,
            ) {
                Ok(environment) => return Ok(Some(environment)),
                Err(err) => {
                    if system.is_directory(&virtual_env_directory) {
                        tracing::debug!(
                            "Ignoring automatically detected virtual environment at `{}`: {}",
                            &virtual_env_directory,
                            err
                        );
                    }
                }
            }
        }

        if let Some(conda_env) = conda_environment_from_env(system, CondaEnvironmentKind::Base) {
            return resolve_environment(system, &conda_env, SysPrefixPathOrigin::CondaPrefixVar)
                .map(Some);
        }

        if let Some(env) = environment_from_binary(system, "python3")
            .or_else(|| environment_from_binary(system, "python"))
        {
            return Ok(Some(env));
        }

        Ok(None)
    }

    pub fn new(
        path: impl AsRef<SystemPath>,
        origin: SysPrefixPathOrigin,
        system: &dyn System,
    ) -> SitePackagesDiscoveryResult<Self> {
        let path = PythonEnvironmentPath::new(path.as_ref(), origin, system)?;

        // Attempt to inspect as a virtual environment first
        match VirtualEnvironment::new(path.sys_prefix(), system) {
            Ok(venv) => Ok(Self::Virtual(venv)),
            // If there's not a `pyvenv.cfg` marker, attempt to inspect as a system environment
            Err(SitePackagesDiscoveryError::NoPyvenvCfgFile(_, _, _))
                if !path.origin().must_be_virtual_env() =>
            {
                tracing::trace!(
                    "Resolved system Python environment from `{}`",
                    path.selected_path()
                );
                Ok(Self::System(SystemEnvironment { path }))
            }
            Err(err) => Err(err),
        }
    }

    /// Returns the canonical, absolute `sys.prefix` of this environment.
    pub fn sys_prefix(&self) -> &SysPrefixPath {
        match self {
            Self::Virtual(env) => &env.root_path,
            Self::System(env) => env.path.sys_prefix(),
        }
    }

    /// Returns the Python version that was used to create this environment
    /// (will only be available for virtual environments that specify
    /// the metadata in their `pyvenv.cfg` files).
    pub fn python_version_from_metadata(&self) -> Option<&PythonVersionWithSource> {
        match self {
            Self::Virtual(venv) => venv.version.as_ref(),
            Self::System(_) => None,
        }
    }

    pub fn site_packages_paths(
        &self,
        system: &dyn System,
    ) -> SitePackagesDiscoveryResult<SitePackagesPaths> {
        match self {
            Self::Virtual(env) => env.site_packages_directories(system),
            Self::System(env) => env.site_packages_directories(system),
        }
    }

    pub fn real_stdlib_path(&self, system: &dyn System) -> StdlibDiscoveryResult<SystemPathBuf> {
        match self {
            Self::Virtual(env) => env.real_stdlib_directory(system),
            Self::System(env) => env.real_stdlib_directory(system),
        }
    }

    pub fn origin(&self) -> &SysPrefixPathOrigin {
        match self {
            Self::Virtual(env) => &env.root_path.origin,
            Self::System(env) => env.path.origin(),
        }
    }

    /// Returns `true` if this is a virtual environment (has a `pyvenv.cfg` file).
    pub fn is_virtual(&self) -> bool {
        matches!(self, Self::Virtual(_))
    }
}

/// Enumeration of the subdirectories of `sys.prefix` that could contain a
/// `site-packages` directory if the host system is Unix-like.
///
/// For example, if `sys.prefix` is `.venv` and the Python version is 3.10,
/// the `site-packages` directory could be located at `.venv/lib/python3.10/site-packages`,
/// or at `.venv/lib64/python3.10/site-packages`, or there could indeed be `site-packages`
/// directories at both of these locations.
#[derive(Debug, Clone, Copy, Eq, PartialEq, strum_macros::EnumIter)]
enum UnixLibDir {
    Lib,
    Lib64,
}

impl UnixLibDir {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Lib => "lib",
            Self::Lib64 => "lib64",
        }
    }
}

impl std::fmt::Display for UnixLibDir {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl AsRef<SystemPath> for UnixLibDir {
    fn as_ref(&self) -> &SystemPath {
        SystemPath::new(self.as_str())
    }
}

impl PartialEq<&str> for UnixLibDir {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<UnixLibDir> for &str {
    fn eq(&self, other: &UnixLibDir) -> bool {
        other == self
    }
}

/// The subdirectory name under a version-specific Python lib directory
/// that contains installed packages.
///
/// For example, `site-packages` (the standard layout) or `dist-packages`
/// (used by Debian/Ubuntu for system-managed packages).
#[derive(Debug, Clone, Copy, Eq, PartialEq, strum_macros::EnumIter)]
enum InstallationDir {
    SitePackages,
    DistPackages,
}

impl InstallationDir {
    const fn as_str(self) -> &'static str {
        match self {
            Self::SitePackages => "site-packages",
            Self::DistPackages => "dist-packages",
        }
    }
}

impl std::fmt::Display for InstallationDir {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The Python runtime that produced the venv.
///
/// We only need to distinguish cases that change the on-disk layout.
/// Everything else can be treated like CPython.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub(crate) enum PythonImplementation {
    CPython,
    PyPy,
    GraalPy,
    /// Fallback when the value is missing or unrecognised.
    /// We treat it like CPython but keep the information for diagnostics.
    #[default]
    Unknown,
}

impl PythonImplementation {
    const fn is_cpython(self) -> bool {
        matches!(self, Self::CPython)
    }

    fn split_executable_name(file_name: &str) -> Option<(Self, &str)> {
        if let Some(suffix) = file_name.strip_prefix("python") {
            Some((Self::CPython, suffix))
        } else if let Some(suffix) = file_name.strip_prefix("pypy") {
            Some((Self::PyPy, suffix))
        } else {
            Some((Self::GraalPy, file_name.strip_prefix("graalpy")?))
        }
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
struct PythonInterpreterLayout {
    version: Option<PythonVersion>,
    implementation: PythonImplementation,
    variant: PythonBuildVariant,
}

impl PythonInterpreterLayout {
    const fn unknown(implementation: PythonImplementation, version: Option<PythonVersion>) -> Self {
        Self {
            version,
            implementation,
            variant: PythonBuildVariant::Unknown,
        }
    }

    fn from_path(path: &SystemPath, system: &dyn System) -> Option<Self> {
        let mut layout = Self::from_file_name(path.file_name()?)?;

        if layout.implementation.is_cpython()
            && layout.variant.is_unknown()
            && let Some(version) = layout.version
            && version.free_threaded_build_available()
            && let Some(parent) = path.parent()
        {
            let mut variant = PythonBuildVariant::Default;

            // CPython's Unix installer hard-links `pythonX.Y` to its versioned executable for a
            // free-threaded build, so neither the file name nor canonicalization can distinguish
            // the two executable paths. Debug builds use the `td` ABI flags but retain the `t`
            // suffix for their library directory.
            for abi_flags in ["t", "td"] {
                let free_threaded_executable = parent.join(format!(
                    "python{version}{abi_flags}{}",
                    std::env::consts::EXE_SUFFIX
                ));

                if !system.is_file(&free_threaded_executable) {
                    continue;
                }

                match system.is_same_file(path, &free_threaded_executable) {
                    Ok(true) => {
                        variant = PythonBuildVariant::FreeThreaded;
                        break;
                    }
                    Ok(false) => {}
                    Err(_) => variant = PythonBuildVariant::Unknown,
                }
            }

            layout.variant = variant;
        }

        Some(layout)
    }

    fn from_file_name(file_name: &str) -> Option<Self> {
        let file_name = file_name
            .strip_suffix(std::env::consts::EXE_SUFFIX)
            .unwrap_or(file_name);

        let (implementation, version) = PythonImplementation::split_executable_name(file_name)?;
        let (version, variant) = PythonBuildVariant::split_executable_suffix(version);
        let version = match PythonVersion::from_str(version) {
            Ok(version) => version,
            Err(_) if variant == PythonBuildVariant::FreeThreaded => return None,
            Err(_) => {
                // PyPy also uses generic executable names such as `python` and `python3`, so an
                // unversioned name in the `python` family does not identify the implementation.
                let implementation = if implementation.is_cpython() {
                    PythonImplementation::Unknown
                } else {
                    implementation
                };
                return Some(Self::unknown(implementation, None));
            }
        };

        if variant == PythonBuildVariant::FreeThreaded
            && (!implementation.is_cpython() || !version.free_threaded_build_available())
        {
            return None;
        }

        // CPython may install `pythonX.Y` as a hard link to `pythonX.Yt`, so defer the build
        // variant until `from_path` can compare the two executable paths.
        let variant = if variant == PythonBuildVariant::Default
            && implementation.is_cpython()
            && version.free_threaded_build_available()
        {
            PythonBuildVariant::Unknown
        } else {
            variant
        };

        Some(Self {
            version: Some(version),
            implementation,
            variant,
        })
    }

    /// Return the relative path from `sys.prefix` to the directory containing the Python stdlib's
    /// `.py` files if the interpreter layout is known.
    fn relative_stdlib_path(self) -> Option<String> {
        let version = self.version?;

        match self.implementation {
            PythonImplementation::CPython => {
                let variant = self.variant.suffix();
                Some(format!("lib/python{version}{variant}"))
            }
            PythonImplementation::GraalPy => Some(format!("lib/python{version}")),
            PythonImplementation::PyPy => Some(format!("lib/pypy{version}")),
            PythonImplementation::Unknown => None,
        }
    }

    fn free_threaded_stdlib_fallback_path(self) -> Option<String> {
        let version = self.version?;

        (self.implementation.is_cpython()
            && self.variant.is_unknown()
            && version.free_threaded_build_available())
        .then(|| format!("lib/python{version}t"))
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
enum PythonBuildVariant {
    #[default]
    Unknown,
    Default,
    FreeThreaded,
}

impl PythonBuildVariant {
    const fn is_unknown(self) -> bool {
        matches!(self, Self::Unknown)
    }

    fn split_executable_suffix(version: &str) -> (&str, Self) {
        // Debug builds add `d` to the ABI flags, but this does not change the library layout.
        let version = version.strip_suffix('d').unwrap_or(version);

        if let Some(version) = version.strip_suffix('t') {
            (version, Self::FreeThreaded)
        } else {
            (version, Self::Default)
        }
    }

    const fn suffix(self) -> &'static str {
        match self {
            Self::Unknown | Self::Default => "",
            Self::FreeThreaded => "t",
        }
    }
}

/// Abstraction for a Python virtual environment.
///
/// Most of this information is derived from the virtual environment's `pyvenv.cfg` file.
/// The format of this file is not defined anywhere, and exactly which keys are present
/// depends on the tool that was used to create the virtual environment.
#[derive(Debug)]
pub struct VirtualEnvironment {
    root_path: SysPrefixPath,
    base_executable_home_path: Option<PythonHomePath>,
    include_system_site_packages: bool,

    /// The version of the Python executable that was used to create this virtual environment.
    ///
    /// The Python version is encoded under different keys and in different formats
    /// by different virtual-environment creation tools,
    /// and the key is never read by the standard-library `site.py` module,
    /// so it's possible that we might not be able to find this information
    /// in an acceptable format under any of the keys we expect.
    /// This field will be `None` if so.
    version: Option<PythonVersionWithSource>,
    implementation: PythonImplementation,

    /// If this virtual environment was created using uv,
    /// it may be an "ephemeral" virtual environment that dynamically adds the `site-packages`
    /// directories of its parent environment to `sys.path` at runtime.
    /// Newer versions of uv record the parent environment in the `pyvenv.cfg` file;
    /// we'll want to add the `site-packages` directories of the parent environment
    /// as search paths as well as the `site-packages` directories of this virtual environment.
    parent_environment: Option<Box<PythonEnvironment>>,
}

impl VirtualEnvironment {
    fn new(path: &SysPrefixPath, system: &dyn System) -> SitePackagesDiscoveryResult<Self> {
        let pyvenv_cfg_path = path.join("pyvenv.cfg");
        tracing::debug!("Attempting to parse virtual environment metadata at '{pyvenv_cfg_path}'");

        let pyvenv_cfg = match system.read_to_string(&pyvenv_cfg_path) {
            Ok(pyvenv_cfg) => pyvenv_cfg,
            Err(err) => {
                return Err(SitePackagesDiscoveryError::NoPyvenvCfgFile(
                    path.clone(),
                    err,
                    system.dyn_clone(),
                ));
            }
        };

        let parsed_pyvenv_cfg =
            PyvenvCfgParser::new(&pyvenv_cfg)
                .parse()
                .map_err(|pyvenv_parse_error| {
                    SitePackagesDiscoveryError::PyvenvCfgParseError(
                        pyvenv_cfg_path.clone(),
                        pyvenv_parse_error,
                    )
                })?;

        let RawPyvenvCfg {
            include_system_site_packages,
            base_executable_home_path,
            version,
            implementation,
            created_with_uv,
            parent_environment,
        } = parsed_pyvenv_cfg;

        // The `home` key is read by the standard library's `site.py` module, so a missing
        // key indicates an irredeemably broken virtual environment. An unresolvable value
        // can still be tolerated when the base interpreter is not needed.
        let Some(base_executable_home_path) = base_executable_home_path else {
            return Err(SitePackagesDiscoveryError::PyvenvCfgParseError(
                pyvenv_cfg_path,
                PyvenvCfgParseErrorKind::NoHomeKey,
            ));
        };

        let base_executable_home_path = match PythonHomePath::new(base_executable_home_path, system)
        {
            Ok(home_path) => Some(home_path),
            Err(io_err) if !include_system_site_packages => {
                tracing::warn!(
                    "Failed to resolve the `home` value in the `pyvenv.cfg` file at \
                     `{pyvenv_cfg_path}`. Goto-definition for stdlib-defined items will not \
                     be able to jump to the real implementation. Underlying error: {io_err}"
                );
                None
            }
            Err(io_err) => {
                return Err(SitePackagesDiscoveryError::PyvenvCfgParseError(
                    pyvenv_cfg_path.clone(),
                    PyvenvCfgParseErrorKind::InvalidHomeValue(io_err),
                ));
            }
        };

        // Since the `extends-environment` key is nonstandard,
        // for now we only trust it if the virtual environment was created with `uv`.
        let parent_environment = if created_with_uv {
            parent_environment
                .and_then(|sys_prefix| {
                    PythonEnvironment::new(
                        sys_prefix,
                        SysPrefixPathOrigin::DerivedFromPyvenvCfg,
                        system,
                    )
                    .inspect_err(|err| {
                        tracing::warn!(
                            "Failed to resolve the parent environment \
                            of this ephemeral uv virtual environment \
                            from the `extends-environment` value specified \
                            in the `pyvenv.cfg` file at {pyvenv_cfg_path}. \
                            Imports will not be resolved correctly \
                            if they refer to packages installed \
                            into the parent environment. \
                            Underlying error: {err}",
                        );
                    })
                    .ok()
                })
                .map(Box::new)
        } else {
            None
        };

        // but the `version`/`version_info` key is not read by the standard library,
        // and is provided under different keys depending on which virtual-environment creation tool
        // created the `pyvenv.cfg` file. Lenient parsing is appropriate here:
        // the file isn't really *invalid* if it doesn't have this key,
        // or if the value doesn't parse according to our expectations.
        let version = version.and_then(|(version_string, range)| {
            let mut version_info_parts = version_string.split('.');
            let (major, minor) = (version_info_parts.next()?, version_info_parts.next()?);
            let version = PythonVersion::try_from((major, minor)).ok()?;
            let source = PythonVersionSource::PyvenvCfgFile(PythonVersionFileSource::new(
                Arc::new(pyvenv_cfg_path),
                Some(range),
            ));
            Some(PythonVersionWithSource { version, source })
        });

        let metadata = Self {
            root_path: path.clone(),
            base_executable_home_path,
            include_system_site_packages,
            version,
            implementation,
            parent_environment,
        };

        tracing::trace!("Resolved metadata for virtual environment: {metadata:?}");
        Ok(metadata)
    }

    /// Return a list of `site-packages` directories that are available from this virtual environment
    ///
    /// See the documentation for [`site_packages_directories_from_sys_prefix`] for more details.
    fn site_packages_directories(
        &self,
        system: &dyn System,
    ) -> SitePackagesDiscoveryResult<SitePackagesPaths> {
        let VirtualEnvironment {
            root_path,
            base_executable_home_path,
            include_system_site_packages,
            implementation,
            version,
            parent_environment,
        } = self;

        let version = version.as_ref().map(|v| v.version);
        let layout = PythonInterpreterLayout::unknown(*implementation, version);

        let mut site_packages_directories =
            site_packages_directories_from_sys_prefix(root_path, layout, system)?;

        if let Some(parent_env_site_packages) = parent_environment.as_deref() {
            match parent_env_site_packages.site_packages_paths(system) {
                Ok(parent_environment_site_packages) => {
                    site_packages_directories.extend(parent_environment_site_packages);
                }
                Err(err) => {
                    tracing::warn!(
                        "Failed to resolve the site-packages directories \
                        of this ephemeral uv virtual environment's parent environment. \
                        Imports will not be resolved correctly if they refer to packages \
                        installed into the parent environment. \
                        Underlying error: {err}"
                    );
                }
            }
        }

        if *include_system_site_packages {
            let system_sys_prefix = base_executable_home_path
                .as_ref()
                .and_then(SysPrefixPath::from_executable_home_path);

            // If we fail to resolve the `sys.prefix` path from the base executable home path,
            // or if we fail to resolve the `site-packages` from the `sys.prefix` path,
            // we should probably print a warning but *not* abort type checking
            if let Some(sys_prefix_path) = system_sys_prefix {
                match site_packages_directories_from_sys_prefix(&sys_prefix_path, layout, system) {
                    Ok(system_directories) => {
                        site_packages_directories.extend(system_directories);
                    }
                    Err(error) => tracing::warn!(
                        "{error}. System site-packages will not be used for module resolution."
                    ),
                }
            } else {
                tracing::warn!(
                    "Failed to resolve `sys.prefix` of the system Python installation \
                    from the `home` value in the `pyvenv.cfg` file at `{}`. \
                    System site-packages will not be used for module resolution.",
                    root_path.join("pyvenv.cfg")
                );
            }
        }

        tracing::debug!(
            "Resolved site-packages directories for this virtual environment are: \
            {site_packages_directories}"
        );
        Ok(site_packages_directories)
    }

    /// Return the real stdlib path (containing actual .py files, and not some variation of typeshed).
    ///
    /// See the documentation for [`real_stdlib_directory_from_sys_prefix`] for more details.
    fn real_stdlib_directory(&self, system: &dyn System) -> StdlibDiscoveryResult<SystemPathBuf> {
        let VirtualEnvironment {
            base_executable_home_path,
            implementation,
            version,
            // Unlike site-packages, what we're looking for is never inside the virtual environment
            // so this is only used for diagnostics.
            root_path,
            // We don't need to respect this setting
            include_system_site_packages: _,
            // We don't need to inherit any info from the parent environment
            parent_environment: _,
        } = self;

        // Unconditionally follow the same logic that `site_packages_directories` uses when
        // `include_system_site_packages` is true, as those site-packages should be a subdir
        // of the dir we're looking for.
        let version = version.as_ref().map(|v| v.version);
        let layout = PythonInterpreterLayout::unknown(*implementation, version);
        if let Some(system_sys_prefix) = base_executable_home_path
            .as_ref()
            .and_then(|home_path| SysPrefixPath::from_executable_home_path_real(system, home_path))
        {
            let real_stdlib_directory =
                real_stdlib_directory_from_sys_prefix(&system_sys_prefix, layout, system);
            match &real_stdlib_directory {
                Ok(path) => tracing::debug!(
                    "Resolved real stdlib path for this virtual environment is: {path}"
                ),
                Err(_) => tracing::debug!(
                    "Failed to resolve real stdlib path for this virtual environment"
                ),
            }
            real_stdlib_directory
        } else {
            let cfg_path = root_path.join("pyvenv.cfg");
            tracing::debug!(
                "Failed to resolve `sys.prefix` of the system Python installation from the `home` \
                 value in the `pyvenv.cfg` file at `{cfg_path}`. System stdlib will not be used \
                 for module definitions.",
            );
            Err(StdlibDiscoveryError::NoSysPrefixFound(cfg_path))
        }
    }
}

/// Different kinds of conda environment
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub(crate) enum CondaEnvironmentKind {
    /// The base Conda environment; treated like a system Python environment.
    Base,
    /// Any other Conda environment; treated like a virtual environment.
    Child,
}

impl CondaEnvironmentKind {
    /// Compute the kind of `CONDA_PREFIX` we have.
    ///
    /// The base environment is typically stored in a location matching the `_CONDA_ROOT` path.
    ///
    /// Additionally, when the base environment is active, `CONDA_DEFAULT_ENV` will be set to a
    /// name, e.g., `base`, which does not match the `CONDA_PREFIX`, e.g., `/usr/local` instead of
    /// `/usr/local/conda/envs/<name>`. Note that the name `CONDA_DEFAULT_ENV` is misleading, it's
    /// the active environment name, not a constant base environment name.
    fn from_prefix_path(system: &dyn System, path: &SystemPath) -> Self {
        // If `_CONDA_ROOT` is set and matches `CONDA_PREFIX`, it's the base environment.
        if let Ok(conda_root) = system.env_var(EnvVars::CONDA_ROOT)
            && path.as_str() == conda_root
        {
            return Self::Base;
        }

        // Next, we'll use a heuristic based on `CONDA_DEFAULT_ENV`
        let Ok(current_env) = system.env_var(EnvVars::CONDA_DEFAULT_ENV) else {
            return Self::Child;
        };

        // If the environment name is "base" or "root", treat it as a base environment
        //
        // These are the expected names for the base environment; and is retained for backwards
        // compatibility, but in a future breaking release we should remove this special-casing.
        if current_env == "base" || current_env == "root" {
            return Self::Base;
        }

        // For other environment names, use the path-based logic
        let Some(name) = path.file_name() else {
            return Self::Child;
        };

        // If the environment is in a directory matching the name of the environment, it's not
        // usually a base environment.
        if name == current_env {
            Self::Child
        } else {
            Self::Base
        }
    }
}

/// Read `CONDA_PREFIX` and confirm that it has the expected kind
fn conda_environment_from_env(
    system: &dyn System,
    kind: CondaEnvironmentKind,
) -> Option<SystemPathBuf> {
    let dir = system
        .env_var(EnvVars::CONDA_PREFIX)
        .ok()
        .filter(|value| !value.is_empty())?;
    let path = SystemPathBuf::from(dir);

    if kind != CondaEnvironmentKind::from_prefix_path(system, &path) {
        return None;
    }

    Some(path)
}

fn environment_from_binary(system: &dyn System, binary: &str) -> Option<PythonEnvironment> {
    let binary = system.which(binary).ok()?;
    let env = PythonEnvironment::new(binary, SysPrefixPathOrigin::PythonBinary, system).ok()?;

    // TODO: replace this with better shim support, e.g. pyenv
    // sanity check to filter out shims
    env.site_packages_paths(system).ok()?;

    Some(env)
}

/// A parser for `pyvenv.cfg` files: metadata files for virtual environments.
///
/// Note that a `pyvenv.cfg` file *looks* like a `.ini` file, but actually isn't valid `.ini` syntax!
///
/// See also: <https://snarky.ca/how-virtual-environments-work/>
#[derive(Debug)]
struct PyvenvCfgParser<'s> {
    source: &'s str,
    cursor: Cursor<'s>,
    line_number: NonZeroUsize,
    data: RawPyvenvCfg<'s>,
}

impl<'s> PyvenvCfgParser<'s> {
    fn new(source: &'s str) -> Self {
        Self {
            source,
            cursor: Cursor::new(source),
            line_number: NonZeroUsize::new(1).unwrap(),
            data: RawPyvenvCfg::default(),
        }
    }

    /// Parse the `pyvenv.cfg` file and return the parsed data.
    fn parse(mut self) -> Result<RawPyvenvCfg<'s>, PyvenvCfgParseErrorKind> {
        while !self.cursor.is_eof() {
            self.parse_line()?;
            self.line_number = self.line_number.checked_add(1).unwrap();
        }
        Ok(self.data)
    }

    /// Parse a single line of the `pyvenv.cfg` file and advance the cursor
    /// to the beginning of the next line.
    fn parse_line(&mut self) -> Result<(), PyvenvCfgParseErrorKind> {
        let PyvenvCfgParser {
            source,
            cursor,
            line_number,
            data,
        } = self;

        let line_number = *line_number;

        cursor.eat_while(|c| c.is_whitespace() && c != '\n');

        let key_start = cursor.offset();
        cursor.eat_while(|c| !matches!(c, '\n' | '='));
        let key_end = cursor.offset();

        if !cursor.eat_char('=') {
            // Skip over any lines that do not contain '=' characters, same as the CPython stdlib
            // <https://github.com/python/cpython/blob/e64395e8eb8d3a9e35e3e534e87d427ff27ab0a5/Lib/site.py#L625-L632>
            cursor.eat_char('\n');
            return Ok(());
        }

        let key = source[TextRange::new(key_start, key_end)].trim();

        cursor.eat_while(|c| c.is_whitespace() && c != '\n');
        let value_start = cursor.offset();
        cursor.eat_while(|c| c != '\n');
        let value = source[TextRange::new(value_start, cursor.offset())].trim();
        cursor.eat_char('\n');

        if value.is_empty() {
            return Err(PyvenvCfgParseErrorKind::MalformedKeyValuePair { line_number });
        }

        match key {
            "include-system-site-packages" => {
                data.include_system_site_packages = value.eq_ignore_ascii_case("true");
            }
            "home" => data.base_executable_home_path = Some(value),
            // `virtualenv` and `uv` call this key `version_info`,
            // but the stdlib venv module calls it `version`
            "version" | "version_info" => {
                let version_range = TextRange::at(value_start, value.text_len());
                data.version = Some((value, version_range));
            }
            "implementation" => {
                data.implementation = match value.to_ascii_lowercase().as_str() {
                    "cpython" => PythonImplementation::CPython,
                    "graalvm" => PythonImplementation::GraalPy,
                    "pypy" => PythonImplementation::PyPy,
                    _ => PythonImplementation::Unknown,
                };
            }
            "uv" => data.created_with_uv = true,
            "extends-environment" => data.parent_environment = Some(value),
            "" => {
                return Err(PyvenvCfgParseErrorKind::MalformedKeyValuePair { line_number });
            }
            _ => {}
        }

        Ok(())
    }
}

/// A `key:value` mapping derived from parsing a `pyvenv.cfg` file.
///
/// This data contained within is still mostly raw and unvalidated.
#[derive(Debug, Default)]
struct RawPyvenvCfg<'s> {
    include_system_site_packages: bool,
    base_executable_home_path: Option<&'s str>,
    version: Option<(&'s str, TextRange)>,
    implementation: PythonImplementation,
    created_with_uv: bool,
    parent_environment: Option<&'s str>,
}

/// A Python environment that is _not_ a virtual environment.
///
/// This environment may or may not be one that is managed by the operating system itself, e.g.,
/// this captures both Homebrew-installed Python versions and the bundled macOS Python installation.
#[derive(Debug)]
pub struct SystemEnvironment {
    path: PythonEnvironmentPath,
}

impl SystemEnvironment {
    /// Return a list of `site-packages` directories that are available from this environment.
    ///
    /// See the documentation for [`site_packages_directories_from_sys_prefix`] for more details.
    fn site_packages_directories(
        &self,
        system: &dyn System,
    ) -> SitePackagesDiscoveryResult<SitePackagesPaths> {
        let site_packages_directories = site_packages_directories_from_sys_prefix(
            self.path.sys_prefix(),
            self.path.interpreter_layout().unwrap_or_default(),
            system,
        )?;

        tracing::debug!(
            "Resolved site-packages directories for this environment are: \
            {site_packages_directories}"
        );
        Ok(site_packages_directories)
    }

    /// Return a list of `site-packages` directories that are available from this environment.
    ///
    /// See the documentation for [`site_packages_directories_from_sys_prefix`] for more details.
    fn real_stdlib_directory(&self, system: &dyn System) -> StdlibDiscoveryResult<SystemPathBuf> {
        let stdlib_directory = real_stdlib_directory_from_sys_prefix(
            self.path.sys_prefix(),
            self.path.interpreter_layout().unwrap_or_default(),
            system,
        )?;

        tracing::debug!(
            "Resolved real stdlib directory for this environment is: {stdlib_directory:?}"
        );
        Ok(stdlib_directory)
    }
}

/// Enumeration of ways in which `site-packages` discovery can fail.
#[derive(Debug)]
pub enum SitePackagesDiscoveryError {
    /// `site-packages` discovery failed because the provided path couldn't be canonicalized.
    CanonicalizationError(
        SystemPathBuf,
        SysPrefixPathOrigin,
        io::Error,
        Box<dyn System>,
    ),

    /// `site-packages` discovery failed because the provided path doesn't appear to point to
    /// a Python executable or a `sys.prefix` directory.
    PathNotExecutableOrDirectory(
        SystemPathBuf,
        SysPrefixPathOrigin,
        Option<io::Error>,
        Box<dyn System>,
    ),

    /// `site-packages` discovery failed because the [`SysPrefixPathOrigin`] indicated that
    /// the provided path should point to the `sys.prefix` of a virtual environment,
    /// but there was no file at `<sys.prefix>/pyvenv.cfg`.
    NoPyvenvCfgFile(SysPrefixPath, io::Error, Box<dyn System>),

    /// `site-packages` discovery failed because the `pyvenv.cfg` file could not be parsed.
    PyvenvCfgParseError(SystemPathBuf, PyvenvCfgParseErrorKind),

    /// `site-packages` discovery failed because we're on a Unix system,
    /// we weren't able to figure out from the `pyvenv.cfg` file exactly where `site-packages`
    /// would be relative to the `sys.prefix` path, and we tried to fallback to iterating
    /// through the `<sys.prefix>/lib` directory looking for a `site-packages` directory,
    /// but we came across some I/O error while trying to do so.
    CouldNotReadLibDirectory(SysPrefixPath, Box<dyn System>),

    /// We looked everywhere we could think of for the `site-packages` directory,
    /// but none could be found despite our best endeavours.
    NoSitePackagesDirFound(SysPrefixPath, Box<dyn System>),
}

/// Enumeration of ways in which stdlib discovery can fail.
#[derive(Debug)]
pub enum StdlibDiscoveryError {
    /// We looked everywhere we could think of for the standard library's directory,
    /// but none could be found despite our best endeavours.
    NoStdlibFound(SysPrefixPath, Box<dyn System>),
    /// Stdlib discovery failed because we're on a Unix system,
    /// we weren't able to figure out from the `pyvenv.cfg` file exactly where the stdlib
    /// would be relative to the `sys.prefix` path, and we tried to fallback to iterating
    /// through the `<sys.prefix>/lib` directory looking for a stdlib directory,
    /// but we came across some I/O error while trying to do so.
    CouldNotReadLibDirectory(SysPrefixPath, io::Error, Box<dyn System>),
    /// We failed to resolve the value of `sys.prefix`.
    NoSysPrefixFound(SystemPathBuf),
}

impl std::error::Error for SitePackagesDiscoveryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CanonicalizationError(_, _, io_err, _) => Some(io_err),
            Self::PathNotExecutableOrDirectory(_, _, io_err, _) => {
                io_err.as_ref().map(|e| e as &dyn std::error::Error)
            }
            Self::NoPyvenvCfgFile(_, io_err, _) => Some(io_err),
            Self::PyvenvCfgParseError(_, _)
            | Self::CouldNotReadLibDirectory(_, _)
            | Self::NoSitePackagesDirFound(_, _) => None,
        }
    }
}

impl std::fmt::Display for SitePackagesDiscoveryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CanonicalizationError(given_path, origin, _, system) => display_error(
                f,
                origin,
                given_path,
                "Failed to canonicalize",
                None,
                &**system,
            ),
            Self::PathNotExecutableOrDirectory(path, origin, _, system) => {
                let thing = if origin.must_point_directly_to_sys_prefix() {
                    "directory on disk"
                } else {
                    "Python executable or a directory on disk"
                };
                display_error(
                    f,
                    origin,
                    path,
                    &format!("Invalid {origin}"),
                    Some(&format!("does not point to a {thing}")),
                    &**system,
                )
            }
            Self::NoPyvenvCfgFile(SysPrefixPath { inner, origin }, _, system) => display_error(
                f,
                origin,
                inner,
                &format!("Invalid {origin}"),
                Some("points to a broken venv with no pyvenv.cfg file"),
                &**system,
            ),
            Self::PyvenvCfgParseError(path, kind) => {
                write!(
                    f,
                    "Failed to parse the `pyvenv.cfg` file at `{path}` because {kind}"
                )
            }
            Self::CouldNotReadLibDirectory(SysPrefixPath { inner, origin }, system) => {
                display_error(
                    f,
                    origin,
                    inner,
                    "Failed to iterate over the contents \
                    of the `lib`/`lib64` directories of the Python installation",
                    None,
                    &**system,
                )
            }
            Self::NoSitePackagesDirFound(SysPrefixPath { inner, origin }, system) => display_error(
                f,
                origin,
                inner,
                &format!("Invalid {origin}"),
                Some(
                    "Could not find a `site-packages` directory for this Python \
                    installation/executable",
                ),
                &**system,
            ),
        }
    }
}

impl std::error::Error for StdlibDiscoveryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CouldNotReadLibDirectory(_, io_err, _) => Some(io_err),
            Self::NoStdlibFound(_, _) => None,
            Self::NoSysPrefixFound(_) => None,
        }
    }
}

impl std::fmt::Display for StdlibDiscoveryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoSysPrefixFound(path) => {
                write!(
                    f,
                    "Failed to resolve a `sys.prefix` from the `pyvenv.cfg` file at `{path}`"
                )
            }
            Self::CouldNotReadLibDirectory(SysPrefixPath { inner, origin }, _, system) => {
                display_error(
                    f,
                    origin,
                    inner,
                    "Failed to iterate over the contents \
                    of the `lib` directory of the Python installation",
                    None,
                    &**system,
                )
            }
            Self::NoStdlibFound(SysPrefixPath { inner, origin }, system) => display_error(
                f,
                origin,
                inner,
                &format!("Invalid {origin}"),
                Some("Could not find a stdlib directory for this Python installation/executable"),
                &**system,
            ),
        }
    }
}

fn display_error(
    f: &mut std::fmt::Formatter<'_>,
    sys_prefix_origin: &SysPrefixPathOrigin,
    given_path: &SystemPath,
    primary_message: &str,
    secondary_message: Option<&str>,
    system: &dyn System,
) -> std::fmt::Result {
    let fallback: &mut dyn FnMut() -> std::fmt::Result = &mut || {
        f.write_str(primary_message)?;
        write!(f, " `{given_path}`")?;
        if let Some(secondary_message) = secondary_message {
            f.write_str(": ")?;
            f.write_str(secondary_message)?;
        }
        Ok(())
    };

    let SysPrefixPathOrigin::ConfigFileSetting(config_file_path, Some(setting_range)) =
        sys_prefix_origin
    else {
        return fallback();
    };

    let Ok(config_file_source) = system.read_to_string(config_file_path) else {
        return fallback();
    };

    let index = LineIndex::from_source_text(&config_file_source);
    let source = SourceCode::new(&config_file_source, &index);

    let primary_message = format!(
        "{primary_message}

--> Invalid setting in configuration file `{config_file_path}`"
    );

    let start_index = source.line_index(setting_range.start()).saturating_sub(2);
    let end_index = source
        .line_index(setting_range.end())
        .saturating_add(2)
        .min(OneIndexed::from_zero_indexed(source.line_count()));

    let start_offset = source.line_start(start_index);
    let end_offset = source.line_end(end_index);

    let mut annotation = AnnotationKind::Primary.span((setting_range - start_offset).into());

    if let Some(secondary_message) = secondary_message {
        annotation = annotation.label(secondary_message);
    }

    let snippet = Snippet::source(&config_file_source[TextRange::new(start_offset, end_offset)])
        .annotation(annotation)
        .line_start(start_index.get())
        .fold(false);

    let message = Level::ERROR
        .no_name()
        .primary_title(&primary_message)
        .element(snippet);

    let renderer = if colored::control::SHOULD_COLORIZE.should_colorize() {
        Renderer::styled()
    } else {
        Renderer::plain()
    };
    let renderer = renderer.cut_indicator("…");

    writeln!(f, "{}", renderer.render(&[message]))
}

/// The various ways in which parsing a `pyvenv.cfg` file could fail
#[derive(Debug)]
pub enum PyvenvCfgParseErrorKind {
    MalformedKeyValuePair { line_number: NonZeroUsize },
    NoHomeKey,
    InvalidHomeValue(io::Error),
}

impl fmt::Display for PyvenvCfgParseErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MalformedKeyValuePair { line_number } => write!(
                f,
                "line {line_number} has a malformed `<key> = <value>` pair"
            ),
            Self::NoHomeKey => f.write_str("the file does not have a `home` key"),
            Self::InvalidHomeValue(io_err) => {
                write!(
                    f,
                    "the following error was encountered \
                    when trying to resolve the `home` value \
                    to a directory on disk: {io_err}"
                )
            }
        }
    }
}

/// Probe exact package directories under `prefix_dir` for a known Python version.
///
/// Discovers directories in the form `{prefix_dir}/{python,pypy}X.Y[t]/{suffix}`, where `suffix`
/// will typically be `site-packages` (but sometimes `dist-packages` on Debian).
///
/// If implementation is `Unknown`, probe CPython-style paths first, then PyPy-style paths.
fn probe_package_dirs(
    prefix_dir: &SystemPath,
    suffix: InstallationDir,
    layout: PythonInterpreterLayout,
    system: &dyn System,
    settings_diagnostic_path: Option<&SystemPath>,
    directories: &mut SitePackagesPaths,
) {
    let PythonInterpreterLayout {
        version: Some(python_version),
        implementation,
        variant,
    } = layout
    else {
        return;
    };
    let settings_diagnostic_path = || settings_diagnostic_path.map(SystemPath::to_path_buf);

    // Try to insert the CPython-style package path into `directories`.
    // Returns `true` if a matching directory was found, so the caller can
    // decide whether to fall back to probing other implementations.
    let probe_cpython_path = |directories: &mut SitePackagesPaths| {
        let path = |variant: PythonBuildVariant| {
            prefix_dir.join(format!(
                "python{python_version}{variant}/{suffix}",
                variant = variant.suffix()
            ))
        };

        let path = match variant {
            PythonBuildVariant::Default | PythonBuildVariant::FreeThreaded => path(variant),
            PythonBuildVariant::Unknown => {
                // Preserve the existing regular-first fallback when the build flavor is unknown.
                let regular = path(PythonBuildVariant::Default);
                if system.is_directory(&regular) || !python_version.free_threaded_build_available()
                {
                    regular
                } else {
                    path(PythonBuildVariant::FreeThreaded)
                }
            }
        };

        if system.is_directory(&path) {
            directories.insert_with_settings_diagnostic_path(path, settings_diagnostic_path());
            true
        } else {
            false
        }
    };

    // Try to insert the PyPy-style package path into `directories`.
    // Returns `true` if a matching directory was found.
    let probe_pypy_path = |directories: &mut SitePackagesPaths| {
        let path = prefix_dir.join(format!("pypy{python_version}/{suffix}"));
        if system.is_directory(&path) {
            directories.insert_with_settings_diagnostic_path(path, settings_diagnostic_path());
            true
        } else {
            false
        }
    };

    match implementation {
        PythonImplementation::CPython | PythonImplementation::GraalPy => {
            probe_cpython_path(directories);
        }
        PythonImplementation::PyPy => {
            probe_pypy_path(directories);
        }
        PythonImplementation::Unknown => {
            if !probe_cpython_path(directories) {
                probe_pypy_path(directories);
            }
        }
    }
}

/// Discover package directories under `prefix_dir` when the Python version is unknown.
///
/// Scans `prefix_dir` for subdirectories matching `{python,pypy}3.X` and checks each
/// for the given `suffixes` (typically `site-packages` and `dist-packages`).
fn discover_package_dirs(
    prefix_dir: &SystemPath,
    suffixes: &(impl IntoIterator<Item = InstallationDir> + Clone),
    implementation: PythonImplementation,
    system: &dyn System,
    settings_diagnostic_path: Option<&SystemPath>,
    directories: &mut SitePackagesPaths,
) {
    let Ok(dir_iter) = system.read_directory(prefix_dir) else {
        return;
    };

    for entry_result in dir_iter {
        let Ok(entry) = entry_result else { continue };
        if !entry.file_type().is_directory() {
            continue;
        }
        let path = entry.into_path();
        let name = path.file_name().unwrap_or_else(|| {
            panic!(
                "File name should be non-null because path is guaranteed \
                to be a child of `{prefix_dir}`"
            )
        });

        let matches_implementation = match implementation {
            PythonImplementation::CPython | PythonImplementation::GraalPy => {
                name.starts_with("python3.")
            }
            PythonImplementation::PyPy => name.starts_with("pypy3."),
            PythonImplementation::Unknown => {
                name.starts_with("python3.") || name.starts_with("pypy3.")
            }
        };

        if matches_implementation {
            for suffix in suffixes.clone() {
                let candidate = path.join(suffix.as_str());
                if system.is_directory(&candidate) {
                    directories.insert_with_settings_diagnostic_path(
                        candidate,
                        settings_diagnostic_path.map(SystemPath::to_path_buf),
                    );
                }
            }
        }
    }
}

/// Attempt to retrieve the `site-packages` directories
/// associated with a given Python installation.
///
/// The location of the `site-packages` directories can vary according to the
/// interpreter layout represented by this installation.
fn site_packages_directories_from_sys_prefix(
    sys_prefix_path: &SysPrefixPath,
    layout: PythonInterpreterLayout,
    system: &dyn System,
) -> SitePackagesDiscoveryResult<SitePackagesPaths> {
    tracing::debug!(
        "Searching for site-packages directory in sys.prefix {}",
        sys_prefix_path.inner
    );

    if cfg!(target_os = "windows") {
        let site_packages = sys_prefix_path.join(r"Lib\site-packages");
        return system
            .is_directory(&site_packages)
            .then(|| SitePackagesPaths::from([site_packages]))
            .ok_or_else(|| {
                SitePackagesDiscoveryError::NoSitePackagesDirFound(
                    sys_prefix_path.to_owned(),
                    system.dyn_clone(),
                )
            });
    }

    // In the Python standard library's `site.py` module (used for finding `site-packages`
    // at runtime), we can find this in [the non-Windows branch]:
    //
    // ```py
    // libdirs = [sys.platlibdir]
    // if sys.platlibdir != "lib":
    //     libdirs.append("lib")
    // ```
    //
    // We generally only care about the `site-packages` directory insofar as it allows
    // us to discover Python source code that can be used for inferring type
    // information regarding third-party dependencies. In theory, therefore, that means
    // that we don't need to care about any possible `lib64/site-packages` directories,
    // since [the `sys`-module documentation] states that `sys.platlibdir` is *only* ever
    // used for C extensions, never for pure-Python modules. However, in practice,
    // some installers appear to do [some strange things on Fedora] that mean that `.py`
    // files *can* end up in `lib64/site-packages` in some edge cases. And we'll probably
    // need to start looking in `lib64/site-packages` directories in the future anyway, in
    // order to distinguish between "unresolved import" and "resolved to an opaque C
    // extension" in diagnostic messages.
    //
    // [the non-Windows branch]: https://github.com/python/cpython/blob/a8be8fc6c4682089be45a87bd5ee1f686040116c/Lib/site.py#L401-L410
    // [the `sys`-module documentation]: https://docs.python.org/3/library/sys.html#sys.platlibdir
    // [some strange things on Fedora]: https://github.com/astral-sh/ty/issues/1043

    let mut directories = SitePackagesPaths::default();
    let is_debian_system_prefix = sys_prefix_path.as_str() == "/usr";
    let settings_diagnostic_path =
        settings_diagnostic_path_from_sys_prefix(sys_prefix_path, system);

    // On Debian/Ubuntu with sys.prefix=/usr, pip-installed packages go to
    // /usr/local/lib/pythonX.Y/dist-packages and take priority over system
    // packages in /usr/lib (they appear earlier in sys.path at runtime).
    // Insert these first for correct precedence.
    // Only check /usr/local/lib (not lib64): Debian/Ubuntu pip installs
    // do not use /usr/local/lib64.
    if layout.version.is_some() {
        if is_debian_system_prefix {
            probe_package_dirs(
                SystemPath::new("/usr/local/lib"),
                InstallationDir::DistPackages,
                layout,
                system,
                settings_diagnostic_path.as_deref(),
                &mut directories,
            );
        }

        for lib_dir in UnixLibDir::iter() {
            let prefix = sys_prefix_path.join(lib_dir);
            for suffix in InstallationDir::iter() {
                probe_package_dirs(
                    &prefix,
                    suffix,
                    layout,
                    system,
                    settings_diagnostic_path.as_deref(),
                    &mut directories,
                );
            }
        }
    } else {
        if is_debian_system_prefix {
            discover_package_dirs(
                SystemPath::new("/usr/local/lib"),
                &[InstallationDir::DistPackages],
                layout.implementation,
                system,
                settings_diagnostic_path.as_deref(),
                &mut directories,
            );
        }

        for lib_dir in UnixLibDir::iter() {
            let prefix = sys_prefix_path.join(lib_dir);
            discover_package_dirs(
                &prefix,
                &InstallationDir::iter(),
                layout.implementation,
                system,
                settings_diagnostic_path.as_deref(),
                &mut directories,
            );
        }
    }

    // Debian/Ubuntu also uses `/usr/lib/python3/dist-packages/` (without minor version)
    // for packages that work across multiple Python versions.
    // See: https://wiki.debian.org/Python#Deviations_from_upstream
    if matches!(
        layout.implementation,
        PythonImplementation::CPython | PythonImplementation::Unknown
    ) {
        let debian_dist_packages = sys_prefix_path.join("lib/python3/dist-packages");
        if system.is_directory(&debian_dist_packages) {
            directories.insert_with_settings_diagnostic_path(
                debian_dist_packages,
                settings_diagnostic_path,
            );
        }
    }

    if directories.is_empty() {
        let any_lib_dir =
            UnixLibDir::iter().any(|lib_dir| system.is_directory(&sys_prefix_path.join(lib_dir)));
        if any_lib_dir {
            Err(SitePackagesDiscoveryError::NoSitePackagesDirFound(
                sys_prefix_path.to_owned(),
                system.dyn_clone(),
            ))
        } else {
            Err(SitePackagesDiscoveryError::CouldNotReadLibDirectory(
                sys_prefix_path.to_owned(),
                system.dyn_clone(),
            ))
        }
    } else {
        Ok(directories)
    }
}

/// Attempt to retrieve the real stdlib directory
/// associated with a given Python installation.
///
/// The location of the stdlib directory can vary according to the interpreter
/// layout represented by this installation.
fn real_stdlib_directory_from_sys_prefix(
    sys_prefix_path: &SysPrefixPath,
    layout: PythonInterpreterLayout,
    system: &dyn System,
) -> StdlibDiscoveryResult<SystemPathBuf> {
    tracing::debug!(
        "Searching for real stdlib directory in sys.prefix {}",
        sys_prefix_path.inner
    );

    if cfg!(target_os = "windows") {
        let stdlib = sys_prefix_path.join("Lib");
        return system.is_directory(&stdlib).then_some(stdlib).ok_or(
            StdlibDiscoveryError::NoStdlibFound(sys_prefix_path.to_owned(), system.dyn_clone()),
        );
    }

    // If we were able to figure out what Python version this installation is,
    // we should be able to avoid iterating through all items in the `lib/` directory:
    if let Some(expected_relative_path) = layout.relative_stdlib_path() {
        let expected_absolute_path = sys_prefix_path.join(expected_relative_path);
        if system.is_directory(&expected_absolute_path) {
            return Ok(expected_absolute_path);
        }

        // CPython free-threaded (3.13+) variant: pythonXYt
        if let Some(alternative_relative_path) = layout.free_threaded_stdlib_fallback_path() {
            let alternative_path = sys_prefix_path.join(alternative_relative_path);
            if system.is_directory(&alternative_path) {
                return Ok(alternative_path);
            }
        }
    }

    // Either we couldn't figure out the version before calling this function
    // (e.g., from a `pyvenv.cfg` file if this was a venv),
    // or we couldn't find a stdlib folder at the expected location given
    // the parsed version
    //
    // Note: the `python3.x` part of the stdlib path can't be computed from
    // the `--python-version` the user has passed, as they might be running Python 3.12 locally
    // even if they've requested that we type check their code "as if" they're running 3.8.
    for entry_result in system
        // must be `lib`, not `lib64`, for the stdlib
        .read_directory(&sys_prefix_path.join(UnixLibDir::Lib))
        .map_err(|io_err| {
            StdlibDiscoveryError::CouldNotReadLibDirectory(
                sys_prefix_path.to_owned(),
                io_err,
                system.dyn_clone(),
            )
        })?
    {
        let Ok(entry) = entry_result else {
            continue;
        };

        if !entry.file_type().is_directory() {
            continue;
        }

        let path = entry.into_path();

        let name = path.file_name().expect(
            "File name should be non-null because path is guaranteed to be a child of `lib`",
        );

        if !(name.starts_with("python3.") || name.starts_with("pypy3.")) {
            continue;
        }

        return Ok(path);
    }
    Err(StdlibDiscoveryError::NoStdlibFound(
        sys_prefix_path.to_owned(),
        system.dyn_clone(),
    ))
}

/// A path that represents the value of [`sys.prefix`] at runtime in Python
/// for a given Python executable.
///
/// For the case of a virtual environment, where a
/// Python binary is at `/.venv/bin/python`, `sys.prefix` is the path to
/// the virtual environment the Python binary lies inside, i.e. `/.venv`,
/// and `site-packages` will be at `.venv/lib/python3.X/site-packages`.
/// System Python installations generally work the same way: if a system
/// Python installation lies at `/opt/homebrew/bin/python`, `sys.prefix`
/// will be `/opt/homebrew`, and `site-packages` will be at
/// `/opt/homebrew/lib/python3.X/site-packages`.
///
/// [`sys.prefix`]: https://docs.python.org/3/library/sys.html#sys.prefix
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct SysPrefixPath {
    inner: SystemPathBuf,
    origin: SysPrefixPathOrigin,
}

fn sys_prefix_from_executable_path(path: &SystemPath) -> Option<&SystemPath> {
    if cfg!(windows) {
        // On Windows, the relative path to the executable from `sys.prefix` is different
        // depending on whether it's a virtual environment or a system installation.
        // System installations have their executable at `<sys.prefix>/python.exe`,
        // whereas virtual environments have their executable at `<sys.prefix>/Scripts/python.exe`.
        let parent = path.parent()?;
        if parent.file_name() == Some("Scripts") {
            parent.parent()
        } else {
            Some(parent)
        }
    } else {
        // On Unix, `sys.prefix` is always the grandparent directory of the Python executable,
        // regardless of whether it's a virtual environment or a system installation.
        path.ancestors().nth(2)
    }
}

/// A selected Python environment path resolved to its `sys.prefix`.
#[derive(Debug)]
enum PythonEnvironmentPath {
    Prefix(SysPrefixPath),
    Executable {
        path: SystemPathBuf,
        sys_prefix: SysPrefixPath,
        layout: Option<PythonInterpreterLayout>,
    },
}

impl PythonEnvironmentPath {
    fn new(
        unvalidated_path: &SystemPath,
        origin: SysPrefixPathOrigin,
        system: &dyn System,
    ) -> SitePackagesDiscoveryResult<Self> {
        let executable_path = (!origin.must_point_directly_to_sys_prefix()
            && system.is_file(unvalidated_path)
            && unvalidated_path.file_name().is_some_and(|name| {
                PythonImplementation::split_executable_name(name).is_some()
                    || name.eq_ignore_ascii_case(&format!("ty{}", std::env::consts::EXE_SUFFIX))
            }))
        .then_some(unvalidated_path);

        let unvalidated_sys_prefix = if let Some(executable_path) = executable_path {
            let Some(sys_prefix) = sys_prefix_from_executable_path(executable_path) else {
                return Err(SitePackagesDiscoveryError::PathNotExecutableOrDirectory(
                    unvalidated_path.to_path_buf(),
                    origin,
                    None,
                    system.dyn_clone(),
                ));
            };
            sys_prefix
        } else {
            unvalidated_path
        };

        // It's important to resolve symlinks here rather than simply making the path absolute,
        // since system Python installations often only put symlinks in the "expected"
        // locations for `home` and `site-packages`
        let sys_prefix = match system.canonicalize_path(unvalidated_sys_prefix) {
            Ok(path) => path,
            Err(io_err) => {
                let unvalidated_path = unvalidated_path.to_path_buf();
                let err = if io_err.kind() == io::ErrorKind::NotFound {
                    SitePackagesDiscoveryError::PathNotExecutableOrDirectory(
                        unvalidated_path,
                        origin,
                        Some(io_err),
                        system.dyn_clone(),
                    )
                } else {
                    SitePackagesDiscoveryError::CanonicalizationError(
                        unvalidated_path,
                        origin,
                        io_err,
                        system.dyn_clone(),
                    )
                };
                return Err(err);
            }
        };

        if !system.is_directory(&sys_prefix) {
            return Err(SitePackagesDiscoveryError::PathNotExecutableOrDirectory(
                unvalidated_path.to_path_buf(),
                origin,
                None,
                system.dyn_clone(),
            ));
        }

        let layout = executable_path.and_then(|executable_path| {
            let canonical_layout = system
                .canonicalize_path(executable_path)
                .ok()
                .and_then(|path| PythonInterpreterLayout::from_path(&path, system));

            // A complete layout from the symlink target describes the actual interpreter, while
            // the selected path may only be a facade. Keep its layout as a fallback when the
            // target name does not include a version.
            if let Some(layout) = canonical_layout
                && layout.version.is_some()
            {
                return Some(layout);
            }

            let direct_layout = PythonInterpreterLayout::from_path(executable_path, system);
            if let Some(layout) = direct_layout
                && layout.version.is_some()
            {
                return Some(layout);
            }

            canonical_layout.or(direct_layout)
        });

        let sys_prefix = SysPrefixPath {
            inner: sys_prefix,
            origin,
        };

        if let Some(executable_path) = executable_path {
            Ok(Self::Executable {
                path: executable_path.to_path_buf(),
                sys_prefix,
                layout,
            })
        } else {
            Ok(Self::Prefix(sys_prefix))
        }
    }

    fn sys_prefix(&self) -> &SysPrefixPath {
        match self {
            Self::Prefix(sys_prefix) | Self::Executable { sys_prefix, .. } => sys_prefix,
        }
    }

    fn origin(&self) -> &SysPrefixPathOrigin {
        &self.sys_prefix().origin
    }

    fn interpreter_layout(&self) -> Option<PythonInterpreterLayout> {
        match self {
            Self::Executable { layout, .. } => *layout,
            Self::Prefix(_) => None,
        }
    }

    fn selected_path(&self) -> &SystemPath {
        match self {
            Self::Prefix(sys_prefix) => sys_prefix,
            Self::Executable { path, .. } => path,
        }
    }
}

impl SysPrefixPath {
    fn from_executable_home_path(path: &PythonHomePath) -> Option<Self> {
        // No need to check whether `path.parent()` is a directory:
        // the parent of a canonicalised path that is known to exist
        // is guaranteed to be a directory.
        if cfg!(target_os = "windows") {
            Some(Self {
                inner: path.to_path_buf(),
                origin: SysPrefixPathOrigin::DerivedFromPyvenvCfg,
            })
        } else {
            path.parent().map(|path| Self {
                inner: path.to_path_buf(),
                origin: SysPrefixPathOrigin::DerivedFromPyvenvCfg,
            })
        }
    }
    /// Like `from_executable_home_path` but attempts to resolve through symlink facades
    /// to find a sys prefix that will actually contain the stdlib.
    fn from_executable_home_path_real(system: &dyn System, path: &PythonHomePath) -> Option<Self> {
        let mut home_path = path.0.clone();

        // Try to find the python executable in the given directory and canonicalize it
        // to resolve any symlink. This is (at least) necessary for homebrew pythons
        // and the macOS system python.
        //
        // In python installations like homebrew, the home path points to a directory like
        // `/opt/homebrew/opt/python@3.13/bin` and indeed if you look for `../lib/python3.13/`
        // you *will* find `site-packages` but you *won't* find the stdlib! (For the macOS
        // system install you won't even find `site-packages` here.)
        //
        // However if you look at `/opt/homebrew/opt/python@3.13/bin/python3.13` (the actual
        // python executable in that dir) you will find that it's a symlink to something like
        // `../Frameworks/Python.framework/Versions/3.13/bin/python3.13`
        //
        // From this Framework binary path if you go to `../../lib/python3.13/` you will then
        // find the python stdlib as expected (and a different instance of site-packages).
        //
        // FIXME: it would be nice to include a "we know the python name" fastpath like in
        // `real_stdlib_directory_from_sys_prefix`.
        if let Ok(dir) = system.read_directory(&home_path) {
            for entry_result in dir {
                let Ok(entry) = entry_result else {
                    continue;
                };

                if entry.file_type().is_directory() {
                    continue;
                }

                let path = entry.into_path();

                let name = path.file_name().expect(
                    "File name should be non-null \
                    because path is guaranteed to be a child of `lib`",
                );

                if !(name.starts_with("python3.") || name.starts_with("pypy3.")) {
                    continue;
                }

                let Ok(canonical_path) = system.canonicalize_path(&path) else {
                    continue;
                };

                let Some(parent) = canonical_path.parent() else {
                    continue;
                };

                home_path = parent.to_path_buf();
                break;
            }
        }

        // No need to check whether `path.parent()` is a directory:
        // the parent of a canonicalised path that is known to exist
        // is guaranteed to be a directory.
        if cfg!(target_os = "windows") {
            Some(Self {
                inner: home_path.to_path_buf(),
                origin: SysPrefixPathOrigin::DerivedFromPyvenvCfg,
            })
        } else {
            home_path.parent().map(|home_path| Self {
                inner: home_path.to_path_buf(),
                origin: SysPrefixPathOrigin::DerivedFromPyvenvCfg,
            })
        }
    }
}

impl Deref for SysPrefixPath {
    type Target = SystemPath;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

/// Enumeration of sources a `sys.prefix` path can come from.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum SysPrefixPathOrigin {
    /// The `sys.prefix` path came from a configuration file setting: `pyproject.toml` or `ty.toml`
    ConfigFileSetting(Arc<SystemPathBuf>, Option<TextRange>),
    /// The `sys.prefix` path came from a standalone script's inline metadata.
    ScriptMetadataSetting,
    /// The `sys.prefix` path came from a `--python` CLI flag
    PythonCliFlag,
    /// The selected interpreter in the user's editor.
    Editor,
    /// The `sys.prefix` path was provided by `uv workspace metadata`.
    UvWorkspace,
    /// The `sys.prefix` path came from the `VIRTUAL_ENV` environment variable
    VirtualEnvVar,
    /// The `sys.prefix` path came from the `CONDA_PREFIX` environment variable
    CondaPrefixVar,
    /// The `sys.prefix` path was derived from a value in a `pyvenv.cfg` file:
    /// either the value associated with the `home` key
    /// or the value associated with the `extends-environment` key
    DerivedFromPyvenvCfg,
    /// A `.venv` directory was found in the current working directory,
    /// and the `sys.prefix` path is the path to that virtual environment.
    LocalVenv,
    /// The `sys.prefix` path came from the environment ty is installed in.
    SelfEnvironment,
    /// The Python binary discovered in $PATH
    PythonBinary,
}

impl SysPrefixPathOrigin {
    /// Whether the given `sys.prefix` path must be a virtual environment (rather than a system
    /// Python environment).
    const fn must_be_virtual_env(&self) -> bool {
        match self {
            Self::LocalVenv | Self::VirtualEnvVar => true,
            Self::ConfigFileSetting(..)
            | Self::ScriptMetadataSetting
            | Self::PythonCliFlag
            | Self::Editor
            | Self::DerivedFromPyvenvCfg
            | Self::CondaPrefixVar
            | Self::PythonBinary
            | Self::UvWorkspace
            | Self::SelfEnvironment => false,
        }
    }

    /// Whether paths with this origin always point directly to the `sys.prefix` directory.
    ///
    /// Some variants can point either directly to `sys.prefix` or to a Python executable inside
    /// the `sys.prefix` directory, e.g. the `--python` CLI flag.
    const fn must_point_directly_to_sys_prefix(&self) -> bool {
        match self {
            Self::PythonCliFlag
            | Self::ConfigFileSetting(..)
            | Self::ScriptMetadataSetting
            | Self::Editor
            | Self::SelfEnvironment
            | Self::PythonBinary => false,
            Self::VirtualEnvVar
            | Self::CondaPrefixVar
            | Self::DerivedFromPyvenvCfg
            | Self::LocalVenv
            | Self::UvWorkspace => true,
        }
    }

    /// Whether paths with this origin should allow combination with paths with a
    /// [`SysPrefixPathOrigin::SelfEnvironment`] origin.
    pub const fn allows_concatenation_with_self_environment(&self) -> bool {
        match self {
            Self::SelfEnvironment
            | Self::CondaPrefixVar
            | Self::VirtualEnvVar
            | Self::Editor
            | Self::DerivedFromPyvenvCfg
            | Self::ConfigFileSetting(..)
            | Self::ScriptMetadataSetting
            | Self::PythonCliFlag
            | Self::PythonBinary
            | Self::UvWorkspace => false,
            Self::LocalVenv => true,
        }
    }
}

impl std::fmt::Display for SysPrefixPathOrigin {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::PythonCliFlag => f.write_str("`--python` argument"),
            Self::ConfigFileSetting(_, _) => f.write_str("`environment.python` setting"),
            Self::ScriptMetadataSetting => {
                f.write_str("`environment.python` setting in script metadata")
            }
            Self::VirtualEnvVar => f.write_str("`VIRTUAL_ENV` environment variable"),
            Self::CondaPrefixVar => f.write_str("`CONDA_PREFIX` environment variable"),
            Self::DerivedFromPyvenvCfg => f.write_str("derived `sys.prefix` path"),
            Self::LocalVenv => f.write_str("local virtual environment"),
            Self::Editor => f.write_str("selected interpreter in your editor"),
            Self::UvWorkspace => f.write_str("uv workspace environment"),
            Self::SelfEnvironment => f.write_str("ty environment"),
            Self::PythonBinary => f.write_str("Python binary discovered in $PATH"),
        }
    }
}

/// The value given by the `home` key in `pyvenv.cfg` files.
///
/// This is equivalent to `{sys_prefix_path}/bin`, and points
/// to a directory in which a Python executable can be found.
/// Confusingly, it is *not* the same as the [`PYTHONHOME`]
/// environment variable that Python provides! However, it's
/// consistent among all mainstream creators of Python virtual
/// environments (the stdlib Python `venv` module, the third-party
/// `virtualenv` library, and `uv`), was specified by
/// [the original PEP adding the `venv` module],
/// and it's one of the few fields that's read by the Python
/// standard library's `site.py` module.
///
/// Although it doesn't appear to be specified anywhere,
/// all existing virtual environment tools always use an absolute path
/// for the `home` value, and the Python standard library also assumes
/// that the `home` value will be an absolute path.
///
/// Other values, such as the path to the Python executable or the
/// base-executable `sys.prefix` value, are either only provided in
/// `pyvenv.cfg` files by some virtual-environment creators,
/// or are included under different keys depending on which
/// virtual-environment creation tool you've used.
///
/// [`PYTHONHOME`]: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHOME
/// [the original PEP adding the `venv` module]: https://peps.python.org/pep-0405/
#[derive(Debug, PartialEq, Eq)]
struct PythonHomePath(SystemPathBuf);

impl PythonHomePath {
    fn new(path: impl AsRef<SystemPath>, system: &dyn System) -> io::Result<Self> {
        let path = path.as_ref();
        // It's important to resolve symlinks here rather than simply making the path absolute,
        // since system Python installations often only put symlinks in the "expected"
        // locations for `home` and `site-packages`
        let canonicalized = system.canonicalize_path(path)?;
        system
            .is_directory(&canonicalized)
            .then_some(Self(canonicalized))
            .ok_or_else(|| io::Error::other("not a directory"))
    }
}

impl Deref for PythonHomePath {
    type Target = SystemPath;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl fmt::Display for PythonHomePath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "`home` location `{}`", self.0)
    }
}

impl PartialEq<SystemPath> for PythonHomePath {
    fn eq(&self, other: &SystemPath) -> bool {
        &*self.0 == other
    }
}

impl PartialEq<SystemPathBuf> for PythonHomePath {
    fn eq(&self, other: &SystemPathBuf) -> bool {
        self == &**other
    }
}

#[cfg(test)]
mod tests {
    use ruff_db::system::TestSystem;
    #[cfg(unix)]
    use ruff_db::system::{OsSystem, SystemPath};

    use super::*;

    impl PythonEnvironment {
        fn expect_venv(self) -> VirtualEnvironment {
            match self {
                Self::Virtual(venv) => venv,
                Self::System(_) => panic!("Expected a virtual environment"),
            }
        }
    }

    #[derive(Default)]
    struct VirtualEnvironmentTestCase {
        system_site_packages: bool,
        pyvenv_cfg_version_field: Option<&'static str>,
        command_field: Option<&'static str>,
        implementation_field: Option<&'static str>,
    }

    impl VirtualEnvironmentTestCase {
        fn implementation(&self) -> PythonImplementation {
            let Some((_, implementation)) = self
                .implementation_field
                .and_then(|field| field.split_once('='))
            else {
                return PythonImplementation::CPython;
            };

            match implementation.trim().to_ascii_lowercase().as_str() {
                "cpython" => PythonImplementation::CPython,
                "graalvm" => PythonImplementation::GraalPy,
                "pypy" => PythonImplementation::PyPy,
                _ => PythonImplementation::Unknown,
            }
        }
    }

    struct PythonEnvironmentTestCase {
        system: TestSystem,
        minor_version: u8,
        free_threaded: bool,
        origin: SysPrefixPathOrigin,
        virtual_env: Option<VirtualEnvironmentTestCase>,
    }

    impl PythonEnvironmentTestCase {
        /// Builds a mock environment, and returns the path to the environment root.
        fn build(&self) -> SystemPathBuf {
            let PythonEnvironmentTestCase {
                system,
                minor_version,
                free_threaded: _,
                origin: _,
                virtual_env,
            } = self;
            let memory_fs = system.memory_file_system();
            let unix_site_packages = self.unix_site_packages();

            let system_install_sys_prefix =
                SystemPathBuf::from(&*format!("/Python3.{minor_version}"));
            let (system_home_path, system_exe_path, system_site_packages_path) =
                if cfg!(target_os = "windows") {
                    let system_home_path = system_install_sys_prefix.clone();
                    let system_exe_path = system_home_path.join("python.exe");
                    let system_site_packages_path =
                        system_install_sys_prefix.join(r"Lib\site-packages");
                    (system_home_path, system_exe_path, system_site_packages_path)
                } else {
                    let system_home_path = system_install_sys_prefix.join("bin");
                    let system_exe_path = system_home_path.join("python");
                    let system_site_packages_path =
                        system_install_sys_prefix.join(&unix_site_packages);
                    (system_home_path, system_exe_path, system_site_packages_path)
                };
            memory_fs.write_file_all(system_exe_path, "").unwrap();
            memory_fs
                .create_directory_all(&system_site_packages_path)
                .unwrap();

            let Some(VirtualEnvironmentTestCase {
                pyvenv_cfg_version_field,
                system_site_packages,
                command_field,
                implementation_field,
            }) = virtual_env
            else {
                return system_install_sys_prefix;
            };

            let venv_sys_prefix = SystemPathBuf::from("/.venv");
            let (venv_exe, site_packages_path) = if cfg!(target_os = "windows") {
                (
                    venv_sys_prefix.join(r"Scripts\python.exe"),
                    venv_sys_prefix.join(r"Lib\site-packages"),
                )
            } else {
                (
                    venv_sys_prefix.join("bin/python"),
                    venv_sys_prefix.join(&unix_site_packages),
                )
            };
            memory_fs.write_file_all(&venv_exe, "").unwrap();
            memory_fs.create_directory_all(&site_packages_path).unwrap();

            let pyvenv_cfg_path = venv_sys_prefix.join("pyvenv.cfg");
            let mut pyvenv_cfg_contents = format!("home = {system_home_path}\n");
            if let Some(version_field) = pyvenv_cfg_version_field {
                pyvenv_cfg_contents.push_str(version_field);
                pyvenv_cfg_contents.push('\n');
            }
            if let Some(command_field) = command_field {
                pyvenv_cfg_contents.push_str(command_field);
                pyvenv_cfg_contents.push('\n');
            }
            if let Some(implementation_field) = implementation_field {
                pyvenv_cfg_contents.push_str(implementation_field);
                pyvenv_cfg_contents.push('\n');
            }

            // Deliberately using weird casing here to test that our pyvenv.cfg parsing is case-insensitive:
            if *system_site_packages {
                pyvenv_cfg_contents.push_str("include-system-site-packages = TRuE\n");
            }
            memory_fs
                .write_file_all(pyvenv_cfg_path, &pyvenv_cfg_contents)
                .unwrap();

            venv_sys_prefix
        }

        #[track_caller]
        fn err(self) -> SitePackagesDiscoveryError {
            PythonEnvironment::new(self.build(), self.origin, &self.system)
                .expect_err("Expected environment construction to fail")
        }

        #[track_caller]
        fn run(self) -> PythonEnvironment {
            let env_path = self.build();
            let env = PythonEnvironment::new(env_path.clone(), self.origin.clone(), &self.system)
                .expect("Expected environment construction to succeed");

            let expect_virtual_env = self.virtual_env.is_some();
            assert_eq!(env.sys_prefix().as_std_path(), env_path.as_std_path());
            match &env {
                PythonEnvironment::Virtual(venv) if expect_virtual_env => {
                    self.assert_virtual_environment(venv, &env_path);
                }
                PythonEnvironment::Virtual(venv) => {
                    panic!(
                        "Expected a system environment, but got a virtual environment: {venv:?}"
                    );
                }
                PythonEnvironment::System(env) if !expect_virtual_env => {
                    self.assert_system_environment(env, &env_path);
                }
                PythonEnvironment::System(env) => {
                    panic!("Expected a virtual environment, but got a system environment: {env:?}");
                }
            }
            env
        }

        #[track_caller]
        fn assert_virtual_environment(
            &self,
            venv: &VirtualEnvironment,
            expected_env_path: &SystemPathBuf,
        ) {
            let self_venv = self.virtual_env.as_ref().expect(
                "`assert_virtual_environment` should only be used when `virtual_env` is populated",
            );

            assert_eq!(
                venv.root_path,
                SysPrefixPath {
                    inner: self.system.canonicalize_path(expected_env_path).unwrap(),
                    origin: self.origin.clone(),
                }
            );
            assert_eq!(
                venv.include_system_site_packages,
                self_venv.system_site_packages
            );

            if self_venv.pyvenv_cfg_version_field.is_some() {
                assert_eq!(
                    venv.version.as_ref().map(|v| v.version),
                    Some(PythonVersion {
                        major: 3,
                        minor: self.minor_version
                    })
                );
            } else {
                assert_eq!(venv.version, None);
            }

            let expected_home = if cfg!(target_os = "windows") {
                SystemPathBuf::from(&*format!(r"\Python3.{}", self.minor_version))
            } else {
                SystemPathBuf::from(&*format!("/Python3.{}/bin", self.minor_version))
            };
            assert_eq!(
                venv.base_executable_home_path.as_deref(),
                Some(&*expected_home)
            );

            let site_packages_directories = venv.site_packages_directories(&self.system).unwrap();
            let expected_venv_site_packages = if cfg!(target_os = "windows") {
                SystemPathBuf::from(r"\.venv\Lib\site-packages")
            } else if matches!(
                self.virtual_env_implementation(),
                PythonImplementation::PyPy
            ) {
                SystemPathBuf::from(&*format!(
                    "/.venv/lib/pypy3.{}/site-packages",
                    self.minor_version
                ))
            } else if self.free_threaded {
                SystemPathBuf::from(&*format!(
                    "/.venv/lib/python3.{}t/site-packages",
                    self.minor_version
                ))
            } else {
                SystemPathBuf::from(&*format!(
                    "/.venv/lib/python3.{}/site-packages",
                    self.minor_version
                ))
            };

            let expected_system_site_packages = self.expected_system_site_packages();

            if self_venv.system_site_packages {
                assert_eq!(
                    site_packages_directories,
                    [expected_venv_site_packages, expected_system_site_packages].as_slice()
                );
            } else {
                assert_eq!(
                    &site_packages_directories.into_iter().next().unwrap(),
                    &expected_venv_site_packages
                );
            }

            let stdlib_directory = venv.real_stdlib_directory(&self.system).unwrap();
            let expected_stdlib_directory = self.expected_system_stdlib();
            assert_eq!(stdlib_directory, expected_stdlib_directory);
        }

        #[track_caller]
        fn assert_system_environment(
            &self,
            env: &SystemEnvironment,
            expected_env_path: &SystemPathBuf,
        ) {
            assert!(
                self.virtual_env.is_none(),
                "`assert_system_environment` should only be used \
                when `virtual_env` is not populated"
            );

            assert_eq!(
                env.path.sys_prefix(),
                &SysPrefixPath {
                    inner: self.system.canonicalize_path(expected_env_path).unwrap(),
                    origin: self.origin.clone(),
                }
            );

            let site_packages_directories = env.site_packages_directories(&self.system).unwrap();
            let expected_site_packages = self.expected_system_site_packages();
            assert_eq!(
                site_packages_directories,
                std::slice::from_ref(&expected_site_packages)
            );

            let stdlib_directory = env.real_stdlib_directory(&self.system).unwrap();
            let expected_stdlib_directory = self.expected_system_stdlib();
            assert_eq!(stdlib_directory, expected_stdlib_directory);
        }

        fn expected_system_site_packages(&self) -> SystemPathBuf {
            let minor_version = self.minor_version;
            if cfg!(target_os = "windows") {
                SystemPathBuf::from(&*format!(r"\Python3.{minor_version}\Lib\site-packages"))
            } else if matches!(
                self.virtual_env_implementation(),
                PythonImplementation::PyPy
            ) {
                SystemPathBuf::from(&*format!(
                    "/Python3.{minor_version}/lib/pypy3.{minor_version}/site-packages"
                ))
            } else if self.free_threaded {
                SystemPathBuf::from(&*format!(
                    "/Python3.{minor_version}/lib/python3.{minor_version}t/site-packages"
                ))
            } else {
                SystemPathBuf::from(&*format!(
                    "/Python3.{minor_version}/lib/python3.{minor_version}/site-packages"
                ))
            }
        }

        fn expected_system_stdlib(&self) -> SystemPathBuf {
            let minor_version = self.minor_version;
            if cfg!(target_os = "windows") {
                SystemPathBuf::from(&*format!(r"\Python3.{minor_version}\Lib"))
            } else if matches!(
                self.virtual_env_implementation(),
                PythonImplementation::PyPy
            ) {
                SystemPathBuf::from(&*format!(
                    "/Python3.{minor_version}/lib/pypy3.{minor_version}"
                ))
            } else if self.free_threaded {
                SystemPathBuf::from(&*format!(
                    "/Python3.{minor_version}/lib/python3.{minor_version}t"
                ))
            } else {
                SystemPathBuf::from(&*format!(
                    "/Python3.{minor_version}/lib/python3.{minor_version}"
                ))
            }
        }

        fn unix_site_packages(&self) -> String {
            let minor_version = self.minor_version;

            match self.virtual_env_implementation() {
                PythonImplementation::PyPy => format!("lib/pypy3.{minor_version}/site-packages"),
                PythonImplementation::CPython
                | PythonImplementation::GraalPy
                | PythonImplementation::Unknown => {
                    if self.free_threaded {
                        format!("lib/python3.{minor_version}t/site-packages")
                    } else {
                        format!("lib/python3.{minor_version}/site-packages")
                    }
                }
            }
        }

        fn virtual_env_implementation(&self) -> PythonImplementation {
            self.virtual_env
                .as_ref()
                .map(VirtualEnvironmentTestCase::implementation)
                .unwrap_or(PythonImplementation::CPython)
        }
    }

    #[test]
    fn can_find_site_packages_directory_no_virtual_env() {
        // Shouldn't be converted to an mdtest because mdtest automatically creates a
        // pyvenv.cfg file for you if it sees you creating a `site-packages` directory.
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 12,
            free_threaded: false,
            origin: SysPrefixPathOrigin::PythonCliFlag,
            virtual_env: None,
        };
        test.run();
    }

    #[test]
    fn can_find_site_packages_directory_no_virtual_env_at_origin_uv_workspace() {
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 12,
            free_threaded: false,
            origin: SysPrefixPathOrigin::UvWorkspace,
            virtual_env: None,
        };
        test.run();
    }

    #[test]
    fn can_find_site_packages_directory_no_virtual_env_freethreaded() {
        // Shouldn't be converted to an mdtest because mdtest automatically creates a
        // pyvenv.cfg file for you if it sees you creating a `site-packages` directory.
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: true,
            origin: SysPrefixPathOrigin::PythonCliFlag,
            virtual_env: None,
        };
        test.run();
    }

    #[test]
    fn cannot_find_site_packages_directory_no_virtual_env_at_origin_virtual_env_var() {
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: false,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: None,
        };
        let err = test.err();
        assert!(
            matches!(err, SitePackagesDiscoveryError::NoPyvenvCfgFile(..)),
            "Got {err:?}",
        );
    }

    #[test]
    fn cannot_find_site_packages_directory_no_virtual_env_at_origin_local_venv() {
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: false,
            origin: SysPrefixPathOrigin::LocalVenv,
            virtual_env: None,
        };
        let err = test.err();
        assert!(
            matches!(err, SitePackagesDiscoveryError::NoPyvenvCfgFile(..)),
            "Got {err:?}",
        );
    }

    #[test]
    fn can_find_site_packages_directory_no_virtual_env_at_origin_self_environment() {
        // Test that ty can discover dependencies in a system Python environment
        // that it's installed into (issue #2068).
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: false,
            origin: SysPrefixPathOrigin::SelfEnvironment,
            virtual_env: None,
        };
        test.run();
    }

    #[test]
    fn can_find_site_packages_directory_venv_style_version_field_in_pyvenv_cfg() {
        // Shouldn't be converted to an mdtest because we want to assert
        // that we parsed the `version` field correctly in `test.run()`.
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 12,
            free_threaded: false,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase {
                pyvenv_cfg_version_field: Some("version = 3.12"),
                ..VirtualEnvironmentTestCase::default()
            }),
        };
        test.run();
    }

    #[test]
    fn can_find_site_packages_directory_uv_style_version_field_in_pyvenv_cfg() {
        // Shouldn't be converted to an mdtest because we want to assert
        // that we parsed the `version` field correctly in `test.run()`.
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 12,
            free_threaded: false,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase {
                pyvenv_cfg_version_field: Some("version_info = 3.12"),
                ..VirtualEnvironmentTestCase::default()
            }),
        };
        test.run();
    }

    #[test]
    fn can_find_site_packages_directory_virtualenv_style_version_field_in_pyvenv_cfg() {
        // Shouldn't be converted to an mdtest because we want to assert
        // that we parsed the `version` field correctly in `test.run()`.
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 12,
            free_threaded: false,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase {
                pyvenv_cfg_version_field: Some("version_info = 3.12.0rc2"),
                ..VirtualEnvironmentTestCase::default()
            }),
        };
        test.run();
    }

    #[test]
    fn can_find_site_packages_directory_freethreaded_build() {
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: true,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase {
                pyvenv_cfg_version_field: Some("version_info = 3.13"),
                ..VirtualEnvironmentTestCase::default()
            }),
        };
        test.run();
    }

    #[test]
    fn finds_system_site_packages() {
        // Can't be converted to an mdtest because the system installation's `sys.prefix`
        // path is at a different location relative to the `pyvenv.cfg` file's `home` value
        // on Windows.
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: true,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase {
                system_site_packages: true,
                pyvenv_cfg_version_field: Some("version_info = 3.13"),
                ..VirtualEnvironmentTestCase::default()
            }),
        };
        test.run();
    }

    #[test]
    fn detects_pypy_implementation() {
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: true,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase {
                implementation_field: Some("implementation = PyPy"),
                ..VirtualEnvironmentTestCase::default()
            }),
        };
        let venv = test.run().expect_venv();
        assert_eq!(venv.implementation, PythonImplementation::PyPy);
    }

    #[test]
    fn detects_cpython_implementation() {
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: true,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase {
                implementation_field: Some("implementation = CPython"),
                ..VirtualEnvironmentTestCase::default()
            }),
        };
        let venv = test.run().expect_venv();
        assert_eq!(venv.implementation, PythonImplementation::CPython);
    }

    #[test]
    fn detects_graalpy_implementation() {
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: true,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase {
                implementation_field: Some("implementation = GraalVM"),
                ..VirtualEnvironmentTestCase::default()
            }),
        };
        let venv = test.run().expect_venv();
        assert_eq!(venv.implementation, PythonImplementation::GraalPy);
    }

    #[test]
    fn detects_unknown_implementation() {
        let test = PythonEnvironmentTestCase {
            system: TestSystem::default(),
            minor_version: 13,
            free_threaded: true,
            origin: SysPrefixPathOrigin::VirtualEnvVar,
            virtual_env: Some(VirtualEnvironmentTestCase::default()),
        };
        let venv = test.run().expect_venv();
        assert_eq!(venv.implementation, PythonImplementation::Unknown);
    }

    #[test]
    fn reject_env_that_does_not_exist() {
        let system = TestSystem::default();
        assert!(matches!(
            PythonEnvironment::new("/env", SysPrefixPathOrigin::PythonCliFlag, &system),
            Err(SitePackagesDiscoveryError::PathNotExecutableOrDirectory(..))
        ));
    }

    #[test]
    fn reject_env_that_is_not_a_directory() {
        let system = TestSystem::default();
        system
            .memory_file_system()
            .write_file_all("/env", "")
            .unwrap();
        assert!(matches!(
            PythonEnvironment::new("/env", SysPrefixPathOrigin::PythonCliFlag, &system),
            Err(SitePackagesDiscoveryError::PathNotExecutableOrDirectory(..))
        ));
    }

    #[test]
    fn cannot_read_lib_directory() {
        let system = TestSystem::default();
        system
            .memory_file_system()
            .create_directory_all("/env")
            .unwrap();
        // Environment creation succeeds, but site-packages retrieval fails reading the `lib`
        // directory
        let env =
            PythonEnvironment::new("/env", SysPrefixPathOrigin::PythonCliFlag, &system).unwrap();
        let site_packages = env.site_packages_paths(&system);
        if cfg!(unix) {
            assert!(
                matches!(
                    site_packages,
                    Err(SitePackagesDiscoveryError::CouldNotReadLibDirectory(..)),
                ),
                "Got {site_packages:?}",
            );
        } else {
            // On Windows, we look for `Lib/site-packages` directly instead of listing the entries
            // of `lib/...` — so we don't see the intermediate failure
            assert!(
                matches!(
                    site_packages,
                    Err(SitePackagesDiscoveryError::NoSitePackagesDirFound(..)),
                ),
                "Got {site_packages:?}",
            );
        }
    }

    #[test]
    fn cannot_find_site_packages_directory() {
        let system = TestSystem::default();
        if cfg!(unix) {
            system
                .memory_file_system()
                .create_directory_all("/env/lib")
                .unwrap();
        } else {
            system
                .memory_file_system()
                .create_directory_all("/env/Lib")
                .unwrap();
        }
        // Environment creation succeeds, but site-packages retrieval fails
        let env =
            PythonEnvironment::new("/env", SysPrefixPathOrigin::PythonCliFlag, &system).unwrap();
        let site_packages = env.site_packages_paths(&system);
        assert!(
            matches!(
                site_packages,
                Err(SitePackagesDiscoveryError::NoSitePackagesDirFound(..)),
            ),
            "Got {site_packages:?}",
        );
    }

    #[test]
    fn parsing_pyvenv_cfg_with_key_but_no_value_fails() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();
        let pyvenv_cfg_path = SystemPathBuf::from("/.venv/pyvenv.cfg");
        memory_fs
            .write_file_all(&pyvenv_cfg_path, "home =")
            .unwrap();
        let venv_result =
            PythonEnvironment::new("/.venv", SysPrefixPathOrigin::VirtualEnvVar, &system);
        assert!(matches!(
            venv_result,
            Err(SitePackagesDiscoveryError::PyvenvCfgParseError(
                path,
                PyvenvCfgParseErrorKind::MalformedKeyValuePair { line_number }
            ))
            if path == pyvenv_cfg_path && Some(line_number) == NonZeroUsize::new(1)
        ));
    }

    #[test]
    fn parsing_pyvenv_cfg_with_value_but_no_key_fails() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();
        let pyvenv_cfg_path = SystemPathBuf::from("/.venv/pyvenv.cfg");
        memory_fs
            .write_file_all(&pyvenv_cfg_path, "= whatever")
            .unwrap();
        let venv_result =
            PythonEnvironment::new("/.venv", SysPrefixPathOrigin::VirtualEnvVar, &system);
        assert!(matches!(
            venv_result,
            Err(SitePackagesDiscoveryError::PyvenvCfgParseError(
                path,
                PyvenvCfgParseErrorKind::MalformedKeyValuePair { line_number }
            ))
            if path == pyvenv_cfg_path && Some(line_number) == NonZeroUsize::new(1)
        ));
    }

    #[test]
    fn parsing_pyvenv_cfg_with_no_home_key_fails() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();
        let pyvenv_cfg_path = SystemPathBuf::from("/.venv/pyvenv.cfg");
        memory_fs.write_file_all(&pyvenv_cfg_path, "").unwrap();
        let venv_result =
            PythonEnvironment::new("/.venv", SysPrefixPathOrigin::VirtualEnvVar, &system);
        assert!(matches!(
            venv_result,
            Err(SitePackagesDiscoveryError::PyvenvCfgParseError(
                path,
                PyvenvCfgParseErrorKind::NoHomeKey
            ))
            if path == pyvenv_cfg_path
        ));
    }

    #[test]
    fn unresolved_pyvenv_cfg_home_is_nonfatal_without_system_site_packages() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();
        let pyvenv_cfg_path = SystemPathBuf::from("/.venv/pyvenv.cfg");
        memory_fs
            .write_file_all(&pyvenv_cfg_path, "home = foo")
            .unwrap();
        let site_packages = if cfg!(target_os = "windows") {
            SystemPathBuf::from(r"\.venv\Lib\site-packages")
        } else {
            SystemPathBuf::from("/.venv/lib/python3.13/site-packages")
        };
        memory_fs.create_directory_all(&site_packages).unwrap();

        let venv = PythonEnvironment::new("/.venv", SysPrefixPathOrigin::VirtualEnvVar, &system)
            .unwrap()
            .expect_venv();

        assert_eq!(venv.base_executable_home_path, None);
        let expected = [site_packages];
        assert_eq!(
            venv.site_packages_directories(&system).unwrap(),
            &expected[..]
        );
    }

    #[test]
    fn unresolved_pyvenv_cfg_home_with_system_site_packages_fails() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();
        let pyvenv_cfg_path = SystemPathBuf::from("/.venv/pyvenv.cfg");
        memory_fs
            .write_file_all(
                &pyvenv_cfg_path,
                "home = foo\ninclude-system-site-packages = true",
            )
            .unwrap();

        let venv_result =
            PythonEnvironment::new("/.venv", SysPrefixPathOrigin::VirtualEnvVar, &system);

        assert!(matches!(
            venv_result,
            Err(SitePackagesDiscoveryError::PyvenvCfgParseError(
                path,
                PyvenvCfgParseErrorKind::InvalidHomeValue(_)
            ))
            if path == pyvenv_cfg_path
        ));
    }

    #[test]
    fn pyvenv_cfg_with_carriage_return_line_endings_parses() {
        let pyvenv_cfg = "home = /somewhere/python\r\nversion_info = 3.13\r\nimplementation = PyPy";
        let parsed = PyvenvCfgParser::new(pyvenv_cfg).parse().unwrap();
        assert_eq!(parsed.base_executable_home_path, Some("/somewhere/python"));
        let version = parsed.version.unwrap();
        assert_eq!(version.0, "3.13");
        assert_eq!(&pyvenv_cfg[version.1], version.0);
        assert_eq!(parsed.implementation, PythonImplementation::PyPy);
    }

    #[test]
    fn pyvenv_cfg_with_strange_whitespace_parses() {
        let pyvenv_cfg = "  home= /a path with whitespace/python\t   \t  \nversion_info =    3.13 \
            \n\n\n\nimplementation    =PyPy";
        let parsed = PyvenvCfgParser::new(pyvenv_cfg).parse().unwrap();
        assert_eq!(
            parsed.base_executable_home_path,
            Some("/a path with whitespace/python")
        );
        let version = parsed.version.unwrap();
        assert_eq!(version.0, "3.13");
        assert_eq!(&pyvenv_cfg[version.1], version.0);
        assert_eq!(parsed.implementation, PythonImplementation::PyPy);
    }

    #[test]
    fn site_packages_paths_display() {
        let paths = SitePackagesPaths::default();
        assert_eq!(paths.to_string(), "[]");

        let mut paths = SitePackagesPaths::default();
        paths.insert_with_settings_diagnostic_path(
            SystemPathBuf::from("/path/to/site/packages"),
            None,
        );

        assert_eq!(paths.to_string(), r#"["/path/to/site/packages"]"#);
    }

    #[test]
    #[cfg(not(target_os = "windows"))]
    fn layout_inference_uses_the_primary_site_packages_source() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let self_site_packages = SystemPathBuf::from("/self/.venv/lib/python3.16/site-packages");
        let project_site_packages =
            SystemPathBuf::from("/project/.venv/lib/python3.12/site-packages");
        let self_pyvenv_cfg = SystemPathBuf::from("/self/.venv/pyvenv.cfg");
        let project_pyvenv_cfg = SystemPathBuf::from("/project/.venv/pyvenv.cfg");

        memory_fs.create_directory_all(&self_site_packages).unwrap();
        memory_fs
            .create_directory_all(&project_site_packages)
            .unwrap();
        memory_fs
            .write_file_all(&self_pyvenv_cfg, "home = /python/bin")
            .unwrap();
        memory_fs
            .write_file_all(&project_pyvenv_cfg, "home = /python/bin")
            .unwrap();

        let mut paths = SitePackagesPaths::default();
        paths.insert_with_settings_diagnostic_path(
            self_site_packages,
            Some(self_pyvenv_cfg.clone()),
        );
        paths.insert_with_settings_diagnostic_path(project_site_packages, Some(project_pyvenv_cfg));
        let PythonVersionWithSource { version, source } =
            paths.python_version_from_layout().unwrap();

        assert_eq!(version, PythonVersion::from((3, 16)));
        assert_eq!(
            source,
            PythonVersionSource::InstallationDirectoryLayout {
                site_packages_parent_dir: Box::from("python3.16"),
                source: Some(PythonVersionFileSource::new(
                    Arc::new(self_pyvenv_cfg),
                    None
                )),
            }
        );
    }

    #[test]
    #[cfg(not(target_os = "windows"))]
    fn settings_diagnostic_path_ignores_python_helper_scripts() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/python");
        let bin_dir = sys_prefix.join("bin");
        let config_helper = bin_dir.join("python3.16-config");
        let interpreter = bin_dir.join("python3.16");
        let windowed_interpreter = bin_dir.join("pythonw");

        memory_fs.create_directory_all(&bin_dir).unwrap();
        memory_fs.write_file_all(&config_helper, "").unwrap();
        memory_fs.write_file_all(&interpreter, "").unwrap();
        memory_fs.write_file_all(&windowed_interpreter, "").unwrap();

        assert_eq!(
            settings_diagnostic_path_from_sys_prefix(&sys_prefix, &system),
            Some(interpreter)
        );
    }

    /// Test that dist-packages directories (Debian/Ubuntu) are discovered alongside site-packages
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn finds_dist_packages_in_system_environment() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        // Create a system Python installation with both site-packages and dist-packages
        let sys_prefix = SystemPathBuf::from("/usr");
        let site_packages = sys_prefix.join("lib/python3.12/site-packages");
        let dist_packages = sys_prefix.join("lib/python3.12/dist-packages");

        memory_fs.create_directory_all(&site_packages).unwrap();
        memory_fs.create_directory_all(&dist_packages).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::CPython,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter().any(|p| p.as_str().ends_with("site-packages")),
            "Expected to find site-packages, got: {dirs:?}"
        );
        assert!(
            dirs.iter().any(|p| p.as_str().ends_with("dist-packages")),
            "Expected to find dist-packages, got: {dirs:?}"
        );
    }

    /// Test that Debian's version-agnostic dist-packages directory is discovered
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn finds_debian_python3_dist_packages() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        // Create a Debian-style system Python installation
        // Debian uses /usr/lib/python3/dist-packages for packages that work across versions
        let sys_prefix = SystemPathBuf::from("/usr");
        let site_packages = sys_prefix.join("lib/python3.12/site-packages");
        let debian_dist_packages = sys_prefix.join("lib/python3/dist-packages");

        memory_fs.create_directory_all(&site_packages).unwrap();
        memory_fs
            .create_directory_all(&debian_dist_packages)
            .unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::CPython,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str().contains("python3/dist-packages")),
            "Expected to find Debian's python3/dist-packages, got: {dirs:?}"
        );
    }

    /// Test that the `PyPy` layout is probed directly when both the implementation and version are
    /// known, without falling back to the sibling CPython layout.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn finds_pypy_site_packages_when_version_known() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/env");
        let pypy_site_packages = sys_prefix.join("lib/pypy3.12/site-packages");
        let cpython_site_packages = sys_prefix.join("lib/python3.12/site-packages");

        memory_fs.create_directory_all(&pypy_site_packages).unwrap();
        memory_fs
            .create_directory_all(&cpython_site_packages)
            .unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::PyPy,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/env/lib/pypy3.12/site-packages"),
            "Expected to find /env/lib/pypy3.12/site-packages, got: {dirs:?}"
        );
        assert!(
            dirs.iter()
                .all(|p| p.as_str() != "/env/lib/python3.12/site-packages"),
            "Should NOT find CPython site-packages when implementation=PyPy, got: {dirs:?}"
        );
    }

    /// Test that /usr/local/lib/pythonX.Y/dist-packages is discovered when sys.prefix=/usr
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn finds_usr_local_dist_packages_in_system_environment() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/usr");
        let site_packages = sys_prefix.join("lib/python3.12/site-packages");
        let usr_local_dist_packages =
            SystemPathBuf::from("/usr/local/lib/python3.12/dist-packages");

        memory_fs.create_directory_all(&site_packages).unwrap();
        memory_fs
            .create_directory_all(&usr_local_dist_packages)
            .unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::CPython,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/usr/local/lib/python3.12/dist-packages"),
            "Expected to find /usr/local/lib/python3.12/dist-packages, got: {dirs:?}"
        );
    }

    /// Test that /usr/local/lib/pythonX.Y/dist-packages appears before
    /// /usr/lib/pythonX.Y/dist-packages, matching the runtime sys.path precedence
    /// where pip-installed packages take priority over apt-installed packages.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn usr_local_dist_packages_precedes_sys_prefix_dist_packages() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/usr");
        let usr_lib_dist = sys_prefix.join("lib/python3.12/dist-packages");
        let usr_local_dist = SystemPathBuf::from("/usr/local/lib/python3.12/dist-packages");

        memory_fs.create_directory_all(&usr_lib_dist).unwrap();
        memory_fs.create_directory_all(&usr_local_dist).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::CPython,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        let local_pos = dirs
            .iter()
            .position(|p| p.as_str() == "/usr/local/lib/python3.12/dist-packages")
            .expect("/usr/local/lib/python3.12/dist-packages should be found");
        let sys_pos = dirs
            .iter()
            .position(|p| p.as_str() == "/usr/lib/python3.12/dist-packages")
            .expect("/usr/lib/python3.12/dist-packages should be found");
        assert!(
            local_pos < sys_pos,
            "/usr/local should precede /usr/lib for correct precedence, got: {dirs:?}"
        );
    }

    /// Test that /usr/local/lib paths are NOT added when sys.prefix != "/usr"
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn does_not_add_usr_local_when_sys_prefix_is_not_usr() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        // Simulate a pyenv-style installation (sys.prefix != "/usr")
        let sys_prefix = SystemPathBuf::from("/home/user/.pyenv/versions/3.12.0");
        let site_packages = sys_prefix.join("lib/python3.12/site-packages");
        // Also create a /usr/local path to ensure it isn't picked up
        let usr_local_dist = SystemPathBuf::from("/usr/local/lib/python3.12/dist-packages");

        memory_fs.create_directory_all(&site_packages).unwrap();
        memory_fs.create_directory_all(&usr_local_dist).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::CPython,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter().all(|p| !p.as_str().starts_with("/usr/local")),
            "Expected no /usr/local paths when sys.prefix != /usr, got: {dirs:?}"
        );
    }

    /// Test that dist-packages are found during fallback enumeration (when version is unknown
    /// and Debian's python3/dist-packages does not exist)
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn finds_dist_packages_in_fallback_enumeration() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        // Create a system Python installation without the Debian-specific python3/dist-packages
        // This forces the fallback enumeration to run
        let sys_prefix = SystemPathBuf::from("/usr");
        let site_packages = sys_prefix.join("lib/python3.11/site-packages");
        let dist_packages = sys_prefix.join("lib/python3.11/dist-packages");

        memory_fs.create_directory_all(&site_packages).unwrap();
        memory_fs.create_directory_all(&dist_packages).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        // Use Unknown implementation to trigger fallback enumeration
        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(PythonImplementation::Unknown, None),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter().any(|p| p.as_str().ends_with("site-packages")),
            "Expected to find site-packages in fallback, got: {dirs:?}"
        );
        assert!(
            dirs.iter()
                .any(|p| p.as_str().contains("python3.11/dist-packages")),
            "Expected to find version-specific dist-packages in fallback, got: {dirs:?}"
        );
    }

    /// Test that Debian's python3/dist-packages is found during fallback enumeration
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn finds_debian_dist_packages_in_fallback_enumeration() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        // Create a system Python installation with Debian's python3/dist-packages
        let sys_prefix = SystemPathBuf::from("/usr");
        let site_packages = sys_prefix.join("lib/python3.11/site-packages");
        let debian_dist_packages = sys_prefix.join("lib/python3/dist-packages");

        memory_fs.create_directory_all(&site_packages).unwrap();
        memory_fs
            .create_directory_all(&debian_dist_packages)
            .unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        // Use Unknown implementation to trigger fallback enumeration
        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(PythonImplementation::Unknown, None),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        // The Debian-specific check runs first and finds python3/dist-packages
        assert!(
            dirs.iter()
                .any(|p| p.as_str().contains("python3/dist-packages")),
            "Expected to find Debian's python3/dist-packages, got: {dirs:?}"
        );
    }

    /// Test that /usr/local/lib/pythonX.Y/dist-packages is found during fallback enumeration
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn finds_usr_local_dist_packages_in_fallback_enumeration() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/usr");
        // Only create the /usr/local path; no /usr/lib dirs so phase 1 finds nothing
        let usr_local_dist_packages =
            SystemPathBuf::from("/usr/local/lib/python3.12/dist-packages");
        memory_fs
            .create_directory_all(&usr_local_dist_packages)
            .unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(PythonImplementation::Unknown, None),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/usr/local/lib/python3.12/dist-packages"),
            "Expected to find /usr/local/lib/python3.12/dist-packages in fallback, got: {dirs:?}"
        );
    }

    /// Test that when the implementation is known to be CPython, fallback enumeration does not
    /// discover `PyPy` package directories even if they exist alongside the CPython layout.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn fallback_enumeration_for_cpython_excludes_pypy_directories() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/env");
        let cpython_site_packages = sys_prefix.join("lib/python3.11/site-packages");
        let pypy_site_packages = sys_prefix.join("lib/pypy3.11/site-packages");

        memory_fs
            .create_directory_all(&cpython_site_packages)
            .unwrap();
        memory_fs.create_directory_all(&pypy_site_packages).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(PythonImplementation::CPython, None),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/env/lib/python3.11/site-packages"),
            "Expected to find /env/lib/python3.11/site-packages, got: {dirs:?}"
        );
        assert!(
            dirs.iter()
                .all(|p| p.as_str() != "/env/lib/pypy3.11/site-packages"),
            "Should NOT find PyPy site-packages when implementation=CPython, got: {dirs:?}"
        );
    }

    /// Test that when the implementation is known to be `PyPy`, fallback enumeration does not
    /// discover CPython package directories even if they exist alongside the `PyPy` layout.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn fallback_enumeration_for_pypy_excludes_cpython_directories() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/env");
        let pypy_site_packages = sys_prefix.join("lib/pypy3.11/site-packages");
        let cpython_site_packages = sys_prefix.join("lib/python3.11/site-packages");

        memory_fs.create_directory_all(&pypy_site_packages).unwrap();
        memory_fs
            .create_directory_all(&cpython_site_packages)
            .unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(PythonImplementation::PyPy, None),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/env/lib/pypy3.11/site-packages"),
            "Expected to find /env/lib/pypy3.11/site-packages, got: {dirs:?}"
        );
        assert!(
            dirs.iter()
                .all(|p| p.as_str() != "/env/lib/python3.11/site-packages"),
            "Should NOT find CPython site-packages when implementation=PyPy, got: {dirs:?}"
        );
    }

    /// Test that /usr/local/lib is NOT enumerated when version+implementation are both known,
    /// preventing packages from a different Python version from being included.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn does_not_enumerate_usr_local_for_wrong_version_when_version_known() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/usr");
        // Create the correct version's path AND a wrong version's path under /usr/local
        let correct = SystemPathBuf::from("/usr/local/lib/python3.12/dist-packages");
        let wrong = SystemPathBuf::from("/usr/local/lib/python3.11/dist-packages");

        memory_fs.create_directory_all(&correct).unwrap();
        memory_fs.create_directory_all(&wrong).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::CPython,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/usr/local/lib/python3.12/dist-packages"),
            "Expected to find /usr/local/lib/python3.12/dist-packages, got: {dirs:?}"
        );
        assert!(
            dirs.iter()
                .all(|p| p.as_str() != "/usr/local/lib/python3.11/dist-packages"),
            "Should NOT find python3.11 packages when version=3.12 is known, got: {dirs:?}"
        );
    }

    /// Test that when version is known but implementation is Unknown, probing /usr/local/lib
    /// still excludes wrong-version directories.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn does_not_include_wrong_version_when_implementation_unknown() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/usr");
        let correct = SystemPathBuf::from("/usr/local/lib/python3.12/dist-packages");
        let wrong = SystemPathBuf::from("/usr/local/lib/python3.11/dist-packages");

        memory_fs.create_directory_all(&correct).unwrap();
        memory_fs.create_directory_all(&wrong).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::Unknown,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/usr/local/lib/python3.12/dist-packages"),
            "Expected to find /usr/local/lib/python3.12/dist-packages, got: {dirs:?}"
        );
        assert!(
            dirs.iter()
                .all(|p| p.as_str() != "/usr/local/lib/python3.11/dist-packages"),
            "Should NOT find python3.11 packages when version=3.12 is known, got: {dirs:?}"
        );
    }

    /// Test that when the version is known but the implementation is Unknown, CPython-style
    /// paths are preferred over PyPy-style paths if both layouts exist.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn unknown_known_version_prefers_cpython_layout() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/env");
        let cpython_site_packages = sys_prefix.join("lib/python3.12/site-packages");
        let pypy_site_packages = sys_prefix.join("lib/pypy3.12/site-packages");

        memory_fs
            .create_directory_all(&cpython_site_packages)
            .unwrap();
        memory_fs.create_directory_all(&pypy_site_packages).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::Unknown,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert_eq!(
            dirs,
            vec![SystemPathBuf::from("/env/lib/python3.12/site-packages")]
        );
    }

    /// Test that when the version is known but the implementation is Unknown, we can still
    /// discover a matching-version `PyPy` site-packages directory without widening to a
    /// wrong-version CPython directory.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn includes_matching_version_pypy_without_wrong_version_cpython_when_unknown() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/env");
        let correct = sys_prefix.join("lib/pypy3.12/site-packages");
        let wrong = sys_prefix.join("lib/python3.11/site-packages");

        memory_fs.create_directory_all(&correct).unwrap();
        memory_fs.create_directory_all(&wrong).unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::Unknown,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/env/lib/pypy3.12/site-packages"),
            "Expected to find /env/lib/pypy3.12/site-packages, got: {dirs:?}"
        );
        assert!(
            dirs.iter()
                .all(|p| p.as_str() != "/env/lib/python3.11/site-packages"),
            "Should NOT find python3.11 packages when version=3.12 is known, got: {dirs:?}"
        );
    }

    /// Test that when the version is known, finding the matching site-packages directory does not
    /// cause exact-path probing for dist-packages to widen to a wrong-version directory.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn does_not_include_wrong_version_dist_packages_when_exact_dist_missing() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();

        let sys_prefix = SystemPathBuf::from("/env");
        let site_packages = sys_prefix.join("lib/python3.12/site-packages");
        let wrong_dist_packages = sys_prefix.join("lib/python3.11/dist-packages");

        memory_fs.create_directory_all(&site_packages).unwrap();
        memory_fs
            .create_directory_all(&wrong_dist_packages)
            .unwrap();

        let sys_prefix_path = SysPrefixPath {
            inner: sys_prefix,
            origin: SysPrefixPathOrigin::PythonCliFlag,
        };

        let directories = site_packages_directories_from_sys_prefix(
            &sys_prefix_path,
            PythonInterpreterLayout::unknown(
                PythonImplementation::CPython,
                Some(PythonVersion {
                    major: 3,
                    minor: 12,
                }),
            ),
            &system,
        )
        .unwrap();

        let dirs: Vec<_> = directories.into_iter().collect();
        assert!(
            dirs.iter()
                .any(|p| p.as_str() == "/env/lib/python3.12/site-packages"),
            "Expected to find /env/lib/python3.12/site-packages, got: {dirs:?}"
        );
        assert!(
            dirs.iter()
                .all(|p| p.as_str() != "/env/lib/python3.11/dist-packages"),
            "Should NOT find python3.11 dist-packages when version=3.12 is known, got: {dirs:?}"
        );
    }

    /// Regression test for <https://github.com/astral-sh/ty/issues/3424>.
    #[cfg(not(windows))]
    #[test]
    fn uses_selected_system_interpreter_layout() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();
        let sys_prefix = SystemPathBuf::from("/opt");

        memory_fs
            .create_directory_all(sys_prefix.join("lib/python3.13/site-packages"))
            .unwrap();

        let layouts = [
            (
                "python3.14",
                "lib/python3.14/site-packages",
                "lib/python3.14",
            ),
            (
                "python3.14t",
                "lib/python3.14t/site-packages",
                "lib/python3.14t",
            ),
            ("pypy3.14", "lib/pypy3.14/site-packages", "lib/pypy3.14"),
            (
                "graalpy3.14",
                "lib/python3.14/site-packages",
                "lib/python3.14",
            ),
        ];

        for (executable, site_packages, _) in layouts {
            memory_fs
                .write_file_all(sys_prefix.join("bin").join(executable), "")
                .unwrap();
            memory_fs
                .create_directory_all(sys_prefix.join(site_packages))
                .unwrap();
        }

        for (executable, site_packages, stdlib) in layouts {
            let environment = PythonEnvironment::new(
                sys_prefix.join("bin").join(executable),
                SysPrefixPathOrigin::PythonCliFlag,
                &system,
            )
            .unwrap();

            assert_eq!(
                environment.site_packages_paths(&system).unwrap().into_vec(),
                [sys_prefix.join(site_packages)]
            );
            assert_eq!(
                environment.real_stdlib_path(&system).unwrap(),
                sys_prefix.join(stdlib)
            );
        }
    }

    #[cfg(not(windows))]
    #[test]
    fn recognizes_unversioned_graalpy_executable() {
        let system = TestSystem::default();
        let memory_fs = system.memory_file_system();
        let sys_prefix = SystemPathBuf::from("/graal");

        memory_fs
            .write_file_all(sys_prefix.join("bin/graalpy"), "")
            .unwrap();
        memory_fs
            .create_directory_all(sys_prefix.join("lib/python3.14/site-packages"))
            .unwrap();

        let environment = PythonEnvironment::new(
            sys_prefix.join("bin/graalpy"),
            SysPrefixPathOrigin::PythonCliFlag,
            &system,
        )
        .unwrap();

        assert_eq!(
            environment.site_packages_paths(&system).unwrap().into_vec(),
            [sys_prefix.join("lib/python3.14/site-packages")]
        );
    }

    #[cfg(unix)]
    #[test]
    fn distinguishes_unsuffixed_default_from_free_threaded_executable() {
        let temp_dir = tempfile::tempdir().unwrap();
        let root = SystemPath::from_std_path(temp_dir.path()).unwrap();
        let system = OsSystem::new(root);

        let prefix = root.join("prefix");
        let bin = prefix.join("bin");
        let versioned_executable = bin.join("python3.14");
        let site_packages = prefix.join("lib/python3.14/site-packages");

        std::fs::create_dir_all(bin.as_std_path()).unwrap();
        std::fs::File::create(versioned_executable.as_std_path()).unwrap();
        std::fs::File::create(bin.join("python3.14t").as_std_path()).unwrap();
        std::fs::create_dir_all(site_packages.as_std_path()).unwrap();
        std::fs::create_dir_all(prefix.join("lib/python3.14t/site-packages").as_std_path())
            .unwrap();

        let environment = PythonEnvironment::new(
            &versioned_executable,
            SysPrefixPathOrigin::PythonCliFlag,
            &system,
        )
        .unwrap();

        assert_eq!(
            environment.site_packages_paths(&system).unwrap().into_vec(),
            [system.canonicalize_path(&site_packages).unwrap()]
        );
    }

    #[cfg(unix)]
    #[test]
    fn identifies_free_threaded_hard_links() {
        let temp_dir = tempfile::tempdir().unwrap();
        let root = SystemPath::from_std_path(temp_dir.path()).unwrap();
        let system = OsSystem::new(root);

        for executable_name in ["python3.14t", "python3.14td"] {
            let prefix = root.join(executable_name);
            let bin = prefix.join("bin");
            let versioned_executable = bin.join("python3.14");
            let free_threaded_executable = bin.join(executable_name);
            let free_threaded_site_packages = prefix.join("lib/python3.14t/site-packages");

            std::fs::create_dir_all(bin.as_std_path()).unwrap();
            std::fs::File::create(free_threaded_executable.as_std_path()).unwrap();
            std::fs::hard_link(
                free_threaded_executable.as_std_path(),
                versioned_executable.as_std_path(),
            )
            .unwrap();
            std::fs::create_dir_all(prefix.join("lib/python3.14/site-packages").as_std_path())
                .unwrap();
            std::fs::create_dir_all(free_threaded_site_packages.as_std_path()).unwrap();

            for executable in [&versioned_executable, &free_threaded_executable] {
                let environment =
                    PythonEnvironment::new(executable, SysPrefixPathOrigin::PythonCliFlag, &system)
                        .unwrap();

                assert_eq!(
                    environment.site_packages_paths(&system).unwrap().into_vec(),
                    [system
                        .canonicalize_path(&free_threaded_site_packages)
                        .unwrap()]
                );
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn uses_symlink_target_layout() {
        let temp_dir = tempfile::tempdir().unwrap();
        let root = SystemPath::from_std_path(temp_dir.path()).unwrap();
        let system = OsSystem::new(root);

        let prefix = root.join("prefix");
        let bin = prefix.join("bin");
        std::fs::create_dir_all(bin.as_std_path()).unwrap();
        std::fs::File::create(bin.join("python3.14").as_std_path()).unwrap();
        std::os::unix::fs::symlink("python3.14", bin.join("python").as_std_path()).unwrap();

        let path = PythonEnvironmentPath::new(
            &bin.join("python"),
            SysPrefixPathOrigin::PythonCliFlag,
            &system,
        )
        .unwrap();

        assert_eq!(
            path.interpreter_layout(),
            Some(PythonInterpreterLayout {
                version: Some(PythonVersion::PY314),
                implementation: PythonImplementation::CPython,
                variant: PythonBuildVariant::Default,
            })
        );

        let other_prefix = root.join("other");
        let other_bin = other_prefix.join("bin");
        std::fs::create_dir_all(other_bin.as_std_path()).unwrap();
        std::fs::File::create(other_bin.join("python3.14").as_std_path()).unwrap();

        let facade_prefix = root.join("facade");
        let facade_bin = facade_prefix.join("bin");
        let python313_site_packages = facade_prefix.join("lib/python3.13/site-packages");
        let python314_site_packages = facade_prefix.join("lib/python3.14/site-packages");
        std::fs::create_dir_all(facade_bin.as_std_path()).unwrap();
        std::fs::create_dir_all(python313_site_packages.as_std_path()).unwrap();
        std::fs::create_dir_all(python314_site_packages.as_std_path()).unwrap();
        for executable_name in ["python", "python3.13"] {
            std::os::unix::fs::symlink(
                other_bin.join("python3.14").as_std_path(),
                facade_bin.join(executable_name).as_std_path(),
            )
            .unwrap();

            let executable = facade_bin.join(executable_name);
            assert_eq!(
                PythonEnvironmentPath::new(
                    &executable,
                    SysPrefixPathOrigin::PythonCliFlag,
                    &system,
                )
                .unwrap()
                .interpreter_layout(),
                Some(PythonInterpreterLayout {
                    version: Some(PythonVersion::PY314),
                    implementation: PythonImplementation::CPython,
                    variant: PythonBuildVariant::Default,
                })
            );

            let environment =
                PythonEnvironment::new(&executable, SysPrefixPathOrigin::PythonCliFlag, &system)
                    .unwrap();
            assert_eq!(
                environment.site_packages_paths(&system).unwrap().into_vec(),
                [system.canonicalize_path(&python314_site_packages).unwrap()]
            );
        }
    }
}