worktrunk 0.50.0

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

// Snapshot helpers

fn snapshot_switch(test_name: &str, repo: &TestRepo, args: &[&str]) {
    snapshot_switch_impl(test_name, repo, args, false, None, None);
}

fn snapshot_switch_with_directive_file(test_name: &str, repo: &TestRepo, args: &[&str]) {
    snapshot_switch_impl(test_name, repo, args, true, None, None);
}

fn snapshot_switch_from_dir(test_name: &str, repo: &TestRepo, args: &[&str], cwd: &Path) {
    snapshot_switch_impl(test_name, repo, args, false, Some(cwd), None);
}

#[cfg(not(windows))]
fn snapshot_switch_with_shell(test_name: &str, repo: &TestRepo, args: &[&str], shell: &str) {
    snapshot_switch_impl(test_name, repo, args, false, None, Some(shell));
}

fn snapshot_switch_impl(
    test_name: &str,
    repo: &TestRepo,
    args: &[&str],
    with_directive_file: bool,
    cwd: Option<&Path>,
    shell: Option<&str>,
) {
    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        // Directive file guards - declared at closure scope to live through command execution
        let maybe_directive = if with_directive_file {
            Some(directive_files())
        } else {
            None
        };

        let mut cmd = make_snapshot_cmd(repo, "switch", args, cwd);
        if let Some((ref cd_path, ref exec_path, ref _guard)) = maybe_directive {
            configure_directive_files(&mut cmd, cd_path, exec_path);
        }
        if let Some(shell_path) = shell {
            cmd.env("SHELL", shell_path);
        }
        assert_cmd_snapshot!(test_name, cmd);
    });
}
// Basic switch tests
#[rstest]
fn test_switch_create_new_branch(repo: TestRepo) {
    snapshot_switch("switch_create_new", &repo, &["--create", "feature-x"]);
}

/// Test that delayed streaming shows progress message when threshold is 0.
/// This exercises the streaming code path that normally only triggers for slow operations.
#[rstest]
fn test_switch_create_shows_progress_when_forced(repo: TestRepo) {
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "feature-progress"], None);
        // Force immediate streaming by setting threshold to 0
        cmd.env("WORKTRUNK_TEST_DELAYED_STREAM_MS", "0");
        assert_cmd_snapshot!("switch_create_with_progress", cmd);
    });
}

#[rstest]
fn test_switch_create_existing_branch_error(mut repo: TestRepo) {
    // Create a branch first
    repo.add_worktree("feature-y");

    // Try to create it again - should error
    snapshot_switch(
        "switch_create_existing_error",
        &repo,
        &["--create", "feature-y"],
    );
}

/// When --execute is passed and the branch already exists, the error hint should
/// include --execute and trailing args in the suggested command.
#[rstest]
fn test_switch_create_existing_with_execute(mut repo: TestRepo) {
    repo.add_worktree("emails");

    snapshot_switch(
        "switch_create_existing_with_execute",
        &repo,
        &[
            "--create",
            "--execute=claude",
            "emails",
            "--",
            "Check my emails",
        ],
    );
}

/// When --execute is passed and the branch doesn't exist (without --create),
/// the "create" suggestion should include --execute and trailing args.
#[rstest]
fn test_switch_nonexistent_with_execute(repo: TestRepo) {
    snapshot_switch(
        "switch_nonexistent_with_execute",
        &repo,
        &["--execute=claude", "nonexistent", "--", "Check my emails"],
    );
}

#[rstest]
fn test_switch_create_with_remote_branch_only(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a branch on the remote only (no local branch)
    repo.run_git(&["branch", "remote-feature"]);
    repo.run_git(&["push", "origin", "remote-feature"]);

    // Delete the local branch
    repo.run_git(&["branch", "-D", "remote-feature"]);

    // Now we have origin/remote-feature but no local remote-feature
    // This should succeed with --create (previously would fail)
    snapshot_switch(
        "switch_create_remote_only",
        &repo,
        &["--create", "remote-feature"],
    );
}

/// Git's DWIM creates local tracking branch from remote when no local branch exists.
/// Should report "Created branch X (tracking remote)" since DWIM actually created the branch.
#[rstest]
fn test_switch_dwim_from_remote(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a branch on the remote only (no local branch)
    repo.run_git(&["branch", "dwim-feature"]);
    repo.run_git(&["push", "origin", "dwim-feature"]);
    repo.run_git(&["branch", "-D", "dwim-feature"]);

    // Now we have origin/dwim-feature but no local dwim-feature
    // DWIM should create local branch from remote
    snapshot_switch("switch_dwim_from_remote", &repo, &["dwim-feature"]);
}

/// When the branch argument includes the remote prefix (e.g., "origin/feature"),
/// strip the prefix and switch to the local branch via DWIM.
/// This happens when the interactive picker returns a remote branch name.
#[rstest]
fn test_switch_remote_prefix_stripped(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a branch on the remote only (no local branch)
    repo.run_git(&["branch", "remote-feature"]);
    repo.run_git(&["push", "origin", "remote-feature"]);
    repo.run_git(&["branch", "-D", "remote-feature"]);

    // Passing "origin/remote-feature" should strip the prefix and DWIM to local branch
    snapshot_switch(
        "switch_remote_prefix_stripped",
        &repo,
        &["origin/remote-feature"],
    );
}

/// When the branch name contains slashes (e.g., "username/feature-1") and the picker
/// returns it with the remote prefix ("origin/username/feature-1"), the remote prefix
/// should be stripped correctly. Regression test for #1260.
#[rstest]
fn test_switch_remote_prefix_stripped_slash_in_branch(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a branch with / in the name on the remote only
    repo.run_git(&["branch", "username/feature-1"]);
    repo.run_git(&["push", "origin", "username/feature-1"]);
    repo.run_git(&["branch", "-D", "username/feature-1"]);

    // Passing "origin/username/feature-1" should strip "origin/" and DWIM correctly
    snapshot_switch(
        "switch_remote_prefix_slash_branch",
        &repo,
        &["origin/username/feature-1"],
    );
}

/// When a branch exists on multiple remotes, DWIM should fail with an error
/// since git can't determine which remote to track.
#[rstest]
fn test_switch_dwim_ambiguous_remotes(#[from(repo_with_remote)] mut repo: TestRepo) {
    // Add a second remote
    repo.setup_custom_remote("upstream", "main");

    // Create a branch on both remotes (no local branch)
    repo.run_git(&["branch", "shared-feature"]);
    repo.run_git(&["push", "origin", "shared-feature"]);
    repo.run_git(&["push", "upstream", "shared-feature"]);
    repo.run_git(&["branch", "-D", "shared-feature"]);

    // Now shared-feature exists on origin and upstream but not locally
    // DWIM can't pick — git worktree add should error
    snapshot_switch("switch_dwim_ambiguous_remotes", &repo, &["shared-feature"]);
}

/// `--base <branch>` should accept a branch that exists only as a remote-tracking ref
/// (e.g., `origin/releases/4.x.x`) when the user passes the bare name. Without this,
/// `wt switch -c new --base releases/4.x.x` fails the pre-validation in
/// `resolve_switch_target` even though `git worktree add` would have DWIM'd it.
/// Regression test for GitHub issue #2410.
#[rstest]
fn test_switch_create_with_remote_only_base(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a branch with slashes/dots on the remote only (matches the issue repro).
    repo.run_git(&["branch", "releases/4.x.x"]);
    repo.run_git(&["push", "origin", "releases/4.x.x"]);
    repo.run_git(&["branch", "-D", "releases/4.x.x"]);

    let output = repo
        .wt_command()
        .args(["switch", "--create", "new-wt", "--base", "releases/4.x.x"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "switch should succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // The new branch must exist and must NOT track the remote base
    // (same safety property as test_switch_create_from_remote_base_no_upstream).
    let branch_output = repo.git_output(&["branch", "--list", "new-wt"]);
    assert!(branch_output.contains("new-wt"), "branch should be created");

    let upstream_check = repo
        .git_command()
        .args(["rev-parse", "--abbrev-ref", "new-wt@{upstream}"])
        .run()
        .unwrap();
    assert!(
        !upstream_check.status.success(),
        "new branch should NOT track origin/releases/4.x.x"
    );
}

/// When creating a new branch from a remote tracking branch (e.g., origin/main),
/// the new branch should NOT track the remote base branch.
/// This prevents accidental `git push` to the base branch (e.g., pushing to main).
/// This is the bug fix for GitHub issue #713.
#[rstest]
fn test_switch_create_from_remote_base_no_upstream(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a new branch with --base pointing to a remote tracking branch
    let output = repo
        .wt_command()
        .args(["switch", "--create", "my-feature", "--base=origin/main"])
        .output()
        .unwrap();
    assert!(output.status.success(), "switch should succeed");

    // Verify the branch was created
    let branch_output = repo.git_output(&["branch", "--list", "my-feature"]);
    assert!(
        branch_output.contains("my-feature"),
        "branch should be created"
    );

    // Verify the branch does NOT have an upstream (no tracking)
    // Using rev-parse to check for upstream - should fail for untracked branches
    let upstream_check = repo
        .git_command()
        .args(["rev-parse", "--abbrev-ref", "my-feature@{upstream}"])
        .run()
        .unwrap();

    assert!(
        !upstream_check.status.success(),
        "branch should NOT have upstream tracking (to prevent accidental push to origin/main)"
    );
}

/// When local branch already exists and tracks a remote, should report
/// "Created worktree for X" NOT "Created branch X (tracking remote)".
/// This is the bug fix for GitHub issue #656.
#[rstest]
fn test_switch_existing_local_branch_with_upstream(#[from(repo_with_remote)] repo: TestRepo) {
    // Create local branch tracking remote
    repo.run_git(&["checkout", "-b", "tracked-feature"]);
    repo.run_git(&["commit", "--allow-empty", "-m", "feature commit"]);
    repo.run_git(&["push", "-u", "origin", "tracked-feature"]);
    repo.run_git(&["checkout", "main"]);

    // Switch to the existing local branch (should NOT say "Created branch")
    snapshot_switch(
        "switch_existing_local_with_upstream",
        &repo,
        &["tracked-feature"],
    );
}

#[rstest]
fn test_switch_existing_branch(mut repo: TestRepo) {
    repo.add_worktree("feature-z");

    // Switch to it (should find existing worktree)
    snapshot_switch("switch_existing_branch", &repo, &["feature-z"]);
}

///
/// When shell integration is configured in user's rc files (e.g., .zshrc) but the user
/// runs `wt` binary directly (not through the shell wrapper), show a warning that explains
/// the actual situation: shell IS configured, but cd can't happen because we're not
/// running through the shell function.
///
/// Since tests run via `cargo test`, argv[0] contains a path (`target/debug/wt`), which
/// triggers the "explicit path" code path. The warning explains that shell integration
/// won't intercept explicit paths.
///
/// Skipped on Windows: the binary is `wt.exe` so a different (more targeted) warning is
/// shown ("use wt without .exe"). Windows-specific behavior is tested in unit tests.
#[rstest]
#[cfg(not(windows))]
fn test_switch_existing_with_shell_integration_configured(mut repo: TestRepo) {
    use std::fs;

    // Create a worktree first
    repo.add_worktree("shell-configured");

    // Simulate shell integration configured in user's shell rc files
    // (repo.home_path() is automatically set as HOME by configure_wt_cmd)
    let zshrc_path = repo.home_path().join(".zshrc");
    fs::write(
        &zshrc_path,
        "# Existing user zsh config\nif command -v wt >/dev/null 2>&1; then eval \"$(command wt config shell init zsh)\"; fi\n",
    )
    .unwrap();

    // Switch to existing worktree - should show warning about binary invoked directly
    // (different from "no shell integration" warning when shell is not configured at all)
    // Note: Must set SHELL=/bin/zsh so scan_shell_configs() looks for .zshrc
    snapshot_switch_with_shell(
        "switch_existing_with_shell_configured",
        &repo,
        &["shell-configured"],
        "/bin/zsh",
    );
}

///
/// When git runs a subcommand, it sets `GIT_EXEC_PATH` in the environment.
/// Shell integration cannot work in this case because cd directives cannot
/// propagate through git's subprocess to the parent shell.
#[rstest]
fn test_switch_existing_as_git_subcommand(mut repo: TestRepo) {
    // Create a worktree first
    repo.add_worktree("git-subcommand-test");

    // Switch with GIT_EXEC_PATH set (simulating `git wt switch ...`)
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["git-subcommand-test"], None);
        cmd.env("GIT_EXEC_PATH", "/usr/lib/git-core");
        assert_cmd_snapshot!("switch_as_git_subcommand", cmd);
    });
}

#[rstest]
fn test_switch_with_base_branch(repo: TestRepo) {
    repo.commit("Initial commit on main");

    snapshot_switch(
        "switch_with_base",
        &repo,
        &["--create", "--base", "main", "feature-with-base"],
    );
}

#[rstest]
fn test_switch_base_without_create_warning(repo: TestRepo) {
    snapshot_switch(
        "switch_base_without_create",
        &repo,
        &["--base", "main", "main"],
    );
}

#[rstest]
fn test_switch_create_with_invalid_base(repo: TestRepo) {
    // Issues #562, #977: Error message should identify the invalid base branch,
    // not the target branch being created
    snapshot_switch(
        "switch_create_invalid_base",
        &repo,
        &["--create", "new-feature", "--base", "nonexistent-base"],
    );
}

#[rstest]
fn test_switch_nonexistent_branch(repo: TestRepo) {
    // Switching to a nonexistent branch (without --create) should give a clear
    // "branch not found" error, not fall through to a confusing git error.
    snapshot_switch("switch_nonexistent_branch", &repo, &["nonexistent-branch"]);
}

#[rstest]
fn test_switch_nonexistent_branch_with_fetch_time(repo: TestRepo) {
    // When FETCH_HEAD exists, the hint should include "last fetched X ago".
    let git_dir = repo.root_path().join(".git");
    fs::write(git_dir.join("FETCH_HEAD"), "").unwrap();

    // Set TEST_EPOCH to 3 hours after the real mtime so the file appears "3h ago"
    let mtime = fs::metadata(git_dir.join("FETCH_HEAD"))
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let epoch_3h_later = mtime + 3 * 3600;

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["nonexistent-branch"], None);
        cmd.env("WORKTRUNK_TEST_EPOCH", epoch_3h_later.to_string());
        assert_cmd_snapshot!("switch_nonexistent_with_fetch_time", cmd);
    });
}

#[rstest]
fn test_switch_base_accepts_commitish(repo: TestRepo) {
    // Issue #630: --base should accept any commit-ish, not just branch names
    // Test HEAD as base (common use case: branch from current HEAD)
    repo.commit("Initial commit on main");
    snapshot_switch(
        "switch_base_commitish_head",
        &repo,
        &["--create", "feature-from-head", "--base", "HEAD"],
    );
}

// Internal mode tests
#[rstest]
fn test_switch_internal_mode(repo: TestRepo) {
    snapshot_switch_with_directive_file(
        "switch_internal_mode",
        &repo,
        &["--create", "internal-test"],
    );
}

#[rstest]
fn test_switch_existing_worktree_internal(mut repo: TestRepo) {
    repo.add_worktree("existing-wt");

    snapshot_switch_with_directive_file("switch_existing_internal", &repo, &["existing-wt"]);
}

#[rstest]
fn test_switch_internal_with_execute(repo: TestRepo) {
    let execute_cmd = "echo 'line1'\necho 'line2'";

    snapshot_switch_with_directive_file(
        "switch_internal_with_execute",
        &repo,
        &["--create", "exec-internal", "--execute", execute_cmd],
    );
}
// Error tests
#[rstest]
fn test_switch_error_missing_worktree_directory(mut repo: TestRepo) {
    let wt_path = repo.add_worktree("missing-wt");

    // Remove the worktree directory (but leave it registered in git)
    std::fs::remove_dir_all(&wt_path).unwrap();

    // Try to switch to the missing worktree (should fail)
    snapshot_switch("switch_error_missing_directory", &repo, &["missing-wt"]);
}

/// Test error when target path is registered to a worktree whose directory is missing.
///
/// Scenario: branch "feature/collision" has a worktree at "repo.feature-collision",
/// but the directory was deleted. Trying to create "feature-collision" (which maps
/// to the same path) should error about the missing worktree, not try to overwrite.
#[rstest]
fn test_switch_error_path_occupied_by_missing_worktree(mut repo: TestRepo) {
    // Create a worktree for "feature/collision" -> path "repo.feature-collision"
    let wt_path = repo.add_worktree("feature/collision");

    // Delete the worktree directory (but leave it registered in git)
    std::fs::remove_dir_all(&wt_path).unwrap();

    // Try to create "feature-collision" which maps to the same path
    // Should fail because the path is registered to a missing worktree
    snapshot_switch(
        "switch_error_path_occupied_missing",
        &repo,
        &["--create", "feature-collision"],
    );
}

#[rstest]
fn test_switch_error_path_occupied(repo: TestRepo) {
    // Calculate where the worktree would be created
    // Default path pattern is {repo_name}.{branch}
    let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
    let expected_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{}.occupied-branch", repo_name));

    // Create a non-worktree directory at that path
    std::fs::create_dir_all(&expected_path).unwrap();
    std::fs::write(expected_path.join("some_file.txt"), "occupant content").unwrap();

    // Try to create a worktree with a branch that would use that path
    // Should fail with worktree_path_occupied error
    snapshot_switch(
        "switch_error_path_occupied",
        &repo,
        &["--create", "occupied-branch"],
    );

    // Cleanup
    std::fs::remove_dir_all(&expected_path).ok();
}
// Execute flag tests
#[rstest]
fn test_switch_execute_success(repo: TestRepo) {
    snapshot_switch(
        "switch_execute_success",
        &repo,
        &["--create", "exec-test", "--execute", "echo 'test output'"],
    );
}

#[rstest]
fn test_switch_execute_creates_file(repo: TestRepo) {
    let create_file_cmd = "echo 'test content' > test.txt";

    snapshot_switch(
        "switch_execute_creates_file",
        &repo,
        &["--create", "file-test", "--execute", create_file_cmd],
    );
}

#[rstest]
fn test_switch_execute_failure(repo: TestRepo) {
    snapshot_switch(
        "switch_execute_failure",
        &repo,
        &["--create", "fail-test", "--execute", "exit 1"],
    );
}

#[rstest]
fn test_switch_execute_with_existing_worktree(mut repo: TestRepo) {
    repo.add_worktree("existing-exec");

    let create_file_cmd = "echo 'existing worktree' > existing.txt";

    snapshot_switch(
        "switch_execute_existing",
        &repo,
        &["existing-exec", "--execute", create_file_cmd],
    );
}

#[rstest]
fn test_switch_execute_multiline(repo: TestRepo) {
    let multiline_cmd = "echo 'line1'\necho 'line2'\necho 'line3'";

    snapshot_switch(
        "switch_execute_multiline",
        &repo,
        &["--create", "multiline-test", "--execute", multiline_cmd],
    );
}

// Execute template expansion tests
#[rstest]
fn test_switch_execute_template_branch(repo: TestRepo) {
    // Test that {{ branch }} is expanded in --execute command
    snapshot_switch(
        "switch_execute_template_branch",
        &repo,
        &[
            "--create",
            "template-test",
            "--execute",
            "echo 'branch={{ branch }}'",
        ],
    );
}

#[rstest]
fn test_switch_execute_template_base(repo: TestRepo) {
    // Test that {{ base }} is available when creating with --create
    snapshot_switch(
        "switch_execute_template_base",
        &repo,
        &[
            "--create",
            "from-main",
            "--base",
            "main",
            "--execute",
            "echo 'base={{ base }}'",
        ],
    );
}

#[rstest]
fn test_switch_execute_template_base_without_create(mut repo: TestRepo) {
    // Test that {{ base }} errors when switching to existing worktree (no --create)
    // The `base` variable is only available during branch creation
    repo.add_worktree("existing");
    snapshot_switch(
        "switch_execute_template_base_without_create",
        &repo,
        &["existing", "--execute", "echo 'base={{ base }}'"],
    );
}

#[rstest]
fn test_switch_execute_template_with_filter(repo: TestRepo) {
    // Test that filters work ({{ branch | sanitize }})
    snapshot_switch(
        "switch_execute_template_with_filter",
        &repo,
        &[
            "--create",
            "feature/with-slash",
            "--execute",
            "echo 'sanitized={{ branch | sanitize }}'",
        ],
    );
}

#[rstest]
fn test_switch_execute_template_shell_escape(repo: TestRepo) {
    // Test that shell metacharacters in branch names are escaped
    // Without escaping, this would execute `id` as a separate command
    snapshot_switch(
        "switch_execute_template_shell_escape",
        &repo,
        &["--create", "feat;id", "--execute", "echo {{ branch }}"],
    );
}

#[rstest]
fn test_switch_execute_template_worktree_path(repo: TestRepo) {
    // Test that {{ worktree_path }} is expanded
    snapshot_switch(
        "switch_execute_template_worktree_path",
        &repo,
        &[
            "--create",
            "path-test",
            "--execute",
            "echo 'path={{ worktree_path }}'",
        ],
    );
}

#[rstest]
fn test_switch_execute_template_in_args(repo: TestRepo) {
    // Test that templates are expanded in trailing args (after --)
    snapshot_switch(
        "switch_execute_template_in_args",
        &repo,
        &[
            "--create",
            "args-test",
            "--execute",
            "echo",
            "--",
            "branch={{ branch }}",
            "repo={{ repo }}",
        ],
    );
}

#[rstest]
fn test_switch_execute_template_error(repo: TestRepo) {
    // Test that invalid templates are rejected with a clear error
    snapshot_switch(
        "switch_execute_template_error",
        &repo,
        &["--create", "error-test", "--execute", "echo {{ unclosed"],
    );
}

#[rstest]
fn test_switch_execute_arg_template_error(repo: TestRepo) {
    // Test that invalid templates in trailing args (after --) are rejected
    snapshot_switch(
        "switch_execute_arg_template_error",
        &repo,
        &[
            "--create",
            "arg-error-test",
            "--execute",
            "echo",
            "--",
            "valid={{ branch }}",
            "invalid={{ unclosed",
        ],
    );
}

// Verbose mode tests
#[rstest]
fn test_switch_execute_verbose_template_expansion(repo: TestRepo) {
    // Test that -v shows template expansion details
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd_with_global_flags(
            &repo,
            "switch",
            &[
                "--create",
                "verbose-test",
                "--execute",
                "echo 'branch={{ branch }}'",
            ],
            None,
            &["-v"],
        );
        assert_cmd_snapshot!("switch_execute_verbose_template", cmd);
    });
}

#[rstest]
fn test_switch_execute_verbose_multiline_template(repo: TestRepo) {
    // Test that -v shows multiline template expansion with proper formatting
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        // Multiline template with conditional
        let multiline_template = r#"{% if branch %}
echo 'branch={{ branch }}'
echo 'repo={{ repo }}'
{% endif %}"#;

        let mut cmd = make_snapshot_cmd_with_global_flags(
            &repo,
            "switch",
            &[
                "--create",
                "multiline-test",
                "--execute",
                multiline_template,
            ],
            None,
            &["-v"],
        );
        assert_cmd_snapshot!("switch_execute_verbose_multiline_template", cmd);
    });
}

// --no-hooks flag tests
#[rstest]
fn test_switch_no_config_commands_execute_still_runs(repo: TestRepo) {
    snapshot_switch(
        "switch_no_hooks_execute_still_runs",
        &repo,
        &[
            "--create",
            "no-hooks-test",
            "--execute",
            "echo 'execute command runs'",
            "--no-hooks",
        ],
    );
}

#[rstest]
fn test_switch_no_config_commands_skips_post_start_commands(repo: TestRepo) {
    use std::fs;

    // Create project config with a command that would create a file
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();

    let create_file_cmd = "echo 'marker' > marker.txt";

    fs::write(
        config_dir.join("wt.toml"),
        format!(r#"post-start = "{}""#, create_file_cmd),
    )
    .unwrap();

    repo.commit("Add config");

    // Pre-approve the command (repo.home_path() is automatically set as HOME)
    let user_config_dir = repo.home_path().join(".config/worktrunk");
    fs::create_dir_all(&user_config_dir).unwrap();
    fs::write(
        user_config_dir.join("config.toml"),
        format!(
            r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"

[projects."main"]
approved-commands = ["{}"]
"#,
            create_file_cmd
        ),
    )
    .unwrap();

    // With --no-hooks, the post-start command should be skipped
    snapshot_switch(
        "switch_no_hooks_skips_post_start",
        &repo,
        &["--create", "no-post-start", "--no-hooks"],
    );

    // post-start runs in the background; with --no-hooks it is never spawned,
    // but sleep briefly so a regression that incorrectly spawns it has time to
    // create the marker (per tests/CLAUDE.md "Testing absence").
    std::thread::sleep(std::time::Duration::from_millis(500));
    let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
    let worktree = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{repo_name}.no-post-start"));
    assert!(
        !worktree.join("marker.txt").exists(),
        "post-start hook should have been skipped, but marker.txt was created"
    );
}

#[rstest]
fn test_switch_no_config_commands_with_existing_worktree(mut repo: TestRepo) {
    repo.add_worktree("existing-no-hooks");

    // With --no-hooks, the --execute command should still run
    snapshot_switch(
        "switch_no_hooks_existing",
        &repo,
        &[
            "existing-no-hooks",
            "--execute",
            "echo 'execute still runs'",
            "--no-hooks",
        ],
    );
}

#[rstest]
fn test_switch_no_config_commands_with_yes(repo: TestRepo) {
    use std::fs;

    // Create project config with a command that would create a file
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"post-start = "echo 'marker' > marker.txt""#,
    )
    .unwrap();

    repo.commit("Add config");

    // With --no-hooks, even --yes shouldn't execute config commands
    // (HOME is automatically set to repo.home_path() by configure_wt_cmd)
    snapshot_switch(
        "switch_no_hooks_with_yes",
        &repo,
        &["--create", "yes-no-hooks", "--yes", "--no-hooks"],
    );

    // post-start runs in the background; with --no-hooks it is never spawned,
    // but sleep briefly so a regression that incorrectly spawns it has time to
    // create the marker (per tests/CLAUDE.md "Testing absence").
    std::thread::sleep(std::time::Duration::from_millis(500));
    let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
    let worktree = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{repo_name}.yes-no-hooks"));
    assert!(
        !worktree.join("marker.txt").exists(),
        "post-start hook should have been skipped, but marker.txt was created"
    );
}

/// `wt switch --create <new> --base <other>` resolves `pre-start` / `post-start`
/// from the base branch's committed `.config/wt.toml` — the worktree these hooks
/// run in is a checkout of that branch. The primary worktree (cwd) has no
/// project config at all; only `other-base` does, so a regression that read the
/// invoking worktree's config would run nothing.
#[rstest]
fn test_switch_create_reads_base_branch_config(mut repo: TestRepo) {
    // Commit a `.config/wt.toml` on `other-base` only (not on `main`).
    let other_wt = repo.add_worktree("other-base");
    fs::create_dir_all(other_wt.join(".config")).unwrap();
    fs::write(
        other_wt.join(".config/wt.toml"),
        // `{{ repo_path }}` is the main worktree root regardless of which
        // worktree the hook runs in, so the markers land where the test reads.
        r#"pre-start = "echo pre-start-from-base > {{ repo_path }}/pre-start-marker.txt"
post-start = "echo post-start-from-base > {{ repo_path }}/post-start-marker.txt"
"#,
    )
    .unwrap();
    repo.run_git_in(&other_wt, &["add", ".config/wt.toml"]);
    repo.run_git_in(&other_wt, &["commit", "-m", "Add hooks on other-base"]);

    let output = repo
        .wt_command()
        .args([
            "switch",
            "--create",
            "new-feature",
            "--base",
            "other-base",
            "--yes",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "wt switch --create failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let pre_marker = repo.root_path().join("pre-start-marker.txt");
    wait_for_file_content(&pre_marker);
    assert_eq!(
        fs::read_to_string(&pre_marker).unwrap().trim(),
        "pre-start-from-base",
        "pre-start should run with the base branch's config"
    );
    let post_marker = repo.root_path().join("post-start-marker.txt");
    wait_for_file_content(&post_marker);
    assert_eq!(
        fs::read_to_string(&post_marker).unwrap().trim(),
        "post-start-from-base",
        "post-start should run with the base branch's config"
    );
}

/// `wt switch <existing>` resolves `post-switch` from the destination worktree's
/// `.config/wt.toml`, not the worktree `wt switch` ran in. Only the destination
/// has a project config here.
#[rstest]
fn test_switch_existing_reads_destination_worktree_config(mut repo: TestRepo) {
    let dest = repo.add_worktree("dest");
    fs::create_dir_all(dest.join(".config")).unwrap();
    fs::write(
        dest.join(".config/wt.toml"),
        r#"post-switch = "echo post-switch-from-dest > {{ repo_path }}/post-switch-marker.txt""#,
    )
    .unwrap();

    let output = repo
        .wt_command()
        .args(["switch", "dest", "--yes"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "wt switch dest failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let marker = repo.root_path().join("post-switch-marker.txt");
    wait_for_file_content(&marker);
    assert_eq!(
        fs::read_to_string(&marker).unwrap().trim(),
        "post-switch-from-dest",
        "post-switch should run with the destination worktree's config"
    );
}

/// A destination worktree with a malformed `.config/wt.toml` makes `wt switch
/// <existing>` abort with the parse error in stderr — no silent fall-through
/// to a different config. The path is surfaced so the user can find and fix
/// the offending file.
#[rstest]
fn test_switch_existing_aborts_on_malformed_destination_config(mut repo: TestRepo) {
    let dest = repo.add_worktree("dest");
    fs::create_dir_all(dest.join(".config")).unwrap();
    fs::write(dest.join(".config/wt.toml"), "this is not [ valid toml").unwrap();

    let output = repo
        .wt_command()
        .args(["switch", "dest", "--yes"])
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !output.status.success(),
        "wt switch should abort on a malformed destination config; stderr:\n{stderr}"
    );
    assert!(
        stderr.contains("wt.toml"),
        "error should name the offending config file; stderr:\n{stderr}"
    );
}

/// `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path for *every* config read —
/// including `wt switch --create`'s base-ref preview — so the override file's
/// hooks run, not the base branch's committed `.config/wt.toml`.
#[rstest]
fn test_switch_create_honors_project_config_path_override(mut repo: TestRepo) {
    // The base branch carries a committed hook that must be ignored.
    let other_wt = repo.add_worktree("other-base");
    fs::create_dir_all(other_wt.join(".config")).unwrap();
    fs::write(
        other_wt.join(".config/wt.toml"),
        r#"post-start = "echo IGNORED-COMMITTED-HOOK > {{ repo_path }}/wrong-marker.txt""#,
    )
    .unwrap();
    repo.run_git_in(&other_wt, &["add", ".config/wt.toml"]);
    repo.run_git_in(&other_wt, &["commit", "-m", "Committed hook on other-base"]);

    // The override file (outside any worktree) is what should win.
    let override_path = repo.root_path().parent().unwrap().join("override-wt.toml");
    fs::write(
        &override_path,
        r#"post-start = "echo OVERRIDE-HOOK > {{ repo_path }}/right-marker.txt""#,
    )
    .unwrap();

    let output = repo
        .wt_command()
        .env("WORKTRUNK_PROJECT_CONFIG_PATH", &override_path)
        .args([
            "switch",
            "--create",
            "new-feature",
            "--base",
            "other-base",
            "--yes",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "wt switch --create failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let right = repo.root_path().join("right-marker.txt");
    wait_for_file_content(&right);
    assert_eq!(fs::read_to_string(&right).unwrap().trim(), "OVERRIDE-HOOK");
    // The base ref's committed hook must never have run.
    std::thread::sleep(std::time::Duration::from_millis(500));
    assert!(
        !repo.root_path().join("wrong-marker.txt").exists(),
        "the base ref's committed hook must not run when the config path is overridden"
    );
}

// --no-verify backward compatibility
#[rstest]
fn test_switch_no_verify_deprecated_still_works(repo: TestRepo) {
    // --no-verify should still work but emit a deprecation warning
    let output = repo
        .wt_command()
        .args(["switch", "--create", "deprecated-flag-test", "--no-verify"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--no-verify is deprecated"),
        "Expected deprecation warning in stderr: {stderr}"
    );
    assert!(
        stderr.contains("--no-hooks"),
        "Expected --no-hooks suggestion in stderr: {stderr}"
    );
}

// Branch inference and special branch tests
#[rstest]
fn test_switch_create_no_remote(repo: TestRepo) {
    // Deliberately NOT calling setup_remote to test local branch inference
    // Create a branch without specifying base - should infer default branch locally
    snapshot_switch("switch_create_no_remote", &repo, &["--create", "feature"]);
}

#[rstest]
fn test_switch_primary_on_different_branch(mut repo: TestRepo) {
    repo.switch_primary_to("develop");
    assert_eq!(repo.current_branch(), "develop");

    // Create a feature worktree using the default branch (main)
    // This should work fine even though primary is on develop
    snapshot_switch(
        "switch_primary_on_different_branch",
        &repo,
        &["--create", "feature-from-main"],
    );

    // Also test switching to an existing branch
    repo.add_worktree("existing-branch");
    snapshot_switch(
        "switch_to_existing_primary_on_different_branch",
        &repo,
        &["existing-branch"],
    );
}

#[rstest]
fn test_switch_previous_branch_no_history(repo: TestRepo) {
    // No checkout history, so wt switch - should fail with helpful error
    snapshot_switch("switch_previous_branch_no_history", &repo, &["-"]);
}

#[rstest]
fn test_switch_main_branch(repo: TestRepo) {
    // Create a feature branch (use unique name to avoid fixture conflicts)
    repo.run_git(&["branch", "test-feat-x"]);

    // Switch to test-feat-x first
    snapshot_switch("switch_main_branch_to_feature", &repo, &["test-feat-x"]);

    // Now wt switch ^ should resolve to main
    snapshot_switch("switch_main_branch", &repo, &["^"]);
}

#[rstest]
fn test_create_with_base_main(repo: TestRepo) {
    // Create new branch from main using ^
    snapshot_switch(
        "create_with_base_main",
        &repo,
        &["--create", "new-feature", "--base", "^"],
    );
}

#[rstest]
fn test_switch_no_warning_when_branch_matches(mut repo: TestRepo) {
    // Create a worktree for "feature" branch (normal case)
    repo.add_worktree("feature");

    // Switch to feature with shell integration - should NOT show any warning
    snapshot_switch_with_directive_file(
        "switch_no_warning_when_branch_matches",
        &repo,
        &["feature"],
    );
}

#[rstest]
fn test_switch_branch_worktree_mismatch_shows_hint(repo: TestRepo) {
    // Create a worktree at a non-standard path (sibling to repo, not following template)
    let wrong_path = repo.root_path().parent().unwrap().join("wrong-path");
    repo.run_git(&[
        "worktree",
        "add",
        wrong_path.to_str().unwrap(),
        "-b",
        "feature",
    ]);

    // Switch to feature - should show hint about branch-worktree mismatch
    snapshot_switch_with_directive_file(
        "switch_branch_worktree_mismatch_shows_hint",
        &repo,
        &["feature"],
    );
}

///
/// When shell integration is not active, the branch-worktree mismatch warning should appear
/// alongside the "cannot change directory" warning.
#[rstest]
fn test_switch_worktree_mismatch_no_shell_integration(repo: TestRepo) {
    // Create a worktree at a non-standard path
    let wrong_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("wrong-path-no-shell");
    repo.run_git(&[
        "worktree",
        "add",
        wrong_path.to_str().unwrap(),
        "-b",
        "feature-mismatch",
    ]);

    // Switch without directive file (no shell integration) - should show both warnings
    snapshot_switch(
        "switch_branch_worktree_mismatch_no_shell",
        &repo,
        &["feature-mismatch"],
    );
}

///
/// When already in a worktree whose path doesn't match the branch name,
/// switching to that branch should show the branch-worktree mismatch warning.
#[rstest]
fn test_switch_already_at_with_branch_worktree_mismatch(repo: TestRepo) {
    // Create a worktree at a non-standard path
    let wrong_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("wrong-path-already");
    repo.run_git(&[
        "worktree",
        "add",
        wrong_path.to_str().unwrap(),
        "-b",
        "feature-already",
    ]);

    // Switch from within the worktree with branch-worktree mismatch (AlreadyAt case)
    snapshot_switch_from_dir(
        "switch_already_at_branch_worktree_mismatch",
        &repo,
        &["feature-already"],
        &wrong_path,
    );
}

///
/// With branch-first lookup, if a worktree was created for "feature" but then switched to
/// "bugfix", `wt switch feature` can't find it (since it looks by branch name). When it
/// tries to create a new worktree, it fails because the path exists. The hint shows what
/// branch currently occupies the path.
#[rstest]
fn test_switch_error_path_occupied_different_branch(repo: TestRepo) {
    // Create a worktree for "feature" branch at expected path
    let feature_path = repo.root_path().parent().unwrap().join("repo.feature");
    repo.run_git(&[
        "worktree",
        "add",
        feature_path.to_str().unwrap(),
        "-b",
        "feature",
    ]);

    // Switch that worktree to a different branch "bugfix"
    repo.run_git_in(&feature_path, &["switch", "-c", "bugfix"]);

    // Switch to feature - should error since path is occupied by bugfix worktree
    snapshot_switch_with_directive_file(
        "switch_error_path_occupied_different_branch",
        &repo,
        &["feature"],
    );
}

#[rstest]
fn test_switch_error_path_occupied_detached(repo: TestRepo) {
    // Create a worktree for "feature" branch at expected path
    let feature_path = repo.root_path().parent().unwrap().join("repo.feature");
    repo.run_git(&[
        "worktree",
        "add",
        feature_path.to_str().unwrap(),
        "-b",
        "feature",
    ]);

    // Get the HEAD commit and detach
    let output = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .current_dir(&feature_path)
        .run()
        .unwrap();
    let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();

    repo.run_git_in(&feature_path, &["checkout", "--detach", &commit]);

    // Switch to feature - should error since path is occupied by detached worktree
    snapshot_switch_with_directive_file("switch_error_path_occupied_detached", &repo, &["feature"]);
}

/// Switch to a detached worktree by absolute path (#1661).
#[rstest]
fn test_switch_detached_worktree_by_path(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-detached");
    repo.detach_head_in_worktree("feature-detached");

    let worktree_str = worktree_path.to_string_lossy().to_string();
    let output = repo
        .wt_command()
        .args(["switch", &worktree_str])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt switch should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

/// Switch via a symlink that resolves to an existing worktree (#2460).
#[cfg(unix)]
#[rstest]
fn test_switch_worktree_by_symlinked_path(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature-symlinked");

    let symlink_path = worktree_path.parent().unwrap().join("worktree-link");
    std::os::unix::fs::symlink(&worktree_path, &symlink_path).unwrap();

    let symlink_str = symlink_path.to_string_lossy().to_string();
    let output = repo
        .wt_command()
        .args(["switch", &symlink_str])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt switch via symlink should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

/// Switch to a detached worktree by relative path (#1661).
/// Relative paths with directory separators (e.g., "../repo.feature") are resolved against CWD.
#[rstest]
fn test_switch_detached_worktree_by_relative_path(mut repo: TestRepo) {
    repo.add_worktree("feature-detached");
    repo.detach_head_in_worktree("feature-detached");

    // From the main worktree (repo/), the detached worktree is at ../repo.feature-detached
    let relative_path = "../repo.feature-detached";

    snapshot_switch_with_directive_file(
        "switch_detached_worktree_by_relative_path",
        &repo,
        &[relative_path],
    );
}

///
/// When the main worktree (repo root) has been switched to a feature branch via
/// `git checkout feature`, `wt switch main` should error with a helpful message
/// explaining how to get there. This matches GitHub issue #327.
#[rstest]
fn test_switch_main_worktree_on_different_branch(repo: TestRepo) {
    // Switch the main worktree to a different branch
    repo.run_git(&["checkout", "-b", "feature"]);

    // Now try to switch to main - should error since main worktree is on different branch
    snapshot_switch_with_directive_file(
        "switch_main_worktree_on_different_branch",
        &repo,
        &["main"],
    );
}

///
/// This reproduces GitHub issue #327: user is in a feature worktree, main worktree has been
/// switched to a different branch, and user runs `wt switch <default-branch>`.
#[rstest]
fn test_switch_default_branch_from_feature_worktree(mut repo: TestRepo) {
    // Create a feature worktree to work from
    let feature_a_path = repo.add_worktree("feature-a");

    // Switch main worktree to a different branch (simulates user running git checkout there)
    repo.run_git(&["checkout", "-b", "feature-rpa"]);

    // From feature-a worktree, try to switch to main (default branch)
    // This should error because main worktree is now on feature-rpa
    snapshot_switch_from_dir(
        "switch_default_branch_from_feature_worktree",
        &repo,
        &["main"],
        &feature_a_path,
    );
}

// Execute tests with directive file
/// The shell wrapper sources this file and propagates the exit code.
#[rstest]
fn test_switch_internal_execute_exit_code(repo: TestRepo) {
    // wt succeeds (exit 0), but shell script contains "exit 42"
    // Shell wrapper will eval and return 42
    snapshot_switch_with_directive_file(
        "switch_internal_execute_exit_code",
        &repo,
        &["--create", "exit-code-test", "--execute", "exit 42"],
    );
}

/// When wt succeeds but the execute script would fail, wt still exits 0.
/// The shell wrapper handles the execute command's exit code.
#[rstest]
fn test_switch_internal_execute_with_output_before_exit(repo: TestRepo) {
    // Execute command outputs then exits with code
    let cmd = "echo 'doing work'\nexit 7";

    snapshot_switch_with_directive_file(
        "switch_internal_execute_output_then_exit",
        &repo,
        &["--create", "output-exit-test", "--execute", cmd],
    );
}
// History and ping-pong tests
///
/// Bug scenario: If user changes worktrees without using `wt switch` (e.g., cd directly),
/// history becomes stale. The fix ensures we always use the actual current branch
/// when recording new history, not any previously stored value.
#[rstest]
fn test_switch_previous_with_stale_history(repo: TestRepo) {
    // Create branches with worktrees
    for branch in ["branch-a", "branch-b", "branch-c"] {
        repo.run_git(&["branch", branch]);
    }

    // Switch to branch-a, then branch-b to establish history
    snapshot_switch("switch_stale_history_to_a", &repo, &["branch-a"]);
    snapshot_switch("switch_stale_history_to_b", &repo, &["branch-b"]);

    // Now manually set history to simulate user changing worktrees without wt switch.
    // History stores just the previous branch (branch-a from the earlier switches).
    // If user manually cd'd to branch-c's worktree, history would still say branch-a.
    repo.run_git(&["config", "worktrunk.history", "branch-a"]);

    // Run wt switch - from branch-b's worktree.
    // Should go to branch-a (what history says), and record actual current branch as new previous.
    snapshot_switch("switch_stale_history_first_dash", &repo, &["-"]);

    // Run wt switch - again.
    // Should go back to wherever we actually were (recorded as new previous in step above)
    snapshot_switch("switch_stale_history_second_dash", &repo, &["-"]);
}

///
/// This simulates real usage with shell integration, where each `wt switch` actually
/// changes the working directory before the next command runs.
#[rstest]
fn test_switch_ping_pong_realistic(repo: TestRepo) {
    // Create ping-pong branch (unique name to avoid fixture conflicts)
    repo.run_git(&["branch", "ping-pong"]);

    // Step 1: From main worktree, switch to ping-pong (creates worktree)
    // History: current=ping-pong, previous=main
    snapshot_switch_from_dir(
        "ping_pong_1_main_to_feature",
        &repo,
        &["ping-pong"],
        repo.root_path(),
    );

    // Calculate ping-pong worktree path
    let ping_pong_path = repo.root_path().parent().unwrap().join(format!(
        "{}.ping-pong",
        repo.root_path().file_name().unwrap().to_str().unwrap()
    ));

    // Step 2: From ping-pong worktree, switch back to main
    // History: current=main, previous=ping-pong
    snapshot_switch_from_dir(
        "ping_pong_2_feature_to_main",
        &repo,
        &["main"],
        &ping_pong_path,
    );

    // Step 3: From main worktree, wt switch - should go to ping-pong
    // History: current=ping-pong, previous=main
    snapshot_switch_from_dir(
        "ping_pong_3_dash_to_feature",
        &repo,
        &["-"],
        repo.root_path(),
    );

    // Step 4: From ping-pong worktree, wt switch - should go back to main
    // History: current=main, previous=ping-pong
    snapshot_switch_from_dir("ping_pong_4_dash_to_main", &repo, &["-"], &ping_pong_path);

    // Step 5: From main worktree, wt switch - should go to ping-pong again (ping-pong!)
    // History: current=ping-pong, previous=main
    snapshot_switch_from_dir(
        "ping_pong_5_dash_to_feature_again",
        &repo,
        &["-"],
        repo.root_path(),
    );
}

#[cfg(unix)] // Interactive picker only available on Unix
#[rstest]
fn test_switch_no_args_requires_tty(repo: TestRepo) {
    // Run switch with no arguments in non-TTY - should fail with TTY requirement
    // (interactive picker requires a terminal)
    snapshot_switch("switch_missing_argument_hints", &repo, &[]);
}

///
/// This verifies the fix for non-Unix platforms where stdin was incorrectly
/// set to Stdio::null() instead of Stdio::inherit(), breaking interactive
/// programs like `vim`, `python -i`, or `claude`.
///
/// The test pipes input to `wt switch --execute "cat"` and verifies the
/// cat command receives and outputs that input, proving stdin was inherited.
#[rstest]
fn test_switch_execute_stdin_inheritance(repo: TestRepo) {
    use std::io::Write;
    use std::process::Stdio;

    let test_input = "stdin_inheritance_test_content\n";

    let mut cmd = repo.wt_command();
    cmd.args(["switch", "--create", "stdin-test", "--execute", "cat"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    let mut child = cmd.spawn().expect("failed to spawn wt");

    // Write test input to stdin and close it to signal EOF
    {
        let stdin = child.stdin.as_mut().expect("failed to get stdin");
        stdin
            .write_all(test_input.as_bytes())
            .expect("failed to write to stdin");
    }

    let output = child.wait_with_output().expect("failed to wait for child");
    let stdout = String::from_utf8_lossy(&output.stdout);

    // The cat command should have received our input via inherited stdin
    // and echoed it to stdout
    assert!(
        stdout.contains("stdin_inheritance_test_content"),
        "Expected cat to receive piped stdin. Got stdout: {}\nstderr: {}",
        stdout,
        String::from_utf8_lossy(&output.stderr)
    );
}

// Error context tests

#[rstest]
fn test_switch_outside_git_repo(temp_home: TempDir) {
    let temp_dir = tempfile::tempdir().unwrap();

    // Run wt switch --create outside a git repo - should show "Failed to switch worktree" context
    let settings = setup_home_snapshot_settings(&temp_home);
    settings.bind(|| {
        let mut cmd = wt_command();
        cmd.arg("switch")
            .arg("--create")
            .arg("feature")
            .current_dir(temp_dir.path());
        set_temp_home_env(&mut cmd, temp_home.path());

        assert_cmd_snapshot!(cmd);
    });
}

// Clobber flag path backup tests

#[rstest]
fn test_switch_clobber_backs_up_stale_directory(repo: TestRepo) {
    // Calculate where the worktree would be created
    let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
    let expected_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{}.clobber-dir-test", repo_name));

    // Create a stale directory at that path (not a worktree)
    std::fs::create_dir_all(&expected_path).unwrap();
    std::fs::write(expected_path.join("stale_file.txt"), "stale content").unwrap();

    // With --clobber, should move the directory to .bak and create the worktree
    snapshot_switch(
        "switch_clobber_removes_stale_dir",
        &repo,
        &["--create", "--clobber", "clobber-dir-test"],
    );

    // Verify the worktree was created
    assert!(expected_path.exists());
    assert!(expected_path.is_dir());

    // Verify the backup was created (TEST_EPOCH=1735776000 -> 2025-01-02 00:00:00 UTC)
    let backup_path = repo.root_path().parent().unwrap().join(format!(
        "{}.clobber-dir-test.bak.20250102-000000",
        repo_name
    ));
    assert!(
        backup_path.exists(),
        "Backup should exist at {:?}",
        backup_path
    );
    assert!(backup_path.is_dir());

    // Verify stale content is preserved in backup
    let stale_file = backup_path.join("stale_file.txt");
    assert!(stale_file.exists(), "Stale file should be in backup");
    assert_eq!(
        std::fs::read_to_string(&stale_file).unwrap(),
        "stale content"
    );
}

#[rstest]
fn test_switch_clobber_backs_up_stale_file(repo: TestRepo) {
    // Calculate where the worktree would be created
    let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
    let expected_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{}.clobber-file-test", repo_name));

    // Create a file (not directory) at that path
    std::fs::write(&expected_path, "stale file content").unwrap();

    // With --clobber, should move the file to .bak and create the worktree
    snapshot_switch(
        "switch_clobber_removes_stale_file",
        &repo,
        &["--create", "--clobber", "clobber-file-test"],
    );

    // Verify the worktree was created (should be a directory now)
    assert!(expected_path.is_dir());

    // Verify the backup was created (TEST_EPOCH=1735776000 -> 2025-01-02 00:00:00 UTC)
    let backup_path = repo.root_path().parent().unwrap().join(format!(
        "{}.clobber-file-test.bak.20250102-000000",
        repo_name
    ));
    assert!(
        backup_path.exists(),
        "Backup should exist at {:?}",
        backup_path
    );
    assert!(backup_path.is_file());
    assert_eq!(
        std::fs::read_to_string(&backup_path).unwrap(),
        "stale file content"
    );
}

#[rstest]
fn test_switch_clobber_error_backup_exists(repo: TestRepo) {
    // Calculate where the worktree would be created
    let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
    let expected_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{}.clobber-backup-exists", repo_name));

    // Create a stale directory at the target path
    std::fs::create_dir_all(&expected_path).unwrap();

    // Also create the backup path that would be generated
    // TEST_EPOCH=1735776000 -> 2025-01-02 00:00:00 UTC
    let backup_path = repo.root_path().parent().unwrap().join(format!(
        "{}.clobber-backup-exists.bak.20250102-000000",
        repo_name
    ));
    std::fs::create_dir_all(&backup_path).unwrap();

    // With --clobber, should error because backup path exists
    snapshot_switch(
        "switch_clobber_error_backup_exists",
        &repo,
        &["--create", "--clobber", "clobber-backup-exists"],
    );

    // Both paths should still exist (nothing was moved)
    assert!(expected_path.exists());
    assert!(backup_path.exists());
}

///
/// When the user runs `wt` directly (not through shell wrapper), their shell won't
/// cd to the worktree directory. Hooks should show "@ path" to clarify where they run.
#[rstest]
fn test_switch_post_hook_shows_path_without_shell_integration(repo: TestRepo) {
    use std::fs;

    // Create project config with a post-switch hook
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        "post-switch = \"echo switched\"\n",
    )
    .unwrap();

    repo.commit("Add config");

    // Run switch WITHOUT directive file (shell integration not active)
    // Use --yes to auto-approve the hook command
    // The hook output should show "@ path" annotation
    snapshot_switch(
        "switch_post_hook_path_annotation",
        &repo,
        &["--create", "post-hook-test", "--yes"],
    );
}

///
/// When running through the shell wrapper (directive file set), the user's shell will
/// actually cd to the worktree. Hooks don't need the path annotation.
#[rstest]
fn test_switch_post_hook_no_path_with_shell_integration(repo: TestRepo) {
    use std::fs;

    // Create project config with a post-switch hook
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        "post-switch = \"echo switched\"\n",
    )
    .unwrap();

    repo.commit("Add config");

    // Run switch WITH directive file (shell integration active)
    // The hook output should NOT show "@ path" annotation
    snapshot_switch_with_directive_file(
        "switch_post_hook_no_path_with_shell_integration",
        &repo,
        &["--create", "post-hook-shell-test", "--yes"],
    );
}

/// When both post-switch and post-start hooks are configured, they should be combined
/// into a single output line with format: "Running post-switch: {names}; post-start: {names} @ path"
#[rstest]
fn test_switch_combined_post_switch_and_post_start_hooks(repo: TestRepo) {
    // Create project config with both post-switch and post-start hooks
    let config_dir = repo.root_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();
    fs::write(
        config_dir.join("wt.toml"),
        r#"post-switch = "echo switched"
post-start = "echo started"
"#,
    )
    .unwrap();

    repo.commit("Add config");

    // Run switch --create (triggers both post-switch and post-start)
    // Should show a single combined line: "Running post-switch: project; post-start: project @ path"
    snapshot_switch(
        "switch_combined_hooks",
        &repo,
        &["--create", "combined-hooks-test", "--yes"],
    );
}

#[rstest]
fn test_switch_clobber_path_with_extension(repo: TestRepo) {
    // Calculate where the worktree would be created
    let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
    let expected_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{}.clobber-ext.txt", repo_name));

    // Create a file with an extension at that path
    std::fs::write(&expected_path, "file with extension").unwrap();

    // With --clobber, should move the file preserving extension in backup name
    snapshot_switch(
        "switch_clobber_path_with_extension",
        &repo,
        &["--create", "--clobber", "clobber-ext.txt"],
    );

    // Verify the worktree was created
    assert!(expected_path.is_dir());

    // Verify backup path includes the original extension
    // file.txt -> file.txt.bak.TIMESTAMP
    let backup_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{}.clobber-ext.txt.bak.20250102-000000", repo_name));
    assert!(
        backup_path.exists(),
        "Backup should exist at {:?}",
        backup_path
    );
    assert_eq!(
        std::fs::read_to_string(&backup_path).unwrap(),
        "file with extension"
    );
}

#[rstest]
fn test_switch_create_no_hint_with_custom_worktree_path(repo: TestRepo) {
    // Set up custom worktree-path in user config
    repo.write_test_config(r#"worktree-path = ".worktrees/{{ branch | sanitize }}""#);

    let output = repo
        .wt_command()
        .args(["switch", "--create", "test-no-hint"])
        .output()
        .unwrap();
    assert!(output.status.success());

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("Customize worktree locations"),
        "Hint should be suppressed when user has custom worktree-path config"
    );
}

#[rstest]
fn test_switch_create_uses_codename_in_worktree_path(repo: TestRepo) {
    repo.write_test_config(
        r#"worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(3) }}""#,
    );

    let output = repo
        .wt_command()
        .args([
            "switch",
            "--create",
            "feature/JIRA-1234",
            "--format=json",
            "--no-cd",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "switch --create should succeed, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    let path = Path::new(json["path"].as_str().unwrap());
    let dir_name = path.file_name().unwrap().to_str().unwrap();
    let repo_prefix = format!(
        "{}.",
        repo.root_path().file_name().unwrap().to_str().unwrap()
    );
    let codename = dir_name.strip_prefix(&repo_prefix).unwrap();

    assert!(path.exists(), "worktree should exist @ {}", path.display());
    assert_eq!(codename.split('-').count(), 3, "got: {codename}");
    assert!(
        codename.chars().all(|c| c.is_ascii_lowercase() || c == '-'),
        "got: {codename}"
    );
}

/// Test that the worktree-path hint is suppressed when a project-specific
/// worktree-path is configured (not just a global one).
///
/// Regression test for #1939: `has_custom_worktree_path()` only checked the
/// global `worktree-path` setting, causing a misleading hint even when a
/// project-specific template was configured.
#[rstest]
fn test_switch_create_no_hint_with_project_specific_worktree_path(repo: TestRepo) {
    // Set origin to a GitHub URL so the project identifier matches
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/test-org/test-repo.git",
    ]);

    // Redirect GitHub URL to local bare remote for actual git operations
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/test-org/test-repo.git",
    ]);

    // Set project-specific worktree-path (no global worktree-path set)
    repo.write_test_config(
        r#"
[projects."github.com/test-org/test-repo"]
worktree-path = "{{ repo_path }}/../{{ branch | sanitize }}"
"#,
    );

    let output = repo
        .wt_command()
        .args(["switch", "--create", "project-feature"])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "switch --create should succeed, stderr: {stderr}"
    );

    // Hint should be suppressed when project-specific worktree-path exists
    assert!(
        !stderr.contains("customize worktree locations"),
        "Hint should be suppressed when project has custom worktree-path. stderr: {stderr}"
    );
}

// ============================================================================
// PR Syntax Tests (pr:<number>)
// ============================================================================

use crate::common::mock_commands::{MockConfig, MockResponse, copy_mock_binary};

/// Set origin to a GitHub URL so `fetch_pr_info` can parse owner/repo.
///
/// Saves the original bare repo URL and configures `url.insteadOf` so that
/// `git fetch`/`git push` still work against the local bare remote.
fn set_github_remote_url(repo: &TestRepo) {
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);

    // Redirect GitHub URL to local bare remote for actual git operations
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);
}

/// Helper to set up mock gh for PR tests with custom PR response.
///
/// The response should be in `gh api repos/{owner}/{repo}/pulls/{number}` format:
/// - `head.ref`, `head.repo.owner.login`, `head.repo.name`
/// - `base.repo.owner.login`, `base.repo.name`
/// - `html_url`
fn setup_mock_gh_for_pr(repo: &TestRepo, gh_response: Option<&str>) -> std::path::PathBuf {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    // Copy mock-stub binary as "gh"
    copy_mock_binary(&mock_bin, "gh");

    // Write PR response file if provided
    if let Some(response) = gh_response {
        fs::write(mock_bin.join("pr_response.json"), response).unwrap();

        MockConfig::new("gh")
            .version("gh version 2.0.0 (mock)")
            .command("api", MockResponse::file("pr_response.json"))
            .command("_default", MockResponse::exit(1))
            .write(&mock_bin);
    }

    mock_bin
}

/// Configure command environment for any mock CLI installed in `mock_bin`.
///
/// Sets `MOCK_CONFIG_DIR` (so mock-stub finds its config) and prepends
/// `mock_bin` to `PATH` (so the mock binary is found before any real CLI).
fn configure_mock_cli_env(cmd: &mut std::process::Command, mock_bin: &Path) {
    cmd.env("MOCK_CONFIG_DIR", mock_bin);

    // Find the actual PATH var name (case-insensitive on Windows) to avoid
    // creating a duplicate entry with different case.
    let (path_var_name, current_path) = std::env::vars_os()
        .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
        .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))
        .unwrap_or(("PATH".to_string(), None));

    let mut paths: Vec<std::path::PathBuf> = current_path
        .as_deref()
        .map(|p| std::env::split_paths(p).collect())
        .unwrap_or_default();
    paths.insert(0, mock_bin.to_path_buf());
    let new_path = std::env::join_paths(&paths)
        .unwrap()
        .to_string_lossy()
        .into_owned();

    cmd.env(path_var_name, new_path);
}

/// Test that --create flag conflicts with pr: syntax
#[rstest]
fn test_switch_pr_create_conflict(#[from(repo_with_remote)] repo: TestRepo) {
    // Set origin URL to GitHub-style so PR resolution works
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);

    // Mock gh to return PR info (we fetch before checking --create to show branch name)
    let gh_response = r#"{
        "title": "Fix authentication bug in login flow",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/101"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_create_conflict", cmd);
    });
}

/// Test same-repo PR checkout (base.repo == head.repo)
#[rstest]
fn test_switch_pr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
    // Create a feature branch and push it to the remote
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    // Get the bare remote's actual URL before we modify origin
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Set origin URL to GitHub-style so find_remote_for_repo() can match owner/test-repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);

    // Configure git to redirect github.com URLs to the local bare remote.
    // This is necessary because:
    // 1. origin must have a GitHub URL for find_remote_for_repo() to match owner/repo
    // 2. But we need git fetch to actually succeed using the local bare remote
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    // gh api repos/{owner}/{repo}/pulls/{number} format
    let gh_response = r#"{
        "title": "Fix authentication bug in login flow",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/101"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_same_repo", cmd);
    });
}

/// Test same-repo PR with a limited fetch refspec (single-branch clone scenario).
///
/// In repos with a limited refspec (e.g., `+refs/heads/main:refs/remotes/origin/main`),
/// `git fetch origin <branch>` only updates FETCH_HEAD but doesn't create the remote
/// tracking branch. This caused `wt switch pr:101` to fail with "No branch named X".
#[rstest]
fn test_switch_pr_same_repo_limited_refspec(#[from(repo_with_remote)] mut repo: TestRepo) {
    // Create a feature branch and push it to the remote
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Set origin URL to GitHub-style so find_remote_for_repo() can match owner/test-repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);

    // Redirect github.com URLs to the local bare remote
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    // Restrict fetch refspec to only main, simulating a single-branch clone
    repo.run_git(&[
        "config",
        "remote.origin.fetch",
        "+refs/heads/main:refs/remotes/origin/main",
    ]);

    let gh_response = r#"{
        "title": "Fix authentication bug in login flow",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/101"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_same_repo_limited_refspec", cmd);
    });
}

/// Test same-repo PR when origin points to a different repo (no remote for PR's repo)
///
/// User scenario:
/// 1. User has origin pointing to their fork (contributor/test-repo)
/// 2. PR #101 is a same-repo PR on the upstream (owner/test-repo)
/// 3. No remote exists for owner/test-repo -> error with hint to add upstream
#[rstest]
fn test_switch_pr_same_repo_no_remote(#[from(repo_with_remote)] repo: TestRepo) {
    // Set origin to point to a DIFFERENT repo than where the PR is
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/contributor/test-repo.git",
    ]);

    // gh api response says base.repo and head.repo are both owner/test-repo (same-repo PR)
    // but origin points to contributor/test-repo (different repo)
    // So find_remote_for_repo("owner", "test-repo") will fail
    let gh_response = r#"{
        "title": "Fix authentication bug in login flow",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/101"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_same_repo_no_remote", cmd);
    });
}

/// Test fork PR checkout (base.repo != head.repo)
#[rstest]
fn test_switch_pr_fork(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a PR ref on the remote that can be fetched
    // First, create a commit that represents the PR head
    repo.run_git(&["checkout", "-b", "pr-source"]);
    fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
    repo.run_git(&["add", "pr-file.txt"]);
    repo.run_git(&["commit", "-m", "PR commit"]);

    // Get the commit SHA and push to remote as refs/pull/42/head
    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();

    // Push the ref to the bare remote
    repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);

    // Go back to main
    repo.run_git(&["checkout", "main"]);

    // Get the bare remote's actual URL before we modify origin
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Set origin URL to GitHub-style so find_remote_for_repo() can match owner/test-repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);

    // Configure git to redirect github.com URLs to the local bare remote.
    // This is necessary because:
    // 1. origin must have a GitHub URL for find_remote_for_repo() to match owner/repo
    // 2. But we need git fetch to actually succeed using the local bare remote
    // Git's url.<base>.insteadOf transparently rewrites the fetch URL.
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    // gh api repos/{owner}/{repo}/pulls/{number} format
    // head.repo is the fork (contributor/test-repo), base.repo is the upstream (owner/test-repo)
    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_fork", cmd);
    });
}

/// `pre-start`, `post-start`, and `post-switch` hooks on PR/MR-created worktrees
/// see `pr_number` and `pr_url` in their template context. Both GitHub PRs and
/// GitLab MRs canonicalize to the same `pr_*` names — hook authors don't need
/// to branch on platform. Pre-switch fires before PR resolution and never sees
/// them.
#[rstest]
fn test_switch_pr_hooks_see_pr_vars(#[from(repo_with_remote)] repo: TestRepo) {
    // Set up the same fork-PR scenario as test_switch_pr_fork: a refs/pull/42/head on the
    // bare remote, origin redirected to GitHub-style URL, and `gh api` mocked.
    // The PR commit carries the project config so the post-switch hooks read it
    // from the new worktree (a checkout of refs/pull/42/head) directly.
    repo.run_git(&["checkout", "-b", "pr-source"]);
    fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
    // Each hook writes its own marker in the primary worktree so we can verify
    // post-switch + post-start (background) populate pr_number/pr_url too.
    // {{ repo_path }} is always the main repo's working tree.
    fs::create_dir_all(repo.root_path().join(".config")).unwrap();
    fs::write(
        repo.root_path().join(".config/wt.toml"),
        r#"pre-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/pre_start.txt"
post-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_start.txt"
post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_switch.txt"
"#,
    )
    .unwrap();
    repo.run_git(&["add", "pr-file.txt", ".config/wt.toml"]);
    repo.run_git(&["commit", "-m", "PR commit with hook config"]);

    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();
    repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
    repo.run_git(&["checkout", "main"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;
    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let mut cmd = repo.wt_command();
    cmd.args(["switch", "pr:42", "--yes"]);
    configure_mock_cli_env(&mut cmd, &mock_bin);
    let output = cmd.output().expect("wt switch pr:42 should run");
    assert!(
        output.status.success(),
        "wt switch pr:42 failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );

    let expected = "pr_number=42 pr_url=https://github.com/owner/test-repo/pull/42";
    for marker in ["pre_start.txt", "post_start.txt", "post_switch.txt"] {
        let path = repo.root_path().join(marker);
        // post-* hooks run in the background; poll until the file appears.
        wait_for_file_content(&path);
        let contents = fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("{marker} should have been written: {e}"));
        assert_eq!(
            contents.trim(),
            expected,
            "{marker} hook should see canonical pr_number and pr_url variables",
        );
    }
}

/// `wt switch pr:N` resolves `post-start` etc. from the PR's tree — the fetched
/// head ref, potentially from a fork — and the approval prompt reads that same
/// PR config, so what the prompt lists can't diverge from what runs. The local
/// repo has no project config; only the PR commit does. Without `--yes` the
/// prompt lists the PR's hook and bails (non-interactive); with `--yes` the
/// hook executes against the new worktree (a checkout of the PR head).
#[rstest]
fn test_switch_pr_reads_pr_ref_config(#[from(repo_with_remote)] repo: TestRepo) {
    // Fork-PR scenario (mirrors `test_switch_pr_hooks_see_pr_vars`): a
    // refs/pull/42/head on the bare remote, origin redirected to a GitHub URL,
    // `gh api` mocked — but the PR commit carries a `.config/wt.toml`.
    repo.run_git(&["checkout", "-b", "pr-source"]);
    fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
    fs::create_dir_all(repo.root_path().join(".config")).unwrap();
    fs::write(
        repo.root_path().join(".config/wt.toml"),
        r#"post-start = "echo PR-CONFIG-HOOK-RAN > {{ repo_path }}/pr-hook-marker.txt""#,
    )
    .unwrap();
    repo.run_git(&["add", "pr-file.txt", ".config/wt.toml"]);
    repo.run_git(&["commit", "-m", "PR commit with hook config"]);

    let sha = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["rev-parse", "HEAD"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&["push", "origin", &format!("{sha}:refs/pull/42/head")]);
    // Back on `main`, which never had `.config/wt.toml` committed — `pr-source`
    // branched off before that commit, so `git checkout main` drops it from the
    // working tree, leaving the local repo with no project config.
    repo.run_git(&["checkout", "main"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{bare_url}.insteadOf"),
        "https://github.com/owner/test-repo.git",
    ]);

    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;
    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    // (a) Without `--yes`: the approval prompt prints the PR's command template
    // to stderr, then bails (stdin is not a TTY in tests). No worktree, no hook.
    let mut cmd = repo.wt_command();
    cmd.args(["switch", "pr:42"]);
    configure_mock_cli_env(&mut cmd, &mock_bin);
    let output = cmd.output().expect("wt switch pr:42 should run");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("PR-CONFIG-HOOK-RAN"),
        "approval prompt should list the PR ref's post-start hook; stderr:\n{stderr}"
    );
    assert!(
        !output.status.success(),
        "non-interactive approval should bail without running the hook"
    );
    assert!(
        !repo.root_path().join("pr-hook-marker.txt").exists(),
        "a declined approval must not run the hook"
    );

    // (b) With `--yes`: the PR's `post-start` runs against the new worktree.
    let mut cmd = repo.wt_command();
    cmd.args(["switch", "pr:42", "--yes"]);
    configure_mock_cli_env(&mut cmd, &mock_bin);
    let output = cmd.output().expect("wt switch pr:42 --yes should run");
    assert!(
        output.status.success(),
        "wt switch pr:42 --yes failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    let marker = repo.root_path().join("pr-hook-marker.txt");
    wait_for_file_content(&marker);
    assert_eq!(
        fs::read_to_string(&marker).unwrap().trim(),
        "PR-CONFIG-HOOK-RAN",
        "post-start should run with the PR ref's config"
    );
}

/// Test fork PR when origin points to fork (no remote for base repo)
///
/// User scenario:
/// 1. User forked upstream-owner/repo to contributor/repo
/// 2. User cloned their fork, so origin points to contributor/repo
/// 3. User tries to checkout PR from upstream-owner/repo
/// 4. No remote exists for the base repo -> error with hint to add upstream
#[rstest]
fn test_switch_pr_fork_no_upstream_remote(#[from(repo_with_remote)] repo: TestRepo) {
    // Set origin to point to the FORK (contributor's repo), not the base repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/contributor/test-repo.git",
    ]);

    // gh api response says base.repo is owner/test-repo (the upstream)
    // but origin points to contributor/test-repo (the fork)
    // So find_remote_for_repo("owner", "test-repo") will fail
    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_fork_no_upstream", cmd);
    });
}

/// Test fork PR when origin points to fork but `gh repo set-default` is configured
///
/// User scenario:
/// 1. User forked owner/test-repo to contributor/test-repo
/// 2. User cloned their fork, so origin = contributor/test-repo
/// 3. User added upstream remote pointing to owner/test-repo
/// 4. User ran `gh repo set-default owner/test-repo`
/// 5. User runs `wt switch pr:42` where the PR is on owner/test-repo
/// 6. Worktrunk queries the gh default repo instead of origin → success
#[rstest]
fn test_switch_pr_fork_gh_default_repo(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a PR ref on the remote
    repo.run_git(&["checkout", "-b", "pr-source"]);
    fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
    repo.run_git(&["add", "pr-file.txt"]);
    repo.run_git(&["commit", "-m", "PR commit"]);

    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();

    repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
    repo.run_git(&["checkout", "main"]);

    // Get the bare remote's actual URL before modifying remotes
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Set origin to the FORK (contributor's repo) — this is the bug scenario
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/contributor/test-repo.git",
    ]);

    // Add upstream remote pointing to the parent repo
    repo.run_git(&[
        "remote",
        "add",
        "upstream",
        "https://github.com/owner/test-repo.git",
    ]);

    // Redirect both GitHub URLs to the local bare remote for git operations
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/contributor/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        "--add",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    // Cross-repo PR: head is contributor's fork, base is owner's repo
    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    fs::write(mock_bin.join("pr_response.json"), gh_response).unwrap();

    MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command(
            "repo set-default --view",
            MockResponse::output("owner/test-repo\n"),
        )
        .command("api", MockResponse::file("pr_response.json"))
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_fork_gh_default", cmd);
    });
}

/// Test error when PR is not found
#[rstest]
fn test_switch_pr_not_found(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    // Copy mock-stub binary as "gh"
    copy_mock_binary(&mock_bin, "gh");

    // Configure gh api to return error for PR not found (JSON on stdout, human-readable on stderr)
    MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command(
            "api",
            MockResponse::output(r#"{"message":"Not Found","status":"404"}"#)
                .with_stderr("gh: Not Found (HTTP 404)")
                .with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:9999"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_not_found", cmd);
    });
}

/// Test error when fork was deleted (head.repo is null)
#[rstest]
fn test_switch_pr_deleted_fork(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    // gh api repos/{owner}/{repo}/pulls/{number} format with null head.repo
    // This happens when the fork that the PR was opened from has been deleted
    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": null
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_deleted_fork", cmd);
    });
}

/// Test that --base flag conflicts with pr: syntax
#[rstest]
fn test_switch_pr_base_conflict(repo: TestRepo) {
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--base", "main", "pr:101"], None);
        assert_cmd_snapshot!("switch_pr_base_conflict", cmd);
    });
}

/// `wt switch --create X --base pr:N` resolves the PR to its head branch for
/// a same-repo PR, fetching the branch so it's usable as the base.
#[rstest]
fn test_switch_base_pr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
    // Create the PR source branch on the remote so we have something to fetch
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Rewrite origin so find_remote_for_repo matches owner/test-repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    let gh_response = r#"{
        "title": "Fix authentication bug in login flow",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/101"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(
            &repo,
            "switch",
            &[
                "--create",
                "feat/visual-tweaks",
                "--base",
                "pr:101",
                "--no-cd",
            ],
            None,
        );
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_base_pr_same_repo", cmd);
    });
}

/// Reproduction for #2497: `wt switch --create X --base pr:N` should set the
/// new local branch's upstream to the PR's source branch on the remote, so
/// `git push` from the new worktree pushes back to the PR rather than failing
/// with "no upstream branch".
#[rstest]
fn test_switch_base_pr_sets_upstream(#[from(repo_with_remote)] mut repo: TestRepo) {
    let pr_source_branch = "feature-this-is-a-very-long-pr-source-branch-name";
    repo.add_worktree(pr_source_branch);
    repo.run_git(&["push", "origin", pr_source_branch]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    let gh_response = format!(
        r#"{{
        "title": "Some PR title",
        "user": {{"login": "alice"}},
        "state": "open",
        "draft": false,
        "head": {{
            "ref": "{pr_source_branch}",
            "repo": {{"name": "test-repo", "owner": {{"login": "owner"}}}}
        }},
        "base": {{
            "ref": "main",
            "repo": {{"name": "test-repo", "owner": {{"login": "owner"}}}}
        }},
        "html_url": "https://github.com/owner/test-repo/pull/2648"
    }}"#
    );

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(&gh_response));

    let mut cmd = repo.wt_command();
    cmd.args([
        "switch", "--create", "swa-65", "--base", "pr:2648", "--no-cd",
    ]);
    configure_mock_cli_env(&mut cmd, &mock_bin);
    let status = cmd.status().expect("wt switch should run");
    assert!(status.success(), "wt switch failed: {:?}", status);

    let remote = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "--get", "branch.swa-65.remote"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    let merge = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "--get", "branch.swa-65.merge"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    assert_eq!(
        remote, "origin",
        "branch.swa-65.remote should be set so `git push` knows where to push"
    );
    assert_eq!(
        merge,
        format!("refs/heads/{pr_source_branch}"),
        "branch.swa-65.merge should target the PR's source branch on the remote"
    );
}

/// `wt switch --create X --base pr:N` resolves a fork PR to its head commit
/// SHA via refs/pull/N/head without creating a tracking branch.
#[rstest]
fn test_switch_base_pr_fork(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a PR head commit and push it as refs/pull/42/head on the remote
    repo.run_git(&["checkout", "-b", "pr-source"]);
    fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
    repo.run_git(&["add", "pr-file.txt"]);
    repo.run_git(&["commit", "-m", "PR commit"]);
    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();
    repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
    repo.run_git(&["checkout", "main"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    // head.repo differs from base.repo → fork PR
    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let mut settings = setup_snapshot_settings(&repo);
    // Fork base resolves to a commit SHA (no tracking branch created). Mask it
    // so the snapshot is stable across the test repo's non-deterministic SHAs.
    // Can't use \b because ANSI escape characters aren't word boundaries.
    settings.add_filter(r"[0-9a-f]{40}", "[SHA]");
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(
            &repo,
            "switch",
            &["--create", "my-work", "--base", "pr:42", "--no-cd"],
            None,
        );
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_base_pr_fork", cmd);
    });

    // The PR branch name must NOT have been created as a local branch — we
    // just based `my-work` on the PR's head commit.
    let branches = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["branch", "--list"])
            .run()
            .unwrap()
            .stdout,
    )
    .into_owned();
    assert!(
        !branches.contains("feature-fix"),
        "fork PR head should not produce a local tracking branch: {branches}"
    );
    assert!(
        !branches.contains("contributor/feature-fix"),
        "prefixed fork PR branch should not be created: {branches}"
    );
}

/// `wt switch --create X --base mr:N` resolves a same-repo MR to its source
/// branch, fetching it so the base is usable.
#[rstest]
fn test_switch_base_mr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://gitlab.com/owner/test-repo.git",
    ]);

    let glab_response = r#"{
        "title": "Fix authentication bug in login flow",
        "author": {"username": "alice"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-auth",
        "source_project_id": 123,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(
            &repo,
            "switch",
            &["--create", "feat/follow-up", "--base", "mr:101", "--no-cd"],
            None,
        );
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_base_mr_same_repo", cmd);
    });
}

/// `--base pr:N` is ignored when `--create` is absent: we warn and do NOT
/// hit the network. `gh` is intentionally not mocked — if the resolver ran,
/// the command would fail with "gh: command not found".
#[rstest]
fn test_switch_base_pr_without_create(#[from(repo_with_remote)] mut repo: TestRepo) {
    // A branch that already exists so `wt switch` can succeed without --create
    repo.add_worktree("existing");

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(
            &repo,
            "switch",
            &["existing", "--base", "pr:101", "--no-cd"],
            None,
        );
        assert_cmd_snapshot!("switch_base_pr_without_create", cmd);
    });
}

/// Test fork PR where branch already exists and tracks same PR (should reuse)
#[rstest]
fn test_switch_pr_fork_existing_same_pr(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    // First, manually create the branch with correct tracking config
    // Branch name matches headRefName (no owner prefix) so git push works
    let branch_name = "feature-fix";
    repo.run_git(&["branch", branch_name, "main"]);
    repo.run_git(&[
        "config",
        &format!("branch.{}.remote", branch_name),
        "origin",
    ]);
    repo.run_git(&[
        "config",
        &format!("branch.{}.merge", branch_name),
        "refs/pull/42/head",
    ]);

    // gh api repos/{owner}/{repo}/pulls/{number} format
    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_fork_existing_same_pr", cmd);
    });
}

/// Test fork PR where branch already exists but tracks different PR
/// Uses prefixed branch name `contributor/feature-fix` to avoid conflict
#[rstest]
fn test_switch_pr_fork_existing_different_pr(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    // Create a PR ref on the remote
    repo.run_git(&["checkout", "-b", "pr-source"]);
    fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
    repo.run_git(&["add", "pr-file.txt"]);
    repo.run_git(&["commit", "-m", "PR commit"]);
    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();
    repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
    repo.run_git(&["checkout", "main"]);

    // Create the branch with tracking config for a DIFFERENT PR
    let branch_name = "feature-fix";
    repo.run_git(&["branch", branch_name, "main"]);
    repo.run_git(&[
        "config",
        &format!("branch.{}.remote", branch_name),
        "origin",
    ]);
    repo.run_git(&[
        "config",
        &format!("branch.{}.merge", branch_name),
        "refs/pull/99/head", // Different PR!
    ]);

    // Set up GitHub URL and redirect (like test_switch_pr_fork)
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    // gh api repos/{owner}/{repo}/pulls/{number} format
    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_fork_existing_different_pr", cmd);
    });
}

/// Test fork PR where branch already exists with the same PR ref path but the
/// wrong remote configured.
///
/// This branch should not be reused because push/pull would be wired to the
/// wrong repository.
#[rstest]
fn test_switch_pr_fork_existing_same_pr_wrong_remote(#[from(repo_with_remote)] mut repo: TestRepo) {
    set_github_remote_url(&repo);
    repo.setup_custom_remote("fork", "main");

    // Create a PR ref on the real PR remote.
    repo.run_git(&["checkout", "-b", "pr-source"]);
    fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
    repo.run_git(&["add", "pr-file.txt"]);
    repo.run_git(&["commit", "-m", "PR commit"]);
    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();
    repo.run_git(&["push", "origin", &format!("{sha}:refs/pull/42/head")]);
    repo.run_git(&["checkout", "main"]);

    // Create the branch with a stale tracking configuration pointing at a
    // different remote that happens to use the same PR ref path.
    let branch_name = "feature-fix";
    repo.run_git(&["branch", branch_name, "main"]);
    repo.run_git(&["config", &format!("branch.{branch_name}.remote"), "fork"]);
    repo.run_git(&[
        "config",
        &format!("branch.{branch_name}.merge"),
        "refs/pull/42/head",
    ]);

    // Set up GitHub URL and redirect (like test_switch_pr_fork).
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{bare_url}.insteadOf"),
        "https://github.com/owner/test-repo.git",
    ]);

    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));
    let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
    configure_mock_cli_env(&mut cmd, &mock_bin);
    let output = cmd.output().unwrap();
    assert!(output.status.success(), "switch should succeed");

    let stderr = String::from_utf8_lossy(&output.stderr)
        .ansi_strip()
        .into_owned();
    assert!(
        stderr.contains("Using prefixed branch name contributor/feature-fix due to name conflict"),
        "expected prefixed branch warning when existing branch tracks the PR on the wrong remote\nstderr:\n{stderr}",
    );
}

/// Test fork PR where branch exists but has no tracking config
/// Uses prefixed branch name `contributor/feature-fix` to avoid conflict
#[rstest]
fn test_switch_pr_fork_existing_no_tracking(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    // Create a PR ref on the remote
    repo.run_git(&["checkout", "-b", "pr-source"]);
    fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
    repo.run_git(&["add", "pr-file.txt"]);
    repo.run_git(&["commit", "-m", "PR commit"]);
    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();
    repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
    repo.run_git(&["checkout", "main"]);

    // Create the branch without any tracking config
    let branch_name = "feature-fix";
    repo.run_git(&["branch", branch_name, "main"]);
    // No config set - branch exists but doesn't track anything

    // Set up GitHub URL and redirect (like test_switch_pr_fork)
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    // gh api repos/{owner}/{repo}/pulls/{number} format
    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_fork_existing_no_tracking", cmd);
    });
}

/// Test fork PR where prefixed branch already exists and tracks the same PR
/// Should reuse the existing prefixed branch
#[rstest]
fn test_switch_pr_fork_prefixed_exists_same_pr(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    // Create the unprefixed branch (simulating existing local branch)
    repo.run_git(&["branch", "feature-fix", "main"]);

    // Create the prefixed branch with tracking config for THIS PR
    let prefixed_branch = "contributor/feature-fix";
    repo.run_git(&["branch", prefixed_branch, "main"]);
    repo.run_git(&[
        "config",
        &format!("branch.{}.remote", prefixed_branch),
        "origin",
    ]);
    repo.run_git(&[
        "config",
        &format!("branch.{}.merge", prefixed_branch),
        "refs/pull/42/head", // Same PR
    ]);

    // Create the worktree for the prefixed branch
    // Use "repo." prefix to match the test repo's directory naming convention
    let worktree_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("repo.contributor-feature-fix");
    repo.run_git(&[
        "worktree",
        "add",
        worktree_path.to_str().unwrap(),
        prefixed_branch,
    ]);

    // Set up GitHub URL
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_fork_prefixed_exists_same_pr", cmd);
    });
}

/// Test fork PR where prefixed branch exists but tracks different PR (should error)
#[rstest]
fn test_switch_pr_fork_prefixed_exists_different_pr(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    // Create the unprefixed branch (simulating existing local branch)
    repo.run_git(&["branch", "feature-fix", "main"]);

    // Create the prefixed branch with tracking config for a DIFFERENT PR
    let prefixed_branch = "contributor/feature-fix";
    repo.run_git(&["branch", prefixed_branch, "main"]);
    repo.run_git(&[
        "config",
        &format!("branch.{}.remote", prefixed_branch),
        "origin",
    ]);
    repo.run_git(&[
        "config",
        &format!("branch.{}.merge", prefixed_branch),
        "refs/pull/99/head", // Different PR!
    ]);

    // Set up GitHub URL
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://github.com/owner/test-repo.git",
    ]);

    let gh_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/42"
    }"#;

    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_fork_prefixed_exists_different_pr", cmd);
    });
}

/// Test pr: when gh is not authenticated
#[rstest]
fn test_switch_pr_not_authenticated(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "gh");

    // Configure gh api to return auth error (JSON on stdout, human-readable on stderr)
    MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command(
            "api",
            MockResponse::output(r#"{"message":"Requires authentication","status":"401"}"#)
                .with_stderr("gh: Requires authentication (HTTP 401)")
                .with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_not_authenticated", cmd);
    });
}

/// Test pr: when hitting GitHub rate limit
#[rstest]
fn test_switch_pr_rate_limit(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "gh");

    // Configure gh api to return rate limit error (JSON on stdout, human-readable on stderr)
    MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command(
            "api",
            MockResponse::output(
                r#"{"message":"API rate limit exceeded for user","status":"403"}"#,
            )
            .with_stderr("gh: API rate limit exceeded (HTTP 403)")
            .with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_rate_limit", cmd);
    });
}

/// Test pr: when gh returns invalid JSON
#[rstest]
fn test_switch_pr_invalid_json(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "gh");

    // Configure gh api to return invalid JSON
    MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command("api", MockResponse::output("not valid json {{{"))
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_invalid_json", cmd);
    });
}

/// Test pr: when network error occurs
#[rstest]
fn test_switch_pr_network_error(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "gh");

    // Configure gh api to return network error (no JSON, just stderr for network failures)
    MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command(
            "api",
            MockResponse::stderr("connection refused: network is unreachable").with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_network_error", cmd);
    });
}

/// Test pr: when gh returns unknown error
#[rstest]
fn test_switch_pr_unknown_error(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "gh");

    // Configure gh api to return an unrecognized multi-line error
    // (realistic errors from gh often include context on multiple lines)
    let error_message = "error: unexpected API response\n\
                         code: 500\n\
                         message: Internal server error";
    MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command("api", MockResponse::stderr(error_message).with_exit_code(1))
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_unknown_error", cmd);
    });
}

/// Test pr: when PR has empty branch name
#[rstest]
fn test_switch_pr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {
    set_github_remote_url(&repo);
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "gh");

    // Configure gh to return valid JSON but with empty branch name (head.ref is "")
    let gh_response = r#"{
        "title": "PR with empty branch",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://github.com/owner/test-repo/pull/101"
    }"#;

    MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command("api", MockResponse::output(gh_response))
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_empty_branch", cmd);
    });
}

// ============================================================================
// PR Syntax Tests on Gitea remotes
//
// These exercise `pr:<N>` against a Gitea remote (host detection picks the
// `tea` provider; provider selection is in choose_pr_provider). The remote
// URLs use `gitea.example.com` so `GitRemoteUrl::is_gitea()` matches and the
// ambiguous fallback is skipped — the runtime calls only the mock `tea`,
// not real `gh`.
// ============================================================================

/// Helper to set up mock tea for Gitea PR tests with custom response.
///
/// Returns the path to the mock bin directory; pass it to
/// `configure_mock_cli_env`.
fn setup_mock_tea(repo: &TestRepo, tea_response: Option<&str>) -> std::path::PathBuf {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "tea");

    if let Some(response) = tea_response {
        fs::write(mock_bin.join("tea_pr_response.json"), response).unwrap();

        MockConfig::new("tea")
            .version("tea version development (mock)")
            .command("api", MockResponse::file("tea_pr_response.json"))
            .command("_default", MockResponse::exit(1))
            .write(&mock_bin);
    }

    mock_bin
}

#[rstest]
fn test_switch_pr_gitea_create_conflict(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let tea_response = r#"{
        "title": "Fix authentication bug in login flow",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "label": "feature-auth",
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "label": "main",
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://gitea.example.com/owner/test-repo/pulls/101"
    }"#;

    let mock_bin = setup_mock_tea(&repo, Some(tea_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_create_conflict", cmd);
    });
}

#[rstest]
fn test_switch_pr_gitea_base_conflict(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--base", "main", "pr:101"], None);
        assert_cmd_snapshot!("switch_pr_gitea_base_conflict", cmd);
    });
}

#[rstest]
fn test_switch_pr_gitea_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let tea_response = r#"{
        "title": "Fix authentication bug in login flow",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "label": "feature-auth",
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "label": "main",
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://gitea.example.com/owner/test-repo/pulls/101"
    }"#;

    let mock_bin = setup_mock_tea(&repo, Some(tea_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_same_repo", cmd);
    });
}

#[rstest]
fn test_switch_pr_gitea_fork(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&["checkout", "-b", "gitea-pr-source"]);
    fs::write(
        repo.root_path().join("gitea-pr-file.txt"),
        "Gitea PR content",
    )
    .unwrap();
    repo.run_git(&["add", "gitea-pr-file.txt"]);
    repo.run_git(&["commit", "-m", "Gitea PR commit"]);

    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();

    repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
    repo.run_git(&["checkout", "main"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let tea_response = r#"{
        "title": "Add feature fix for edge case",
        "user": {"login": "contributor"},
        "state": "open",
        "draft": false,
        "head": {
            "label": "contributor:feature-fix",
            "ref": "feature-fix",
            "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
        },
        "base": {
            "label": "main",
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://gitea.example.com/owner/test-repo/pulls/42"
    }"#;

    let mock_bin = setup_mock_tea(&repo, Some(tea_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_fork", cmd);
    });
}

#[rstest]
fn test_switch_pr_gitea_not_found(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "tea");

    MockConfig::new("tea")
        .version("tea version development (mock)")
        .command(
            "api",
            MockResponse::output(r#"{"message":"404 Not found"}"#).with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:9999"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_not_found", cmd);
    });
}

#[rstest]
fn test_switch_pr_gitea_tea_not_installed(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let Some(minimal_bin) = setup_minimal_bin_without_cli(&repo) else {
        eprintln!("Skipping test: symlinks not available on this system");
        return;
    };

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_cli_not_installed_env(&mut cmd, &minimal_bin);
        assert_cmd_snapshot!("switch_pr_gitea_tea_not_installed", cmd);
    });
}

/// `forge.platform = "gitea"` selects the Gitea provider directly, even when
/// the remote URL doesn't look like Gitea (no ambiguous two-provider fallback).
#[rstest]
fn test_switch_pr_gitea_forge_platform(#[from(repo_with_remote)] repo: TestRepo) {
    // Non-Gitea-looking URL — without `forge.platform` set we'd hit the ambiguous path.
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://git.internal.example.com/owner/test-repo.git",
    ]);

    let project_config = repo.root_path().join(".config/wt.toml");
    fs::create_dir_all(project_config.parent().unwrap()).unwrap();
    fs::write(&project_config, "[forge]\nplatform = \"gitea\"\n").unwrap();

    let tea_response = r#"{
        "title": "Override test",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "label": "feature-auth",
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "label": "main",
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://git.internal.example.com/owner/test-repo/pulls/101"
    }"#;

    let mock_bin = setup_mock_tea(&repo, Some(tea_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_forge_platform", cmd);
    });
}

/// `forge.platform = "gitlab"` with `pr:` should bail and tell the user to use
/// `mr:` instead — the platform is incompatible with the syntax.
#[rstest]
fn test_switch_pr_forge_platform_gitlab_rejects_pr(#[from(repo_with_remote)] repo: TestRepo) {
    let project_config = repo.root_path().join(".config/wt.toml");
    fs::create_dir_all(project_config.parent().unwrap()).unwrap();
    fs::write(&project_config, "[forge]\nplatform = \"gitlab\"\n").unwrap();

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        assert_cmd_snapshot!("switch_pr_forge_platform_gitlab", cmd);
    });
}

/// An invalid `forge.platform` value bails with a clear error listing the
/// accepted values, rather than silently routing somewhere via fall-through.
#[rstest]
fn test_switch_pr_forge_platform_invalid_bails(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);

    let project_config = repo.root_path().join(".config/wt.toml");
    fs::create_dir_all(project_config.parent().unwrap()).unwrap();
    fs::write(&project_config, "[forge]\nplatform = \"bitbucket\"\n").unwrap();

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        assert_cmd_snapshot!("switch_pr_forge_platform_invalid_bails", cmd);
    });
}

/// With no parseable remote URL, dispatch defaults to GitHub. Without `gh`
/// installed the GitHub provider bails with the install hint — a single,
/// readable error rather than a wrapped two-provider message.
#[rstest]
fn test_switch_pr_no_remote_defaults_to_github(repo: TestRepo) {
    let Some(minimal_bin) = setup_minimal_bin_without_cli(&repo) else {
        eprintln!("Skipping test: symlinks not available on this system");
        return;
    };

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_cli_not_installed_env(&mut cmd, &minimal_bin);
        assert_cmd_snapshot!("switch_pr_no_remote_defaults_to_github", cmd);
    });
}

/// Detected GitLab remote with `pr:` should bail and tell the user to use `mr:`.
#[rstest]
fn test_switch_pr_gitlab_remote_rejects_pr(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/owner/test-repo.git",
    ]);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        assert_cmd_snapshot!("switch_pr_gitlab_remote", cmd);
    });
}

/// Self-hosted forge whose hostname doesn't match any URL detection rule, but
/// `tea` has a login configured for it (via `tea login add`) — dispatch
/// inspects tea's config file and routes to Gitea.
#[rstest]
fn test_switch_pr_self_hosted_tea_authed_dispatches_to_gitea(
    #[from(repo_with_remote)] repo: TestRepo,
) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://forge.selfhosted.test/owner/test-repo.git",
    ]);

    let tea_config_dir = repo.home_path().join(".config").join("tea");
    fs::create_dir_all(&tea_config_dir).unwrap();
    fs::write(
        tea_config_dir.join("config.yml"),
        "logins:\n  - name: selfhosted\n    url: https://forge.selfhosted.test\n    default: true\n",
    )
    .unwrap();

    let tea_response = r#"{
        "title": "Routed via tea config",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "label": "feature-auth",
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "label": "main",
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://forge.selfhosted.test/owner/test-repo/pulls/101"
    }"#;
    let mock_bin = setup_mock_tea(&repo, Some(tea_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_self_hosted_tea_authed", cmd);
    });
}

/// Self-hosted forge with a non-distinctive hostname (`forge.example.com`)
/// and neither `gh` nor `tea` configured for it — dispatch defaults to
/// GitHub. The mock `gh api` succeeds, so the PR is checked out and the
/// user never sees a wrapped error.
#[rstest]
fn test_switch_pr_self_hosted_defaults_to_github(#[from(repo_with_remote)] mut repo: TestRepo) {
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://forge.example.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://forge.example.com/owner/test-repo.git",
    ]);

    let gh_response = r#"{
        "title": "Self-hosted defaults to gh",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "ref": "feature-auth",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://forge.example.com/owner/test-repo/pull/101"
    }"#;
    let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_self_hosted_defaults_to_github", cmd);
    });
}

/// Gitea API returns malformed JSON — covers the JSON parse error path
/// in `gitea::fetch_pr_info`.
#[rstest]
fn test_switch_pr_gitea_invalid_json(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let mock_bin = setup_mock_tea(&repo, Some("not json {"));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_invalid_json", cmd);
    });
}

/// Gitea API returns a 5xx-style generic error (non-404/401/403) — exercises
/// the generic `cli_api_error` fallback in `gitea::fetch_pr_info`.
#[rstest]
fn test_switch_pr_gitea_server_error(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    copy_mock_binary(&mock_bin, "tea");

    MockConfig::new("tea")
        .version("tea version development (mock)")
        .command(
            "api",
            MockResponse::output(r#"{"message":"500 Internal Server Error"}"#)
                .with_stderr("tea: server error\n")
                .with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_server_error", cmd);
    });
}

/// Gitea API returns a PR with no source branch (label and ref both empty)
/// — exercises the `extract_source_branch` failure path in `fetch_pr_info`.
#[rstest]
fn test_switch_pr_gitea_no_source_branch(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let tea_response = r#"{
        "title": "Stuck PR",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "label": "",
            "ref": "",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "base": {
            "label": "main",
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://gitea.example.com/owner/test-repo/pulls/101"
    }"#;

    let mock_bin = setup_mock_tea(&repo, Some(tea_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_no_source_branch", cmd);
    });
}

/// Gitea API returns a PR whose head repo is null (the fork has been deleted).
/// Covers the `head_repo` `ok_or_else` path in `gitea::fetch_pr_info`.
#[rstest]
fn test_switch_pr_gitea_deleted_fork(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let tea_response = r#"{
        "title": "Deleted fork PR",
        "user": {"login": "alice"},
        "state": "open",
        "draft": false,
        "head": {
            "label": "alice:gone",
            "ref": "gone",
            "repo": null
        },
        "base": {
            "label": "main",
            "ref": "main",
            "repo": {"name": "test-repo", "owner": {"login": "owner"}}
        },
        "html_url": "https://gitea.example.com/owner/test-repo/pulls/101"
    }"#;

    let mock_bin = setup_mock_tea(&repo, Some(tea_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_deleted_fork", cmd);
    });
}

/// Gitea CLI returning 401/Unauthorized hits the dedicated bail message
/// (covers the auth-error branch in `gitea::fetch_pr_info`).
#[rstest]
fn test_switch_pr_gitea_unauthorized(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    copy_mock_binary(&mock_bin, "tea");

    MockConfig::new("tea")
        .version("tea version development (mock)")
        .command(
            "api",
            MockResponse::output(r#"{"message":"401 Unauthorized"}"#).with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_unauthorized", cmd);
    });
}

/// Gitea CLI returning 403/Forbidden hits the dedicated bail message
/// (covers the forbidden branch in `gitea::fetch_pr_info`).
#[rstest]
fn test_switch_pr_gitea_forbidden(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    copy_mock_binary(&mock_bin, "tea");

    MockConfig::new("tea")
        .version("tea version development (mock)")
        .command(
            "api",
            MockResponse::output(r#"{"message":"403 Forbidden"}"#).with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_gitea_forbidden", cmd);
    });
}

// ============================================================================
// PR Syntax Tests on Azure DevOps remotes
//
// These exercise `pr:<N>` against an Azure DevOps remote. Host detection picks
// the `az` provider (provider selection is in choose_pr_provider). The remote
// URLs use `dev.azure.com` / `*.visualstudio.com` so `GitRemoteUrl::is_azure_devops()`
// matches and the ambiguous fallback is skipped — the runtime calls only the
// mock `az`, not real `gh`.
// ============================================================================

/// Helper to set up mock `az` for Azure DevOps PR tests with a custom
/// `az repos pr show` response.
///
/// Returns the path to the mock bin directory; pass it to
/// `configure_mock_cli_env`.
fn setup_mock_az(repo: &TestRepo, az_pr_response: Option<&str>) -> std::path::PathBuf {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "az");

    if let Some(response) = az_pr_response {
        fs::write(mock_bin.join("az_pr_response.json"), response).unwrap();

        MockConfig::new("az")
            .version("azure-cli 2.60.0 (mock)")
            .command("repos pr show", MockResponse::file("az_pr_response.json"))
            .command("_default", MockResponse::exit(1))
            .write(&mock_bin);
    }

    mock_bin
}

/// Point `origin` at an Azure DevOps URL and redirect that URL to the local
/// bare remote via `url.insteadOf`, so `git fetch` still works.
fn set_azure_remote_url(repo: &TestRepo, azure_url: &str) {
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    repo.run_git(&["remote", "set-url", "origin", azure_url]);
    repo.run_git(&["config", &format!("url.{}.insteadOf", bare_url), azure_url]);
}

#[rstest]
fn test_switch_pr_azure_create_conflict(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);

    let az_response = r#"{
        "title": "Fix authentication bug in login flow",
        "createdBy": {"uniqueName": "alice@example.com"},
        "status": "active",
        "isDraft": false,
        "sourceRefName": "refs/heads/feature-auth",
        "repository": {
            "name": "test-repo",
            "project": {"name": "myproject"},
            "webUrl": "https://dev.azure.com/myorg/myproject/_git/test-repo"
        },
        "forkSource": null
    }"#;

    let mock_bin = setup_mock_az(&repo, Some(az_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_create_conflict", cmd);
    });
}

#[rstest]
fn test_switch_pr_azure_base_conflict(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--base", "main", "pr:101"], None);
        assert_cmd_snapshot!("switch_pr_azure_base_conflict", cmd);
    });
}

#[rstest]
fn test_switch_pr_azure_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    set_azure_remote_url(
        &repo,
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    );

    let az_response = r#"{
        "title": "Fix authentication bug in login flow",
        "createdBy": {"uniqueName": "alice@example.com"},
        "status": "active",
        "isDraft": false,
        "sourceRefName": "refs/heads/feature-auth",
        "repository": {
            "name": "test-repo",
            "project": {"name": "myproject"},
            "webUrl": "https://dev.azure.com/myorg/myproject/_git/test-repo"
        },
        "forkSource": null
    }"#;

    let mock_bin = setup_mock_az(&repo, Some(az_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_same_repo", cmd);
    });
}

/// Legacy `*.visualstudio.com` remotes encode the org in the hostname — exercises
/// the `*.visualstudio.com` branches of the Azure URL helpers end to end.
#[rstest]
fn test_switch_pr_azure_visualstudio_host(#[from(repo_with_remote)] mut repo: TestRepo) {
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    set_azure_remote_url(
        &repo,
        "https://myorg.visualstudio.com/myproject/_git/test-repo",
    );

    let az_response = r#"{
        "title": "Fix authentication bug in login flow",
        "createdBy": {"uniqueName": "alice@example.com"},
        "status": "active",
        "isDraft": false,
        "sourceRefName": "refs/heads/feature-auth",
        "repository": {
            "name": "test-repo",
            "project": {"name": "myproject"},
            "webUrl": "https://myorg.visualstudio.com/myproject/_git/test-repo"
        },
        "forkSource": null
    }"#;

    let mock_bin = setup_mock_az(&repo, Some(az_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_visualstudio_host", cmd);
    });
}

#[rstest]
fn test_switch_pr_azure_fork(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&["checkout", "-b", "azure-pr-source"]);
    fs::write(
        repo.root_path().join("azure-pr-file.txt"),
        "Azure PR content",
    )
    .unwrap();
    repo.run_git(&["add", "azure-pr-file.txt"]);
    repo.run_git(&["commit", "-m", "Azure PR commit"]);

    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();

    repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
    repo.run_git(&["checkout", "main"]);

    set_azure_remote_url(
        &repo,
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    );

    let az_response = r#"{
        "title": "Add feature fix for edge case",
        "createdBy": {"uniqueName": "contributor@example.com"},
        "status": "active",
        "isDraft": false,
        "sourceRefName": "refs/heads/feature-fix",
        "repository": {
            "name": "test-repo",
            "project": {"name": "myproject"},
            "webUrl": "https://dev.azure.com/myorg/myproject/_git/test-repo"
        },
        "forkSource": {
            "repository": {
                "remoteUrl": "https://dev.azure.com/myorg/myproject/_git/test-repo-fork",
                "sshUrl": "git@ssh.dev.azure.com:v3/myorg/myproject/test-repo-fork"
            }
        }
    }"#;

    let mock_bin = setup_mock_az(&repo, Some(az_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_fork", cmd);
    });
}

/// `az repos pr show` reporting "does not exist" hits the dedicated
/// not-found bail in `azure::fetch_pr_info`.
#[rstest]
fn test_switch_pr_azure_not_found(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    copy_mock_binary(&mock_bin, "az");

    MockConfig::new("az")
        .version("azure-cli 2.60.0 (mock)")
        .command(
            "repos pr show",
            MockResponse::stderr(
                "TF401174: The requested pull request was not found, or it does not exist.\n",
            )
            .with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:9999"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_not_found", cmd);
    });
}

/// `az` not installed: with an Azure remote, dispatch routes to the Azure
/// provider, which bails with the install hint when `az` isn't on PATH.
#[rstest]
fn test_switch_pr_azure_az_not_installed(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);

    let Some(minimal_bin) = setup_minimal_bin_without_cli(&repo) else {
        eprintln!("Skipping test: symlinks not available on this system");
        return;
    };

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_cli_not_installed_env(&mut cmd, &minimal_bin);
        assert_cmd_snapshot!("switch_pr_azure_az_not_installed", cmd);
    });
}

/// `forge.platform = "azure-devops"` selects the Azure provider directly, even
/// when the remote URL doesn't look like Azure DevOps.
#[rstest]
fn test_switch_pr_azure_forge_platform(#[from(repo_with_remote)] repo: TestRepo) {
    // Non-Azure-looking URL — without `forge.platform` set we'd default to GitHub.
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://git.internal.example.com/owner/test-repo.git",
    ]);

    let project_config = repo.root_path().join(".config/wt.toml");
    fs::create_dir_all(project_config.parent().unwrap()).unwrap();
    fs::write(&project_config, "[forge]\nplatform = \"azure-devops\"\n").unwrap();

    let az_response = r#"{
        "title": "Override test",
        "createdBy": {"uniqueName": "alice@example.com"},
        "status": "active",
        "isDraft": false,
        "sourceRefName": "refs/heads/feature-auth",
        "repository": {
            "name": "test-repo",
            "project": {"name": "myproject"},
            "webUrl": "https://dev.azure.com/myorg/myproject/_git/test-repo"
        },
        "forkSource": null
    }"#;

    let mock_bin = setup_mock_az(&repo, Some(az_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_forge_platform", cmd);
    });
}

/// `az repos pr show` returning malformed JSON hits the parse-error path
/// in `azure::fetch_pr_info`.
#[rstest]
fn test_switch_pr_azure_invalid_json(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);

    let mock_bin = setup_mock_az(&repo, Some("not json {"));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_invalid_json", cmd);
    });
}

/// `az repos pr show` failing with a generic (non-auth, non-not-found) error
/// exercises the `cli_api_error` fallback in `azure::fetch_pr_info`.
#[rstest]
fn test_switch_pr_azure_server_error(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    copy_mock_binary(&mock_bin, "az");

    MockConfig::new("az")
        .version("azure-cli 2.60.0 (mock)")
        .command(
            "repos pr show",
            MockResponse::stderr("az: TF400898: An internal error occurred.\n").with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_server_error", cmd);
    });
}

/// `az repos pr show` reporting a login error hits the dedicated auth bail.
#[rstest]
fn test_switch_pr_azure_auth_error(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    copy_mock_binary(&mock_bin, "az");

    MockConfig::new("az")
        .version("azure-cli 2.60.0 (mock)")
        .command(
            "repos pr show",
            MockResponse::stderr("Please run 'az login' to setup account.\n").with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_auth_error", cmd);
    });
}

/// `az repos pr show` failing because the `azure-devops` extension is missing
/// hits the dedicated extension-install bail.
#[rstest]
fn test_switch_pr_azure_extension_not_installed(#[from(repo_with_remote)] repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);

    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    copy_mock_binary(&mock_bin, "az");

    MockConfig::new("az")
        .version("azure-cli 2.60.0 (mock)")
        .command(
            "repos pr show",
            MockResponse::stderr(
                "ERROR: 'repos' is misspelled or not recognized by the system. \
                 The command requires the azure-devops extension.\n",
            )
            .with_exit_code(2),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_extension_not_installed", cmd);
    });
}

/// When the API response has no `webUrl` and no local Azure remote is
/// configured, `fetch_pr_info` can't determine the org/host and bails with a
/// clear error rather than inventing one.
#[rstest]
fn test_switch_pr_azure_org_undeterminable(#[from(repo_with_remote)] repo: TestRepo) {
    // Non-Azure remote → detect_azure_target returns None.
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://git.internal.example.com/owner/test-repo.git",
    ]);

    let project_config = repo.root_path().join(".config/wt.toml");
    fs::create_dir_all(project_config.parent().unwrap()).unwrap();
    fs::write(&project_config, "[forge]\nplatform = \"azure-devops\"\n").unwrap();

    // Response omits `repository.webUrl` → parse_web_url returns None.
    let az_response = r#"{
        "title": "No web URL",
        "createdBy": {"uniqueName": "alice@example.com"},
        "status": "active",
        "isDraft": false,
        "sourceRefName": "refs/heads/feature-auth",
        "repository": {
            "name": "test-repo",
            "project": {"name": "myproject"}
        },
        "forkSource": null
    }"#;

    let mock_bin = setup_mock_az(&repo, Some(az_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_mock_cli_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_pr_azure_org_undeterminable", cmd);
    });
}

// ============================================================================
// MR Syntax Tests (mr:<number>) - GitLab
// ============================================================================

/// Helper to set up mock glab for MR tests with custom MR response.
///
/// The response should be in `glab api projects/:id/merge_requests/<number>` format:
/// - `source_branch`, `source_project_id`, `target_project_id`
/// - `web_url`
fn setup_mock_glab_for_mr(repo: &TestRepo, glab_response: Option<&str>) -> std::path::PathBuf {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    // Copy mock-stub binary as "glab"
    copy_mock_binary(&mock_bin, "glab");

    // Write MR response file if provided
    if let Some(response) = glab_response {
        fs::write(mock_bin.join("mr_response.json"), response).unwrap();

        MockConfig::new("glab")
            .version("glab version 1.40.0 (mock)")
            .command("api", MockResponse::file("mr_response.json"))
            .command("_default", MockResponse::exit(1))
            .write(&mock_bin);
    }

    mock_bin
}

/// Configure command environment for mock glab.
fn configure_mock_glab_env(cmd: &mut std::process::Command, mock_bin: &Path) {
    // Tell mock-stub where to find config files
    cmd.env("MOCK_CONFIG_DIR", mock_bin);

    // Build PATH with mock binary first
    let (path_var_name, current_path) = std::env::vars_os()
        .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
        .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))
        .unwrap_or(("PATH".to_string(), None));

    let mut paths: Vec<std::path::PathBuf> = current_path
        .as_deref()
        .map(|p| std::env::split_paths(p).collect())
        .unwrap_or_default();
    paths.insert(0, mock_bin.to_path_buf());
    let new_path = std::env::join_paths(&paths)
        .unwrap()
        .to_string_lossy()
        .into_owned();

    cmd.env(path_var_name, new_path);
}

/// Test that --create flag conflicts with mr: syntax
#[rstest]
fn test_switch_mr_create_conflict(#[from(repo_with_remote)] repo: TestRepo) {
    // Mock glab to return MR info (we fetch before checking --create to show branch name)
    let glab_response = r#"{
        "title": "Fix authentication bug in login flow",
        "author": {"username": "alice"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-auth",
        "source_project_id": 123,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_create_conflict", cmd);
    });
}

/// Test that --base flag conflicts with mr: syntax
#[rstest]
fn test_switch_mr_base_conflict(repo: TestRepo) {
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--base", "main", "mr:101"], None);
        assert_cmd_snapshot!("switch_mr_base_conflict", cmd);
    });
}

/// Test same-repo MR checkout (source_project_id == target_project_id)
#[rstest]
fn test_switch_mr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
    // Create a feature branch and push it
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Set origin URL to GitLab-style so find_remote_for_repo() can match owner/test-repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // Redirect gitlab.com URLs to the local bare remote
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // glab api projects/:id/merge_requests/<number> format
    let glab_response = r#"{
        "title": "Fix authentication bug in login flow",
        "author": {"username": "alice"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-auth",
        "source_project_id": 123,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_same_repo", cmd);
    });
}

/// Test same-repo MR with a limited fetch refspec (single-branch clone scenario).
///
/// In repos with a limited refspec (e.g., `+refs/heads/main:refs/remotes/origin/main`),
/// `git fetch origin <branch>` only updates FETCH_HEAD but doesn't create the remote
/// tracking branch. This caused `wt switch mr:101` to fail with "No branch named X".
#[rstest]
fn test_switch_mr_same_repo_limited_refspec(#[from(repo_with_remote)] mut repo: TestRepo) {
    // Create a feature branch and push it to the remote
    repo.add_worktree("feature-auth");
    repo.run_git(&["push", "origin", "feature-auth"]);

    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Set origin URL to GitLab-style so find_remote_for_repo() can match owner/test-repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // Redirect gitlab.com URLs to the local bare remote
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // Restrict fetch refspec to only main, simulating a single-branch clone
    repo.run_git(&[
        "config",
        "remote.origin.fetch",
        "+refs/heads/main:refs/remotes/origin/main",
    ]);

    let glab_response = r#"{
        "title": "Fix authentication bug in login flow",
        "author": {"username": "alice"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-auth",
        "source_project_id": 123,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_same_repo_limited_refspec", cmd);
    });
}

/// Test same-repo MR when origin points to a different repo (no remote for MR's repo)
///
/// User scenario:
/// 1. User has origin pointing to their fork (contributor/test-repo)
/// 2. MR !101 is a same-repo MR on the upstream (owner/test-repo)
/// 3. No remote exists for owner/test-repo -> error with hint to add upstream
#[rstest]
fn test_switch_mr_same_repo_no_remote(#[from(repo_with_remote)] repo: TestRepo) {
    // Set origin to point to a DIFFERENT repo than where the MR is
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/contributor/test-repo.git",
    ]);

    let glab_response = r#"{
        "title": "Fix authentication bug in login flow",
        "author": {"username": "alice"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-auth",
        "source_project_id": 123,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_same_repo_no_remote", cmd);
    });
}

/// Test same-repo MR with malformed web_url (missing /-/ separator)
#[rstest]
fn test_switch_mr_malformed_web_url_no_separator(#[from(repo_with_remote)] repo: TestRepo) {
    let glab_response = r#"{
        "title": "Fix bug",
        "author": {"username": "alice"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature",
        "source_project_id": 123,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/merge_requests/101"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_malformed_web_url", cmd);
    });
}

/// Test same-repo MR with unparsable project URL (has /-/ but no owner/repo)
#[rstest]
fn test_switch_mr_malformed_web_url_no_project(#[from(repo_with_remote)] repo: TestRepo) {
    let glab_response = r#"{
        "title": "Fix bug",
        "author": {"username": "alice"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature",
        "source_project_id": 123,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/-/merge_requests/101"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_malformed_web_url_no_project", cmd);
    });
}

/// Test error when MR is not found
#[rstest]
fn test_switch_mr_not_found(#[from(repo_with_remote)] repo: TestRepo) {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    // Copy mock-stub binary as "glab"
    copy_mock_binary(&mock_bin, "glab");

    // Configure glab api to return 404 error (JSON on stdout like real GitLab API)
    MockConfig::new("glab")
        .version("glab version 1.40.0 (mock)")
        .command(
            "api",
            MockResponse::output(r#"{"message":"404 Not found"}"#).with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:9999"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_not_found", cmd);
    });
}

/// Test mr: when glab is not authenticated
#[rstest]
fn test_switch_mr_not_authenticated(#[from(repo_with_remote)] repo: TestRepo) {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "glab");

    // Configure glab api to return 401 error (JSON on stdout like real GitLab API)
    MockConfig::new("glab")
        .version("glab version 1.40.0 (mock)")
        .command(
            "api",
            MockResponse::output(r#"{"message":"401 Unauthorized"}"#).with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_not_authenticated", cmd);
    });
}

/// Test mr: when glab returns invalid JSON
#[rstest]
fn test_switch_mr_invalid_json(#[from(repo_with_remote)] repo: TestRepo) {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "glab");

    // Configure glab api to return invalid JSON
    MockConfig::new("glab")
        .version("glab version 1.40.0 (mock)")
        .command("api", MockResponse::output("not valid json {{{"))
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_invalid_json", cmd);
    });
}

/// Test mr: when MR has empty branch name
#[rstest]
fn test_switch_mr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "glab");

    // Configure glab api to return valid JSON but with empty branch name
    let glab_response = r#"{
        "title": "MR with empty branch",
        "author": {"username": "contributor"},
        "state": "opened",
        "draft": false,
        "source_branch": "",
        "source_project_id": 456,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"
    }"#;

    MockConfig::new("glab")
        .version("glab version 1.40.0 (mock)")
        .command("api", MockResponse::output(glab_response))
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_empty_branch", cmd);
    });
}

/// Test fork MR checkout (source_project_id != target_project_id)
#[rstest]
fn test_switch_mr_fork(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a MR ref on the remote that can be fetched
    // First, create a commit that represents the MR head
    repo.run_git(&["checkout", "-b", "mr-source"]);
    fs::write(repo.root_path().join("mr-file.txt"), "MR content").unwrap();
    repo.run_git(&["add", "mr-file.txt"]);
    repo.run_git(&["commit", "-m", "MR commit"]);

    // Get the commit SHA and push to remote as refs/merge-requests/42/head
    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();

    // Push the ref to the bare remote
    repo.run_git(&[
        "push",
        "origin",
        &format!("{}:refs/merge-requests/42/head", sha),
    ]);

    // Go back to main
    repo.run_git(&["checkout", "main"]);

    // Get the bare remote's actual URL before we modify origin
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    // Set origin URL to GitLab-style so find_remote_by_url() can match
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // Configure git to redirect gitlab.com URLs to the local bare remote.
    // This is necessary because:
    // 1. origin must have a GitLab URL for find_remote_by_url() to match target project
    // 2. But we need git fetch to actually succeed using the local bare remote
    // Git's url.<base>.insteadOf transparently rewrites the fetch URL.
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // Set up mock glab with separate responses for MR API and project APIs.
    // The mock-stub supports compound keys like "api projects/456" to match
    // different API paths.
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();
    copy_mock_binary(&mock_bin, "glab");

    // MR API response (no nested project data - that comes from separate calls)
    let mr_response = r#"{
        "title": "Add feature fix for edge case",
        "author": {"username": "contributor"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-fix",
        "source_project_id": 456,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"
    }"#;

    // Source project (fork) API response
    let source_project_response = r#"{
        "ssh_url_to_repo": "git@gitlab.com:contributor/test-repo.git",
        "http_url_to_repo": "https://gitlab.com/contributor/test-repo.git"
    }"#;

    // Target project (upstream) API response
    let target_project_response = r#"{
        "ssh_url_to_repo": "git@gitlab.com:owner/test-repo.git",
        "http_url_to_repo": "https://gitlab.com/owner/test-repo.git"
    }"#;

    MockConfig::new("glab")
        .version("glab version 1.40.0 (mock)")
        // Compound key: "api projects/:id/merge_requests/42"
        .command(
            "api projects/:id/merge_requests/42",
            MockResponse::output(mr_response),
        )
        // Compound key: "api projects/456" (source project)
        .command(
            "api projects/456",
            MockResponse::output(source_project_response),
        )
        // Compound key: "api projects/123" (target project)
        .command(
            "api projects/123",
            MockResponse::output(target_project_response),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:42"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_fork", cmd);
    });
}

/// Test fork MR checkout when branch already exists and tracks the MR
#[rstest]
fn test_switch_mr_fork_existing_branch_tracks_mr(#[from(repo_with_remote)] repo: TestRepo) {
    // Create the branch that will track the MR
    repo.run_git(&["checkout", "-b", "feature-fix"]);
    fs::write(repo.root_path().join("mr-file.txt"), "MR content").unwrap();
    repo.run_git(&["add", "mr-file.txt"]);
    repo.run_git(&["commit", "-m", "MR commit"]);

    // Get the commit SHA and push to remote as refs/merge-requests/42/head
    let commit_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&commit_sha.stdout)
        .trim()
        .to_string();

    repo.run_git(&[
        "push",
        "origin",
        &format!("{}:refs/merge-requests/42/head", sha),
    ]);

    // Configure branch to track the MR ref (as our code would set it up)
    repo.run_git(&["config", "branch.feature-fix.remote", "origin"]);
    repo.run_git(&[
        "config",
        "branch.feature-fix.merge",
        "refs/merge-requests/42/head",
    ]);

    // Go back to main
    repo.run_git(&["checkout", "main"]);

    // Set origin URL to GitLab-style
    let bare_url = String::from_utf8_lossy(
        &repo
            .git_command()
            .args(["config", "remote.origin.url"])
            .run()
            .unwrap()
            .stdout,
    )
    .trim()
    .to_string();

    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "config",
        &format!("url.{}.insteadOf", bare_url),
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // Fork MR response (project URLs not needed since branch already exists)
    let glab_response = r#"{
        "title": "Add feature fix for edge case",
        "author": {"username": "contributor"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-fix",
        "source_project_id": 456,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:42"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_fork_existing_branch_tracks_mr", cmd);
    });
}

/// Test fork MR checkout when branch exists but tracks something else
#[rstest]
fn test_switch_mr_fork_existing_branch_tracks_different(#[from(repo_with_remote)] repo: TestRepo) {
    // Create the branch that tracks a different ref
    repo.run_git(&["checkout", "-b", "feature-fix"]);
    fs::write(repo.root_path().join("mr-file.txt"), "MR content").unwrap();
    repo.run_git(&["add", "mr-file.txt"]);
    repo.run_git(&["commit", "-m", "MR commit"]);

    // Configure branch to track a different MR
    repo.run_git(&["config", "branch.feature-fix.remote", "origin"]);
    repo.run_git(&[
        "config",
        "branch.feature-fix.merge",
        "refs/merge-requests/99/head", // Different MR number
    ]);

    // Go back to main
    repo.run_git(&["checkout", "main"]);

    // Set origin URL to GitLab-style
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // Fork MR response for MR 42, but branch tracks MR 99 (error case)
    let glab_response = r#"{
        "title": "Add feature fix for edge case",
        "author": {"username": "contributor"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-fix",
        "source_project_id": 456,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:42"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_fork_existing_branch_tracks_different", cmd);
    });
}

/// Test fork MR checkout when branch exists but has no tracking config
#[rstest]
fn test_switch_mr_fork_existing_no_tracking(#[from(repo_with_remote)] repo: TestRepo) {
    // Create the branch without any tracking config
    repo.run_git(&["branch", "feature-fix", "main"]);
    // No config set - branch exists but doesn't track anything

    // Set origin URL to GitLab-style
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/owner/test-repo.git",
    ]);

    // Fork MR response (project URLs not needed since branch already exists)
    let glab_response = r#"{
        "title": "Add feature fix for edge case",
        "author": {"username": "contributor"},
        "state": "opened",
        "draft": false,
        "source_branch": "feature-fix",
        "source_project_id": 456,
        "target_project_id": 123,
        "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"
    }"#;

    let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:42"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_fork_existing_no_tracking", cmd);
    });
}

/// Test mr: with unknown glab error (falls through to general error handler)
#[rstest]
fn test_switch_mr_unknown_error(#[from(repo_with_remote)] repo: TestRepo) {
    let mock_bin = repo.root_path().join("mock-bin");
    fs::create_dir_all(&mock_bin).unwrap();

    copy_mock_binary(&mock_bin, "glab");

    // Configure glab api to return an unknown error (non-JSON stderr, like network errors)
    MockConfig::new("glab")
        .version("glab version 1.40.0 (mock)")
        .command(
            "api",
            MockResponse::stderr("glab: unexpected internal error: something went wrong")
                .with_exit_code(1),
        )
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_mock_glab_env(&mut cmd, &mock_bin);
        assert_cmd_snapshot!("switch_mr_unknown_error", cmd);
    });
}

/// Set up a minimal bin directory with only git (no gh/glab).
///
/// Creates a temporary directory with a symlink to git, excluding gh/glab.
/// Returns the path to use as PATH.
/// Create a minimal bin directory with only git, excluding gh/glab.
/// Returns None on Windows where this approach doesn't work reliably.
#[cfg(unix)]
fn setup_minimal_bin_without_cli(repo: &TestRepo) -> Option<std::path::PathBuf> {
    let minimal_bin = repo.root_path().join("minimal-bin");
    fs::create_dir_all(&minimal_bin).unwrap();

    // Find git binary using the which crate (cross-platform)
    let git_path = which::which("git").expect("git must be installed to run tests");

    // Symlink git into our minimal bin directory
    std::os::unix::fs::symlink(&git_path, minimal_bin.join("git")).unwrap();
    Some(minimal_bin)
}

/// On Windows, git requires its entire installation directory to function,
/// so we can't easily create a minimal PATH with just git. Skip these tests.
#[cfg(windows)]
fn setup_minimal_bin_without_cli(_repo: &TestRepo) -> Option<std::path::PathBuf> {
    None
}

/// Configure PATH to exclude gh/glab, keeping only git.
///
/// This simulates the "CLI not installed" scenario.
fn configure_cli_not_installed_env(cmd: &mut std::process::Command, minimal_bin: &Path) {
    cmd.env("PATH", minimal_bin);
}

/// Test pr: when gh CLI is not installed
#[rstest]
fn test_switch_pr_gh_not_installed(#[from(repo_with_remote)] repo: TestRepo) {
    // Set a GitHub URL so fetch_pr_info can parse owner/repo before checking for gh
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);
    let Some(minimal_bin) = setup_minimal_bin_without_cli(&repo) else {
        // Symlinks not available (Windows without Developer Mode)
        eprintln!("Skipping test: symlinks not available on this system");
        return;
    };

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
        configure_cli_not_installed_env(&mut cmd, &minimal_bin);
        assert_cmd_snapshot!("switch_pr_gh_not_installed", cmd);
    });
}

/// Test mr: when glab CLI is not installed
#[rstest]
fn test_switch_mr_glab_not_installed(#[from(repo_with_remote)] repo: TestRepo) {
    let Some(minimal_bin) = setup_minimal_bin_without_cli(&repo) else {
        // Symlinks not available (Windows without Developer Mode)
        eprintln!("Skipping test: symlinks not available on this system");
        return;
    };

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
        configure_cli_not_installed_env(&mut cmd, &minimal_bin);
        assert_cmd_snapshot!("switch_mr_glab_not_installed", cmd);
    });
}

/// Bug fix: switching to the current worktree (AlreadyAt) must NOT update switch history.
///
/// Previously, `wt switch foo` while already in `foo` would record `foo` as the
/// previous branch, corrupting `wt switch -` so it pointed to the current branch
/// instead of the actual previous one.
#[rstest]
fn test_switch_already_at_preserves_history(repo: TestRepo) {
    // Create a feature branch with worktree
    repo.run_git(&["branch", "hist-feature"]);

    // Step 1: Switch from main to hist-feature (establishes history: previous=main)
    let feature_path = repo.root_path().parent().unwrap().join(format!(
        "{}.hist-feature",
        repo.root_path().file_name().unwrap().to_str().unwrap()
    ));
    snapshot_switch_from_dir(
        "already_at_preserves_history_1_to_feature",
        &repo,
        &["hist-feature"],
        repo.root_path(),
    );

    // Step 2: Switch to hist-feature again while already there (AlreadyAt)
    // This should NOT update history
    snapshot_switch_from_dir(
        "already_at_preserves_history_2_noop",
        &repo,
        &["hist-feature"],
        &feature_path,
    );

    // Step 3: `wt switch -` should still go to main (the real previous),
    // not to hist-feature (which the bug would have recorded)
    snapshot_switch_from_dir(
        "already_at_preserves_history_3_dash_to_main",
        &repo,
        &["-"],
        &feature_path,
    );
}

/// WORKTRUNK_FIRST_OUTPUT exits after execute_switch, before mismatch computation
/// and output rendering. Used by time-to-first-output benchmarks.
#[rstest]
fn test_switch_first_output_exits_cleanly(mut repo: TestRepo) {
    repo.add_worktree("feature-bench");

    let output = repo
        .wt_command()
        .args(["switch", "feature-bench", "--yes"])
        .env("WORKTRUNK_FIRST_OUTPUT", "1")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "WORKTRUNK_FIRST_OUTPUT should exit 0: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    // No output expected — early exit skips all rendering
    assert!(output.stdout.is_empty());
    assert!(output.stderr.is_empty());
}

/// Bug fix: `--base` without `--create` should warn, not error.
///
/// Previously, `--base -` was resolved (calling resolve_worktree_name) before
/// checking the `--create` flag. When there was no previous branch in history,
/// this produced "No previous branch found" instead of the expected
/// "--base flag is only used with --create, ignoring" warning.
#[rstest]
fn test_switch_base_without_create_warns_not_errors(repo: TestRepo) {
    repo.run_git(&["branch", "base-test"]);

    // No switch history exists, so resolving `-` would fail.
    // But --base without --create should just warn and ignore the flag.
    snapshot_switch(
        "switch_base_without_create_warns",
        &repo,
        &["base-test", "--base", "-"],
    );
}

/// Test that `--cd` flag overrides `[switch] cd = false` config
#[rstest]
fn test_switch_cd_flag_overrides_no_cd_config(repo: TestRepo) {
    // Set up config with cd = false
    repo.write_test_config(
        r#"worktree-path = "../{{ repo }}.{{ branch }}"

[switch]
cd = false
"#,
    );

    repo.run_git(&["branch", "cd-override-test"]);

    // --cd should override the config and include cd directive
    snapshot_switch(
        "switch_cd_flag_overrides_config",
        &repo,
        &["cd-override-test", "--cd"],
    );
}

/// Test that `--no-cd` flag works (explicit flag, no config)
#[rstest]
fn test_switch_no_cd_flag_explicit(repo: TestRepo) {
    repo.run_git(&["branch", "no-cd-explicit"]);

    // --no-cd should skip the cd directive
    snapshot_switch(
        "switch_no_cd_flag_explicit",
        &repo,
        &["no-cd-explicit", "--no-cd"],
    );
}

/// Test that worktrunk works correctly when `worktree.useRelativePaths` is enabled.
///
/// Git 2.48+ supports `worktree.useRelativePaths`, which stores relative paths in the
/// `.git` file of linked worktrees instead of absolute paths. This makes worktree
/// directories relocatable. We verify that worktrunk's path handling (which canonicalizes
/// paths internally) works correctly with this configuration.
///
/// See: https://github.com/max-sixty/worktrunk/issues/1630
#[rstest]
fn test_switch_with_relative_worktree_paths(repo: TestRepo) {
    // Enable relative paths for worktrees
    repo.run_git(&["config", "worktree.useRelativePaths", "true"]);

    // Create a new worktree via wt switch --create
    snapshot_switch(
        "switch_create_relative_paths",
        &repo,
        &["--create", "relative-test"],
    );

    // Verify the .git file in the worktree contains a relative path
    let worktree_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("repo.relative-test");
    let git_file = std::fs::read_to_string(worktree_path.join(".git")).unwrap();
    assert!(
        !git_file.contains(repo.root_path().to_str().unwrap()),
        "Expected relative path in .git file, but found absolute path: {git_file}"
    );
    assert!(
        git_file.contains("gitdir: ../"),
        "Expected relative gitdir in .git file: {git_file}"
    );

    // Verify wt list shows the worktree (path resolution works)
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "list", &[], None);
        assert_cmd_snapshot!("list_with_relative_paths", cmd);
    });

    // Verify switching to the relative-path worktree works
    snapshot_switch("switch_to_relative_paths", &repo, &["relative-test"]);
}

// -- JSON format tests --

#[rstest]
fn test_switch_format_json_create(repo: TestRepo) {
    let output = repo
        .wt_command()
        .args([
            "switch",
            "--create",
            "json-test",
            "--no-cd",
            "--yes",
            "--format=json",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["action"], "created");
    assert_eq!(json["branch"], "json-test");
    assert!(json["path"].as_str().unwrap().contains("json-test"));
    assert_eq!(json["created_branch"], true);
}

#[rstest]
fn test_switch_format_json_existing(mut repo: TestRepo) {
    // Create worktree first
    repo.add_worktree("existing-json");

    let output = repo
        .wt_command()
        .args([
            "switch",
            "existing-json",
            "--no-cd",
            "--yes",
            "--format=json",
        ])
        .output()
        .unwrap();
    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["action"], "existing");
    assert_eq!(json["branch"], "existing-json");
    // created_branch should be absent for existing switches
    assert!(json.get("created_branch").is_none());
}

#[rstest]
fn test_switch_format_json_already_at(mut repo: TestRepo) {
    // Create worktree and switch to it
    let path = repo.add_worktree("already-json");

    let output = repo
        .wt_command()
        .current_dir(&path)
        .args([
            "switch",
            "already-json",
            "--no-cd",
            "--yes",
            "--format=json",
        ])
        .output()
        .unwrap();
    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["action"], "already_at");
    assert_eq!(json["branch"], "already-json");
}

#[rstest]
fn test_switch_format_table_rejected_by_clap(repo: TestRepo) {
    let output = repo
        .wt_command()
        .args([
            "switch",
            "--create",
            "table-test",
            "--no-cd",
            "--yes",
            "--format=table",
        ])
        .output()
        .unwrap();
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("invalid value"), "stderr: {stderr}");
}

/// Test that `[switch] cd = false` config is respected when no flags provided
#[rstest]
fn test_switch_no_cd_config_default(repo: TestRepo) {
    // Set up config with cd = false
    repo.write_test_config(
        r#"worktree-path = "../{{ repo }}.{{ branch }}"

[switch]
cd = false
"#,
    );

    repo.run_git(&["branch", "no-cd-config-test"]);

    // Without any cd flags, config should be respected (no cd directive)
    snapshot_switch("switch_no_cd_config_default", &repo, &["no-cd-config-test"]);
}