cascade-cli 0.1.152

Stacked diffs CLI for Bitbucket Server
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
use crate::cli::output::Output;
use crate::errors::{CascadeError, Result};
use chrono;
use dialoguer::{theme::ColorfulTheme, Confirm, Select};
use git2::{Oid, Repository, Signature};
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

/// Repository information
#[derive(Debug, Clone)]
pub struct RepositoryInfo {
    pub path: PathBuf,
    pub head_branch: Option<String>,
    pub head_commit: Option<String>,
    pub is_dirty: bool,
    pub untracked_files: Vec<String>,
}

/// Backup information for force push operations
#[derive(Debug, Clone)]
struct ForceBackupInfo {
    pub backup_branch_name: String,
    pub remote_commit_id: String,
    #[allow(dead_code)] // Used for logging/display purposes
    pub commits_that_would_be_lost: usize,
}

/// Safety information for branch deletion operations
#[derive(Debug, Clone)]
struct BranchDeletionSafety {
    pub unpushed_commits: Vec<String>,
    pub remote_tracking_branch: Option<String>,
    pub is_merged_to_main: bool,
    pub main_branch_name: String,
}

/// Safety information for checkout operations
#[derive(Debug, Clone)]
struct CheckoutSafety {
    #[allow(dead_code)] // Used in confirmation dialogs and future features
    pub has_uncommitted_changes: bool,
    pub modified_files: Vec<String>,
    pub staged_files: Vec<String>,
    pub untracked_files: Vec<String>,
    #[allow(dead_code)] // Reserved for future automatic stashing implementation
    pub stash_created: Option<String>,
    #[allow(dead_code)] // Used for context in confirmation dialogs
    pub current_branch: Option<String>,
}

/// SSL configuration for git operations
#[derive(Debug, Clone)]
pub struct GitSslConfig {
    pub accept_invalid_certs: bool,
    pub ca_bundle_path: Option<String>,
}

/// Summary of git repository status
#[derive(Debug, Clone)]
pub struct GitStatusSummary {
    staged_files: usize,
    unstaged_files: usize,
    untracked_files: usize,
}

impl GitStatusSummary {
    pub fn is_clean(&self) -> bool {
        self.staged_files == 0 && self.unstaged_files == 0 && self.untracked_files == 0
    }

    pub fn has_staged_changes(&self) -> bool {
        self.staged_files > 0
    }

    pub fn has_unstaged_changes(&self) -> bool {
        self.unstaged_files > 0
    }

    pub fn has_untracked_files(&self) -> bool {
        self.untracked_files > 0
    }

    pub fn staged_count(&self) -> usize {
        self.staged_files
    }

    pub fn unstaged_count(&self) -> usize {
        self.unstaged_files
    }

    pub fn untracked_count(&self) -> usize {
        self.untracked_files
    }
}

/// Wrapper around git2::Repository with safe operations
///
/// For thread safety, use the async variants (e.g., fetch_async, pull_async)
/// which automatically handle threading using tokio::spawn_blocking.
/// The async methods create new repository instances in background threads.
pub struct GitRepository {
    repo: Repository,
    path: PathBuf,
    ssl_config: Option<GitSslConfig>,
    bitbucket_credentials: Option<BitbucketCredentials>,
}

#[derive(Debug, Clone)]
struct BitbucketCredentials {
    username: Option<String>,
    token: Option<String>,
}

impl GitRepository {
    /// Open a Git repository at the given path
    /// Automatically loads SSL configuration from cascade config if available
    pub fn open(path: &Path) -> Result<Self> {
        let repo = Repository::discover(path)
            .map_err(|e| CascadeError::config(format!("Not a git repository: {e}")))?;

        let workdir = repo
            .workdir()
            .ok_or_else(|| CascadeError::config("Repository has no working directory"))?
            .to_path_buf();

        // Try to load SSL configuration from cascade config
        let ssl_config = Self::load_ssl_config_from_cascade(&workdir);
        let bitbucket_credentials = Self::load_bitbucket_credentials_from_cascade(&workdir);

        Ok(Self {
            repo,
            path: workdir,
            ssl_config,
            bitbucket_credentials,
        })
    }

    /// Load SSL configuration from cascade config file if it exists
    fn load_ssl_config_from_cascade(repo_path: &Path) -> Option<GitSslConfig> {
        // Try to load cascade configuration
        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
        let config_path = config_dir.join("config.json");
        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;

        // Convert BitbucketConfig to GitSslConfig if SSL settings exist
        if settings.bitbucket.accept_invalid_certs.is_some()
            || settings.bitbucket.ca_bundle_path.is_some()
        {
            Some(GitSslConfig {
                accept_invalid_certs: settings.bitbucket.accept_invalid_certs.unwrap_or(false),
                ca_bundle_path: settings.bitbucket.ca_bundle_path,
            })
        } else {
            None
        }
    }

    /// Load Bitbucket credentials from cascade config file if it exists
    fn load_bitbucket_credentials_from_cascade(repo_path: &Path) -> Option<BitbucketCredentials> {
        // Try to load cascade configuration
        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
        let config_path = config_dir.join("config.json");
        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;

        // Return credentials if any are configured
        if settings.bitbucket.username.is_some() || settings.bitbucket.token.is_some() {
            Some(BitbucketCredentials {
                username: settings.bitbucket.username.clone(),
                token: settings.bitbucket.token.clone(),
            })
        } else {
            None
        }
    }

    /// Get repository information
    pub fn get_info(&self) -> Result<RepositoryInfo> {
        let head_branch = self.get_current_branch().ok();
        let head_commit = self.get_head_commit_hash().ok();
        let is_dirty = self.is_dirty()?;
        let untracked_files = self.get_untracked_files()?;

        Ok(RepositoryInfo {
            path: self.path.clone(),
            head_branch,
            head_commit,
            is_dirty,
            untracked_files,
        })
    }

    /// Get the current branch name
    pub fn get_current_branch(&self) -> Result<String> {
        let head = self
            .repo
            .head()
            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;

        if let Some(name) = head.shorthand() {
            Ok(name.to_string())
        } else {
            // Detached HEAD - return commit hash
            let commit = head
                .peel_to_commit()
                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
            Ok(format!("HEAD@{}", commit.id()))
        }
    }

    /// Get the HEAD commit hash
    pub fn get_head_commit_hash(&self) -> Result<String> {
        let head = self
            .repo
            .head()
            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;

        let commit = head
            .peel_to_commit()
            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;

        Ok(commit.id().to_string())
    }

    /// Check if the working directory is dirty (has uncommitted changes)
    /// Excludes .cascade/ directory changes as these are internal metadata
    pub fn is_dirty(&self) -> Result<bool> {
        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;

        for status in statuses.iter() {
            let flags = status.status();

            // Skip .cascade/ directory - it's internal metadata that shouldn't block operations
            if let Some(path) = status.path() {
                if path.starts_with(".cascade/") || path == ".cascade" {
                    continue;
                }
            }

            // Check for any modifications, additions, or deletions
            if flags.intersects(
                git2::Status::INDEX_MODIFIED
                    | git2::Status::INDEX_NEW
                    | git2::Status::INDEX_DELETED
                    | git2::Status::WT_MODIFIED
                    | git2::Status::WT_NEW
                    | git2::Status::WT_DELETED,
            ) {
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// Get list of untracked files
    pub fn get_untracked_files(&self) -> Result<Vec<String>> {
        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;

        let mut untracked = Vec::new();
        for status in statuses.iter() {
            if status.status().contains(git2::Status::WT_NEW) {
                if let Some(path) = status.path() {
                    untracked.push(path.to_string());
                }
            }
        }

        Ok(untracked)
    }

    /// Create a new branch
    pub fn create_branch(&self, name: &str, target: Option<&str>) -> Result<()> {
        let target_commit = if let Some(target) = target {
            // Find the specified target commit/branch
            let target_obj = self.repo.revparse_single(target).map_err(|e| {
                CascadeError::branch(format!("Could not find target '{target}': {e}"))
            })?;
            target_obj.peel_to_commit().map_err(|e| {
                CascadeError::branch(format!("Target '{target}' is not a commit: {e}"))
            })?
        } else {
            // Use current HEAD
            let head = self
                .repo
                .head()
                .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
            head.peel_to_commit()
                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?
        };

        self.repo
            .branch(name, &target_commit, false)
            .map_err(|e| CascadeError::branch(format!("Could not create branch '{name}': {e}")))?;

        // Branch creation logging is handled by the caller for clean output
        Ok(())
    }

    /// Update a branch to point to a specific commit (local operation only)
    /// Creates the branch if it doesn't exist, updates it if it does
    pub fn update_branch_to_commit(&self, branch_name: &str, commit_id: &str) -> Result<()> {
        let commit_oid = Oid::from_str(commit_id).map_err(|e| {
            CascadeError::branch(format!("Invalid commit ID '{}': {}", commit_id, e))
        })?;

        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
            CascadeError::branch(format!("Commit '{}' not found: {}", commit_id, e))
        })?;

        // Try to find existing branch
        if self
            .repo
            .find_branch(branch_name, git2::BranchType::Local)
            .is_ok()
        {
            // Update existing branch to point to new commit
            let refname = format!("refs/heads/{}", branch_name);
            self.repo
                .reference(
                    &refname,
                    commit_oid,
                    true,
                    "update branch to rebased commit",
                )
                .map_err(|e| {
                    CascadeError::branch(format!(
                        "Failed to update branch '{}': {}",
                        branch_name, e
                    ))
                })?;
        } else {
            // Create new branch
            self.repo.branch(branch_name, &commit, false).map_err(|e| {
                CascadeError::branch(format!("Failed to create branch '{}': {}", branch_name, e))
            })?;
        }

        Ok(())
    }

    /// Force-push a single branch to remote (simpler version for when branch is already updated locally)
    pub fn force_push_single_branch(&self, branch_name: &str) -> Result<()> {
        self.force_push_single_branch_with_options(branch_name, false, false)
    }

    /// Force push with option to skip user confirmation (for automated operations like sync)
    pub fn force_push_single_branch_auto(&self, branch_name: &str) -> Result<()> {
        self.force_push_single_branch_with_options(branch_name, true, false)
    }

    /// Force push a single branch without fetching first (assumes fetch already done)
    /// Used in batch operations where we fetch once before pushing multiple branches
    pub fn force_push_single_branch_auto_no_fetch(&self, branch_name: &str) -> Result<()> {
        self.force_push_single_branch_with_options(branch_name, true, true)
    }

    fn force_push_single_branch_with_options(
        &self,
        branch_name: &str,
        auto_confirm: bool,
        skip_fetch: bool,
    ) -> Result<()> {
        // Validate branch exists before attempting push
        // This provides a clearer error message than a failed git push
        if self.get_branch_commit_hash(branch_name).is_err() {
            return Err(CascadeError::branch(format!(
                "Cannot push '{}': branch does not exist locally",
                branch_name
            )));
        }

        // CRITICAL: Fetch with retry to ensure we have latest remote state
        // Using stale refs could cause silent data loss on force push!
        // Skip if caller already fetched (batch operations)
        if !skip_fetch {
            self.fetch_with_retry()?;
        }

        // Check safety and create backup if needed
        let safety_result = if auto_confirm {
            self.check_force_push_safety_auto_no_fetch(branch_name)?
        } else {
            self.check_force_push_safety_enhanced(branch_name)?
        };

        if let Some(backup_info) = safety_result {
            self.create_backup_branch(branch_name, &backup_info.remote_commit_id)?;
            Output::sub_item(format!(
                "Created backup branch: {}",
                backup_info.backup_branch_name
            ));
        }

        // Ensure index is closed before CLI command to prevent lock conflicts
        self.ensure_index_closed()?;

        // Create marker file to signal pre-push hook to allow this internal push
        // (Git hooks don't inherit env vars, so we use a file marker instead)
        let marker_path = self.git_dir().join(".cascade-internal-push");
        std::fs::write(&marker_path, "1")
            .map_err(|e| CascadeError::branch(format!("Failed to create push marker: {}", e)))?;

        // Force push using git CLI (more reliable than git2 for TLS)
        let output = std::process::Command::new("git")
            .args(["push", "--force", "origin", branch_name])
            .current_dir(&self.path)
            .output()
            .map_err(|e| {
                // Clean up marker on error
                let _ = std::fs::remove_file(&marker_path);
                CascadeError::branch(format!("Failed to execute git push: {}", e))
            })?;

        // Clean up marker file after push attempt
        let _ = std::fs::remove_file(&marker_path);

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);

            // Combine stderr and stdout for full error context
            let full_error = if !stdout.is_empty() {
                format!("{}\n{}", stderr.trim(), stdout.trim())
            } else {
                stderr.trim().to_string()
            };

            return Err(CascadeError::branch(format!(
                "Force push failed for '{}':\n{}",
                branch_name, full_error
            )));
        }

        Ok(())
    }

    /// Switch to a branch with safety checks
    pub fn checkout_branch(&self, name: &str) -> Result<()> {
        self.checkout_branch_with_options(name, false, true)
    }

    /// Switch to a branch silently (no output)
    pub fn checkout_branch_silent(&self, name: &str) -> Result<()> {
        self.checkout_branch_with_options(name, false, false)
    }

    /// Switch to a branch with force option to bypass safety checks
    pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
        self.checkout_branch_with_options(name, true, false)
    }

    /// Internal branch checkout implementation with safety options
    fn checkout_branch_with_options(
        &self,
        name: &str,
        force_unsafe: bool,
        show_output: bool,
    ) -> Result<()> {
        debug!("Attempting to checkout branch: {}", name);

        // Enhanced safety check: Detect uncommitted work before checkout
        if !force_unsafe {
            let safety_result = self.check_checkout_safety(name)?;
            if let Some(safety_info) = safety_result {
                // Repository has uncommitted changes, get user confirmation
                self.handle_checkout_confirmation(name, &safety_info)?;
            }
        }

        // Find the branch
        let branch = self
            .repo
            .find_branch(name, git2::BranchType::Local)
            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;

        let branch_ref = branch.get();
        let tree = branch_ref.peel_to_tree().map_err(|e| {
            CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
        })?;

        // Update HEAD first — this validates that the branch can be checked out
        // (e.g., not already checked out in another worktree). Doing this before
        // checkout_tree prevents leaving the working directory in an inconsistent
        // state if set_head fails.
        let old_head = self.repo.head().ok();
        self.repo
            .set_head(&format!("refs/heads/{name}"))
            .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;

        // Now checkout the tree to update the working directory
        let mut checkout_builder = git2::build::CheckoutBuilder::new();
        checkout_builder.force(); // Overwrite modified files
        checkout_builder.remove_untracked(false); // Keep untracked files

        if let Err(e) = self
            .repo
            .checkout_tree(tree.as_object(), Some(&mut checkout_builder))
        {
            // Restore HEAD if checkout_tree fails so we don't leave HEAD
            // pointing at a branch whose tree isn't checked out
            if let Some(old) = old_head {
                if let Some(old_name) = old.name() {
                    let _ = self.repo.set_head(old_name);
                }
            }
            return Err(CascadeError::branch(format!(
                "Could not checkout branch '{name}': {e}"
            )));
        }

        if show_output {
            Output::success(format!("Switched to branch '{name}'"));
        }
        Ok(())
    }

    /// Checkout a specific commit (detached HEAD) with safety checks
    pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
        self.checkout_commit_with_options(commit_hash, false)
    }

    /// Checkout a specific commit with force option to bypass safety checks
    pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
        self.checkout_commit_with_options(commit_hash, true)
    }

    /// Internal commit checkout implementation with safety options
    fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
        debug!("Attempting to checkout commit: {}", commit_hash);

        // Enhanced safety check: Detect uncommitted work before checkout
        if !force_unsafe {
            let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
            if let Some(safety_info) = safety_result {
                // Repository has uncommitted changes, get user confirmation
                self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
            }
        }

        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;

        let commit = self.repo.find_commit(oid).map_err(|e| {
            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
        })?;

        let tree = commit.tree().map_err(|e| {
            CascadeError::branch(format!(
                "Could not get tree for commit '{commit_hash}': {e}"
            ))
        })?;

        // Checkout the tree
        self.repo
            .checkout_tree(tree.as_object(), None)
            .map_err(|e| {
                CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
            })?;

        // Update HEAD to the commit (detached HEAD)
        self.repo.set_head_detached(oid).map_err(|e| {
            CascadeError::branch(format!(
                "Could not update HEAD to commit '{commit_hash}': {e}"
            ))
        })?;

        Output::success(format!(
            "Checked out commit '{commit_hash}' (detached HEAD)"
        ));
        Ok(())
    }

    /// Check if a branch exists
    pub fn branch_exists(&self, name: &str) -> bool {
        self.repo.find_branch(name, git2::BranchType::Local).is_ok()
    }

    /// Check if a branch exists locally, and if not, attempt to fetch it from remote
    pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
        // 1. Check if branch exists locally first
        if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
            return Ok(true);
        }

        // 2. Try to fetch it from remote
        crate::cli::output::Output::info(format!(
            "Branch '{name}' not found locally, trying to fetch from remote..."
        ));

        use std::process::Command;

        // Try: git fetch origin release/12.34:release/12.34
        let fetch_result = Command::new("git")
            .args(["fetch", "origin", &format!("{name}:{name}")])
            .current_dir(&self.path)
            .output();

        match fetch_result {
            Ok(output) => {
                if output.status.success() {
                    println!("✅ Successfully fetched '{name}' from origin");
                    // 3. Check again locally after fetch
                    return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
                } else {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    tracing::debug!("Failed to fetch branch '{name}': {stderr}");
                }
            }
            Err(e) => {
                tracing::debug!("Git fetch command failed: {e}");
            }
        }

        // 4. Try alternative fetch patterns for common branch naming
        if name.contains('/') {
            crate::cli::output::Output::info("Trying alternative fetch patterns...");

            // Try: git fetch origin (to get all refs, then checkout locally)
            let fetch_all_result = Command::new("git")
                .args(["fetch", "origin"])
                .current_dir(&self.path)
                .output();

            if let Ok(output) = fetch_all_result {
                if output.status.success() {
                    // Try to create local branch from remote
                    let checkout_result = Command::new("git")
                        .args(["checkout", "-b", name, &format!("origin/{name}")])
                        .current_dir(&self.path)
                        .output();

                    if let Ok(checkout_output) = checkout_result {
                        if checkout_output.status.success() {
                            println!(
                                "✅ Successfully created local branch '{name}' from origin/{name}"
                            );
                            return Ok(true);
                        }
                    }
                }
            }
        }

        // 5. Only fail if it doesn't exist anywhere
        Ok(false)
    }

    /// Get the commit hash for a specific branch without switching branches
    pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
        let branch = self
            .repo
            .find_branch(branch_name, git2::BranchType::Local)
            .map_err(|e| {
                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
            })?;

        let commit = branch.get().peel_to_commit().map_err(|e| {
            CascadeError::branch(format!(
                "Could not get commit for branch '{branch_name}': {e}"
            ))
        })?;

        Ok(commit.id().to_string())
    }

    /// List all local branches
    pub fn list_branches(&self) -> Result<Vec<String>> {
        let branches = self
            .repo
            .branches(Some(git2::BranchType::Local))
            .map_err(CascadeError::Git)?;

        let mut branch_names = Vec::new();
        for branch in branches {
            let (branch, _) = branch.map_err(CascadeError::Git)?;
            if let Some(name) = branch.name().map_err(CascadeError::Git)? {
                branch_names.push(name.to_string());
            }
        }

        Ok(branch_names)
    }

    /// Get the upstream branch for a local branch
    pub fn get_upstream_branch(&self, branch_name: &str) -> Result<Option<String>> {
        // Try to get the upstream from git config
        let config = self.repo.config().map_err(CascadeError::Git)?;

        // Check for branch.{branch_name}.remote and branch.{branch_name}.merge
        let remote_key = format!("branch.{branch_name}.remote");
        let merge_key = format!("branch.{branch_name}.merge");

        if let (Ok(remote), Ok(merge_ref)) = (
            config.get_string(&remote_key),
            config.get_string(&merge_key),
        ) {
            // Parse the merge ref (e.g., "refs/heads/feature-auth" -> "feature-auth")
            if let Some(branch_part) = merge_ref.strip_prefix("refs/heads/") {
                return Ok(Some(format!("{remote}/{branch_part}")));
            }
        }

        // Fallback: check if there's a remote tracking branch with the same name
        let potential_upstream = format!("origin/{branch_name}");
        if self
            .repo
            .find_reference(&format!("refs/remotes/{potential_upstream}"))
            .is_ok()
        {
            return Ok(Some(potential_upstream));
        }

        Ok(None)
    }

    /// Get ahead/behind counts compared to upstream
    pub fn get_ahead_behind_counts(
        &self,
        local_branch: &str,
        upstream_branch: &str,
    ) -> Result<(usize, usize)> {
        // Get the commit objects for both branches
        let local_ref = self
            .repo
            .find_reference(&format!("refs/heads/{local_branch}"))
            .map_err(|_| {
                CascadeError::config(format!("Local branch '{local_branch}' not found"))
            })?;
        let local_commit = local_ref.peel_to_commit().map_err(CascadeError::Git)?;

        let upstream_ref = self
            .repo
            .find_reference(&format!("refs/remotes/{upstream_branch}"))
            .map_err(|_| {
                CascadeError::config(format!("Upstream branch '{upstream_branch}' not found"))
            })?;
        let upstream_commit = upstream_ref.peel_to_commit().map_err(CascadeError::Git)?;

        // Use git2's graph_ahead_behind to calculate the counts
        let (ahead, behind) = self
            .repo
            .graph_ahead_behind(local_commit.id(), upstream_commit.id())
            .map_err(CascadeError::Git)?;

        Ok((ahead, behind))
    }

    /// Set upstream tracking for a branch
    pub fn set_upstream(&self, branch_name: &str, remote: &str, remote_branch: &str) -> Result<()> {
        let mut config = self.repo.config().map_err(CascadeError::Git)?;

        // Set branch.{branch_name}.remote = remote
        let remote_key = format!("branch.{branch_name}.remote");
        config
            .set_str(&remote_key, remote)
            .map_err(CascadeError::Git)?;

        // Set branch.{branch_name}.merge = refs/heads/{remote_branch}
        let merge_key = format!("branch.{branch_name}.merge");
        let merge_value = format!("refs/heads/{remote_branch}");
        config
            .set_str(&merge_key, &merge_value)
            .map_err(CascadeError::Git)?;

        Ok(())
    }

    /// Create a commit with all staged changes
    pub fn commit(&self, message: &str) -> Result<String> {
        // Validate git user configuration before attempting commit operations
        self.validate_git_user_config()?;

        let signature = self.get_signature()?;
        let tree_id = self.get_index_tree()?;
        let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;

        // Get parent commits
        let head = self.repo.head().map_err(CascadeError::Git)?;
        let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;

        let commit_id = self
            .repo
            .commit(
                Some("HEAD"),
                &signature,
                &signature,
                message,
                &tree,
                &[&parent_commit],
            )
            .map_err(CascadeError::Git)?;

        Output::success(format!("Created commit: {commit_id} - {message}"));
        Ok(commit_id.to_string())
    }

    /// Commit any staged changes with a default message
    pub fn commit_staged_changes(&self, default_message: &str) -> Result<Option<String>> {
        // Check if there are staged changes
        let staged_files = self.get_staged_files()?;
        if staged_files.is_empty() {
            tracing::debug!("No staged changes to commit");
            return Ok(None);
        }

        tracing::debug!("Committing {} staged files", staged_files.len());
        let commit_hash = self.commit(default_message)?;
        Ok(Some(commit_hash))
    }

    /// Stage all changes
    pub fn stage_all(&self) -> Result<()> {
        let mut index = self.repo.index().map_err(CascadeError::Git)?;

        index
            .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
            .map_err(CascadeError::Git)?;

        index.write().map_err(CascadeError::Git)?;
        drop(index); // Explicitly close index after staging

        tracing::debug!("Staged all changes");
        Ok(())
    }

    /// Ensure the Git index is fully written and closed before external git CLI operations
    /// This prevents "index is locked" errors when mixing libgit2 and git CLI commands
    fn ensure_index_closed(&self) -> Result<()> {
        // Open and immediately close the index to ensure any pending writes are flushed
        // and file handles are released before we spawn git CLI processes
        let mut index = self.repo.index().map_err(CascadeError::Git)?;
        index.write().map_err(CascadeError::Git)?;
        drop(index); // Explicit drop to release file handle

        // Give the OS a moment to release file handles
        // This is necessary because even after Rust drops the index,
        // the OS might not immediately release the lock
        std::thread::sleep(std::time::Duration::from_millis(10));

        Ok(())
    }

    /// Stage only specific files (safer than stage_all during rebase)
    pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
        if file_paths.is_empty() {
            tracing::debug!("No files to stage");
            return Ok(());
        }

        let mut index = self.repo.index().map_err(CascadeError::Git)?;

        for file_path in file_paths {
            index
                .add_path(std::path::Path::new(file_path))
                .map_err(CascadeError::Git)?;
        }

        index.write().map_err(CascadeError::Git)?;
        drop(index); // Explicitly close index after staging

        tracing::debug!(
            "Staged {} specific files: {:?}",
            file_paths.len(),
            file_paths
        );
        Ok(())
    }

    /// Stage only files that had conflicts (safer for rebase operations)
    pub fn stage_conflict_resolved_files(&self) -> Result<()> {
        let conflicted_files = self.get_conflicted_files()?;
        if conflicted_files.is_empty() {
            tracing::debug!("No conflicted files to stage");
            return Ok(());
        }

        let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
        self.stage_files(&file_paths)?;

        tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
        Ok(())
    }

    /// Clean up any in-progress merge/revert/cherry-pick state (removes CHERRY_PICK_HEAD etc.)
    pub fn cleanup_state(&self) -> Result<()> {
        let state = self.repo.state();
        if state == git2::RepositoryState::Clean {
            return Ok(());
        }

        tracing::debug!("Cleaning up repository state: {:?}", state);
        self.repo.cleanup_state().map_err(|e| {
            CascadeError::branch(format!(
                "Failed to clean up repository state ({:?}): {}",
                state, e
            ))
        })
    }

    /// Get repository path
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Per-worktree git directory.
    /// Normal repos: /repo/.git/  |  Worktrees: /main/.git/worktrees/<name>/
    pub fn git_dir(&self) -> &Path {
        self.repo.path()
    }

    /// Shared common git directory (hooks, objects, refs).
    /// Normal repos: same as git_dir()  |  Worktrees: /main/.git/
    pub fn common_dir(&self) -> &Path {
        self.repo.commondir()
    }

    /// Check if a commit exists
    pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
        match Oid::from_str(commit_hash) {
            Ok(oid) => match self.repo.find_commit(oid) {
                Ok(_) => Ok(true),
                Err(_) => Ok(false),
            },
            Err(_) => Ok(false),
        }
    }

    /// Check if a commit is already correctly based on a given parent
    /// Returns true if the commit's parent matches the expected base
    pub fn is_commit_based_on(&self, commit_hash: &str, expected_base: &str) -> Result<bool> {
        let commit_oid = Oid::from_str(commit_hash).map_err(|e| {
            CascadeError::branch(format!("Invalid commit hash '{}': {}", commit_hash, e))
        })?;

        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
            CascadeError::branch(format!("Commit '{}' not found: {}", commit_hash, e))
        })?;

        // Get the commit's parent (first parent for merge commits)
        if commit.parent_count() == 0 {
            // Root commit has no parent
            return Ok(false);
        }

        let parent = commit.parent(0).map_err(|e| {
            CascadeError::branch(format!(
                "Could not get parent of commit '{}': {}",
                commit_hash, e
            ))
        })?;
        let parent_hash = parent.id().to_string();

        // Check if expected_base is a commit hash or a branch name
        let expected_base_oid = if let Ok(oid) = Oid::from_str(expected_base) {
            oid
        } else {
            // Try to resolve as a branch name
            let branch_ref = format!("refs/heads/{}", expected_base);
            let reference = self.repo.find_reference(&branch_ref).map_err(|e| {
                CascadeError::branch(format!("Could not find base '{}': {}", expected_base, e))
            })?;
            reference.target().ok_or_else(|| {
                CascadeError::branch(format!("Base '{}' has no target commit", expected_base))
            })?
        };

        let expected_base_hash = expected_base_oid.to_string();

        tracing::debug!(
            "Checking if commit {} is based on {}: parent={}, expected={}",
            &commit_hash[..8],
            expected_base,
            &parent_hash[..8],
            &expected_base_hash[..8]
        );

        Ok(parent_hash == expected_base_hash)
    }

    /// Check whether `descendant` commit contains `ancestor` in its history
    pub fn is_descendant_of(&self, descendant: &str, ancestor: &str) -> Result<bool> {
        let descendant_oid = Oid::from_str(descendant).map_err(|e| {
            CascadeError::branch(format!(
                "Invalid commit hash '{}' for descendant check: {}",
                descendant, e
            ))
        })?;
        let ancestor_oid = Oid::from_str(ancestor).map_err(|e| {
            CascadeError::branch(format!(
                "Invalid commit hash '{}' for descendant check: {}",
                ancestor, e
            ))
        })?;

        self.repo
            .graph_descendant_of(descendant_oid, ancestor_oid)
            .map_err(CascadeError::Git)
    }

    /// Get the HEAD commit object
    pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
        let head = self
            .repo
            .head()
            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
        head.peel_to_commit()
            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
    }

    /// Get a commit object by hash
    pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;

        self.repo.find_commit(oid).map_err(CascadeError::Git)
    }

    /// Get the commit hash at the head of a branch
    pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
        let branch = self
            .repo
            .find_branch(branch_name, git2::BranchType::Local)
            .map_err(|e| {
                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
            })?;

        let commit = branch.get().peel_to_commit().map_err(|e| {
            CascadeError::branch(format!(
                "Could not get commit for branch '{branch_name}': {e}"
            ))
        })?;

        Ok(commit.id().to_string())
    }

    /// Get the commit hash at the head of a remote branch
    pub fn get_remote_branch_head(&self, branch_name: &str) -> Result<String> {
        let refname = format!("refs/remotes/origin/{branch_name}");
        let reference = self.repo.find_reference(&refname).map_err(|e| {
            CascadeError::branch(format!("Remote branch '{branch_name}' not found: {e}"))
        })?;

        let target = reference.target().ok_or_else(|| {
            CascadeError::branch(format!(
                "Remote branch '{branch_name}' does not have a target commit"
            ))
        })?;

        Ok(target.to_string())
    }

    /// Validate git user configuration is properly set
    pub fn validate_git_user_config(&self) -> Result<()> {
        if let Ok(config) = self.repo.config() {
            let name_result = config.get_string("user.name");
            let email_result = config.get_string("user.email");

            if let (Ok(name), Ok(email)) = (name_result, email_result) {
                if !name.trim().is_empty() && !email.trim().is_empty() {
                    tracing::debug!("Git user config validated: {} <{}>", name, email);
                    return Ok(());
                }
            }
        }

        // Check if this is a CI environment where validation can be skipped
        let is_ci = std::env::var("CI").is_ok();

        if is_ci {
            tracing::debug!("CI environment - skipping git user config validation");
            return Ok(());
        }

        Output::warning("Git user configuration missing or incomplete");
        Output::info("This can cause cherry-pick and commit operations to fail");
        Output::info("Please configure git user information:");
        Output::bullet("git config user.name \"Your Name\"".to_string());
        Output::bullet("git config user.email \"your.email@example.com\"".to_string());
        Output::info("Or set globally with the --global flag");

        // Don't fail - let operations continue with fallback signature
        // This preserves backward compatibility while providing guidance
        Ok(())
    }

    /// Read the configured git user name and email from git config
    pub fn get_user_info(&self) -> (Option<String>, Option<String>) {
        let config = match self.repo.config() {
            Ok(c) => c,
            Err(_) => return (None, None),
        };
        let name = config.get_string("user.name").ok();
        let email = config.get_string("user.email").ok();
        (name, email)
    }

    /// Get a signature for commits with comprehensive fallback and validation
    fn get_signature(&self) -> Result<Signature<'_>> {
        // Try to get signature from Git config first
        if let Ok(config) = self.repo.config() {
            // Try global/system config first
            let name_result = config.get_string("user.name");
            let email_result = config.get_string("user.email");

            if let (Ok(name), Ok(email)) = (name_result, email_result) {
                if !name.trim().is_empty() && !email.trim().is_empty() {
                    tracing::debug!("Using git config: {} <{}>", name, email);
                    return Signature::now(&name, &email).map_err(CascadeError::Git);
                }
            } else {
                tracing::debug!("Git user config incomplete or missing");
            }
        }

        // Check if this is a CI environment where fallback is acceptable
        let is_ci = std::env::var("CI").is_ok();

        if is_ci {
            tracing::debug!("CI environment detected, using fallback signature");
            return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
        }

        // Interactive environment - provide helpful guidance
        tracing::warn!("Git user configuration missing - this can cause commit operations to fail");

        // Try fallback signature, but warn about the issue
        match Signature::now("Cascade CLI", "cascade@example.com") {
            Ok(sig) => {
                Output::warning("Git user not configured - using fallback signature");
                Output::info("For better git history, run:");
                Output::bullet("git config user.name \"Your Name\"".to_string());
                Output::bullet("git config user.email \"your.email@example.com\"".to_string());
                Output::info("Or set it globally with --global flag");
                Ok(sig)
            }
            Err(e) => {
                Err(CascadeError::branch(format!(
                    "Cannot create git signature: {e}. Please configure git user with:\n  git config user.name \"Your Name\"\n  git config user.email \"your.email@example.com\""
                )))
            }
        }
    }

    /// Configure remote callbacks with SSL settings
    /// Priority: Cascade SSL config > Git config > Default
    fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
        self.configure_remote_callbacks_with_fallback(false)
    }

    /// Determine if we should retry with DefaultCredentials based on git2 error classification
    fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
        match error.class() {
            // Authentication errors that might be resolved with DefaultCredentials
            git2::ErrorClass::Http => {
                // HTTP errors often indicate authentication issues in corporate environments
                match error.code() {
                    git2::ErrorCode::Auth => true,
                    _ => {
                        // Check for specific HTTP authentication replay errors
                        let error_string = error.to_string();
                        error_string.contains("too many redirects")
                            || error_string.contains("authentication replays")
                            || error_string.contains("authentication required")
                    }
                }
            }
            git2::ErrorClass::Net => {
                // Network errors that might be authentication-related
                let error_string = error.to_string();
                error_string.contains("authentication")
                    || error_string.contains("unauthorized")
                    || error_string.contains("forbidden")
            }
            _ => false,
        }
    }

    /// Determine if we should fallback to git CLI based on git2 error classification
    fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
        match error.class() {
            // SSL/TLS errors that git CLI handles better
            git2::ErrorClass::Ssl => true,

            // Certificate errors
            git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,

            // SSH errors that might need git CLI
            git2::ErrorClass::Ssh => {
                let error_string = error.to_string();
                error_string.contains("no callback set")
                    || error_string.contains("authentication required")
            }

            // Network errors that might be proxy/firewall related
            git2::ErrorClass::Net => {
                let error_string = error.to_string();
                error_string.contains("TLS stream")
                    || error_string.contains("SSL")
                    || error_string.contains("proxy")
                    || error_string.contains("firewall")
            }

            // General HTTP errors not handled by DefaultCredentials retry
            git2::ErrorClass::Http => {
                let error_string = error.to_string();
                error_string.contains("TLS stream")
                    || error_string.contains("SSL")
                    || error_string.contains("proxy")
            }

            _ => false,
        }
    }

    fn configure_remote_callbacks_with_fallback(
        &self,
        use_default_first: bool,
    ) -> Result<git2::RemoteCallbacks<'_>> {
        let mut callbacks = git2::RemoteCallbacks::new();

        // Configure authentication with comprehensive credential support
        let bitbucket_credentials = self.bitbucket_credentials.clone();
        callbacks.credentials(move |url, username_from_url, allowed_types| {
            tracing::debug!(
                "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
                url,
                username_from_url,
                allowed_types
            );

            // For SSH URLs with username
            if allowed_types.contains(git2::CredentialType::SSH_KEY) {
                if let Some(username) = username_from_url {
                    tracing::debug!("Trying SSH key authentication for user: {}", username);
                    return git2::Cred::ssh_key_from_agent(username);
                }
            }

            // For HTTPS URLs, try multiple authentication methods in sequence
            if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
                // If we're in corporate network fallback mode, try DefaultCredentials first
                if use_default_first {
                    tracing::debug!("Corporate network mode: trying DefaultCredentials first");
                    return git2::Cred::default();
                }

                if url.contains("bitbucket") {
                    if let Some(creds) = &bitbucket_credentials {
                        // Method 1: Username + Token (common for Bitbucket)
                        if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
                            tracing::debug!("Trying Bitbucket username + token authentication");
                            return git2::Cred::userpass_plaintext(username, token);
                        }

                        // Method 2: Token as username, empty password (alternate Bitbucket format)
                        if let Some(token) = &creds.token {
                            tracing::debug!("Trying Bitbucket token-as-username authentication");
                            return git2::Cred::userpass_plaintext(token, "");
                        }

                        // Method 3: Just username (will prompt for password or use credential helper)
                        if let Some(username) = &creds.username {
                            tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
                            return git2::Cred::username(username);
                        }
                    }
                }

                // Method 4: Default credential helper for all HTTPS URLs
                tracing::debug!("Trying default credential helper for HTTPS authentication");
                return git2::Cred::default();
            }

            // Fallback to default for any other cases
            tracing::debug!("Using default credential fallback");
            git2::Cred::default()
        });

        // Configure SSL certificate checking with system certificates by default
        // This matches what tools like Graphite, Sapling, and Phabricator do
        // Priority: 1. Use system certificates (default), 2. Manual overrides only if needed

        let mut ssl_configured = false;

        // Check for manual SSL overrides first (only when user explicitly needs them)
        if let Some(ssl_config) = &self.ssl_config {
            if ssl_config.accept_invalid_certs {
                Output::warning(
                    "SSL certificate verification DISABLED via Cascade config - this is insecure!",
                );
                callbacks.certificate_check(|_cert, _host| {
                    tracing::debug!("⚠️  Accepting invalid certificate for host: {}", _host);
                    Ok(git2::CertificateCheckStatus::CertificateOk)
                });
                ssl_configured = true;
            } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
                Output::info(format!(
                    "Using custom CA bundle from Cascade config: {ca_path}"
                ));
                callbacks.certificate_check(|_cert, host| {
                    tracing::debug!("Using custom CA bundle for host: {}", host);
                    Ok(git2::CertificateCheckStatus::CertificateOk)
                });
                ssl_configured = true;
            }
        }

        // Check git config for manual overrides
        if !ssl_configured {
            if let Ok(config) = self.repo.config() {
                let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);

                if !ssl_verify {
                    Output::warning(
                        "SSL certificate verification DISABLED via git config - this is insecure!",
                    );
                    callbacks.certificate_check(|_cert, host| {
                        tracing::debug!("⚠️  Bypassing SSL verification for host: {}", host);
                        Ok(git2::CertificateCheckStatus::CertificateOk)
                    });
                    ssl_configured = true;
                } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
                    Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
                    callbacks.certificate_check(|_cert, host| {
                        tracing::debug!("Using git config CA bundle for host: {}", host);
                        Ok(git2::CertificateCheckStatus::CertificateOk)
                    });
                    ssl_configured = true;
                }
            }
        }

        // DEFAULT BEHAVIOR: Use system certificates (like git CLI and other modern tools)
        // This should work out-of-the-box in corporate environments
        if !ssl_configured {
            tracing::debug!(
                "Using system certificate store for SSL verification (default behavior)"
            );

            // For macOS with SecureTransport backend, try default certificate validation first
            if cfg!(target_os = "macos") {
                tracing::debug!("macOS detected - using default certificate validation");
                // Don't set any certificate callback - let git2 use its default behavior
                // This often works better with SecureTransport backend on macOS
            } else {
                // Use CertificatePassthrough for other platforms
                callbacks.certificate_check(|_cert, host| {
                    tracing::debug!("System certificate validation for host: {}", host);
                    Ok(git2::CertificateCheckStatus::CertificatePassthrough)
                });
            }
        }

        Ok(callbacks)
    }

    /// Get the tree ID from the current index
    fn get_index_tree(&self) -> Result<Oid> {
        let mut index = self.repo.index().map_err(CascadeError::Git)?;

        index.write_tree().map_err(CascadeError::Git)
    }

    /// Get repository status
    pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
        self.repo.statuses(None).map_err(CascadeError::Git)
    }

    /// Get a summary of repository status
    pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
        let statuses = self.get_status()?;

        let mut staged_files = 0;
        let mut unstaged_files = 0;
        let mut untracked_files = 0;

        for status in statuses.iter() {
            let flags = status.status();

            if flags.intersects(
                git2::Status::INDEX_MODIFIED
                    | git2::Status::INDEX_NEW
                    | git2::Status::INDEX_DELETED
                    | git2::Status::INDEX_RENAMED
                    | git2::Status::INDEX_TYPECHANGE,
            ) {
                staged_files += 1;
            }

            if flags.intersects(
                git2::Status::WT_MODIFIED
                    | git2::Status::WT_DELETED
                    | git2::Status::WT_TYPECHANGE
                    | git2::Status::WT_RENAMED,
            ) {
                unstaged_files += 1;
            }

            if flags.intersects(git2::Status::WT_NEW) {
                untracked_files += 1;
            }
        }

        Ok(GitStatusSummary {
            staged_files,
            unstaged_files,
            untracked_files,
        })
    }

    /// Get the current commit hash (alias for get_head_commit_hash)
    pub fn get_current_commit_hash(&self) -> Result<String> {
        self.get_head_commit_hash()
    }

    /// Get the count of commits between two commits
    pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
        let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
        let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;

        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
        revwalk.push(to_oid).map_err(CascadeError::Git)?;
        revwalk.hide(from_oid).map_err(CascadeError::Git)?;

        Ok(revwalk.count())
    }

    /// Get remote URL for a given remote name
    pub fn get_remote_url(&self, name: &str) -> Result<String> {
        let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
        Ok(remote.url().unwrap_or("unknown").to_string())
    }

    /// Cherry-pick a specific commit to the current branch
    pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
        tracing::debug!("Cherry-picking commit {}", commit_hash);

        // Validate git user configuration before attempting commit operations
        self.validate_git_user_config()?;

        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
        let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;

        // Get the commit's tree
        let commit_tree = commit.tree().map_err(CascadeError::Git)?;

        // Get parent tree for merge base
        let parent_commit = if commit.parent_count() > 0 {
            commit.parent(0).map_err(CascadeError::Git)?
        } else {
            // Root commit - use empty tree
            let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
            let empty_tree = self.repo.find_tree(empty_tree_oid)?;
            let sig = self.get_signature()?;
            return self
                .repo
                .commit(
                    Some("HEAD"),
                    &sig,
                    &sig,
                    commit.message().unwrap_or("Cherry-picked commit"),
                    &empty_tree,
                    &[],
                )
                .map(|oid| oid.to_string())
                .map_err(CascadeError::Git);
        };

        let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;

        // Get current HEAD tree for 3-way merge
        let head_commit = self.get_head_commit()?;
        let head_tree = head_commit.tree().map_err(CascadeError::Git)?;

        // Perform 3-way merge
        let mut index = self
            .repo
            .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
            .map_err(CascadeError::Git)?;

        // Check for conflicts
        if index.has_conflicts() {
            // CRITICAL: Write the conflicted state to disk so auto-resolve can see it!
            // Without this, conflicts only exist in memory and Git's index stays clean
            debug!("Cherry-pick has conflicts - writing conflicted state to disk for resolution");

            // The merge_trees() index is in-memory only. We need to:
            // 1. Get the repository's actual index
            // 2. Read entries from the merge result into it
            // 3. Write the repository index to disk

            let mut repo_index = self.repo.index().map_err(CascadeError::Git)?;

            // Clear the current index and read from the merge result
            repo_index.clear().map_err(CascadeError::Git)?;
            repo_index
                .read_tree(&head_tree)
                .map_err(CascadeError::Git)?;

            // Now merge the commit tree into the repo index (this will create conflicts)
            repo_index
                .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
                .map_err(CascadeError::Git)?;

            // Use git CLI to do the actual cherry-pick with conflicts
            // This is more reliable than trying to manually construct the conflicted index

            // First, ensure our libgit2 index is closed so git CLI can work
            drop(repo_index);
            self.ensure_index_closed()?;

            let cherry_pick_output = std::process::Command::new("git")
                .args(["cherry-pick", commit_hash])
                .current_dir(self.path())
                .output()
                .map_err(CascadeError::Io)?;

            if !cherry_pick_output.status.success() {
                debug!("Git CLI cherry-pick failed as expected (has conflicts)");
                // This is expected - the cherry-pick failed due to conflicts
                // The conflicts are now in the working directory and index
            }

            // CRITICAL: Reload the index from disk so libgit2 sees the conflicts
            // Git CLI wrote the conflicts to disk, but our in-memory index doesn't know yet
            self.repo
                .index()
                .and_then(|mut idx| idx.read(true).map(|_| ()))
                .map_err(CascadeError::Git)?;

            debug!("Conflicted state written and index reloaded - auto-resolve can now process conflicts");

            return Err(CascadeError::branch(format!(
                "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
            )));
        }

        // Write merged tree
        let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
        let merged_tree = self
            .repo
            .find_tree(merged_tree_oid)
            .map_err(CascadeError::Git)?;

        // Create new commit with original message (preserve it exactly)
        let signature = self.get_signature()?;
        let message = commit.message().unwrap_or("Cherry-picked commit");

        let new_commit_oid = self
            .repo
            .commit(
                Some("HEAD"),
                &signature,
                &signature,
                message,
                &merged_tree,
                &[&head_commit],
            )
            .map_err(CascadeError::Git)?;

        // Update working directory to reflect the new commit
        let new_commit = self
            .repo
            .find_commit(new_commit_oid)
            .map_err(CascadeError::Git)?;
        let new_tree = new_commit.tree().map_err(CascadeError::Git)?;

        self.repo
            .checkout_tree(
                new_tree.as_object(),
                Some(git2::build::CheckoutBuilder::new().force()),
            )
            .map_err(CascadeError::Git)?;

        tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
        Ok(new_commit_oid.to_string())
    }

    /// Check for merge conflicts in the index
    pub fn has_conflicts(&self) -> Result<bool> {
        let index = self.repo.index().map_err(CascadeError::Git)?;
        Ok(index.has_conflicts())
    }

    /// Get list of conflicted files
    pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
        let index = self.repo.index().map_err(CascadeError::Git)?;

        let mut conflicts = Vec::new();

        // Iterate through index conflicts
        let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;

        for conflict in conflict_iter {
            let conflict = conflict.map_err(CascadeError::Git)?;
            if let Some(our) = conflict.our {
                if let Ok(path) = std::str::from_utf8(&our.path) {
                    conflicts.push(path.to_string());
                }
            } else if let Some(their) = conflict.their {
                if let Ok(path) = std::str::from_utf8(&their.path) {
                    conflicts.push(path.to_string());
                }
            }
        }

        Ok(conflicts)
    }

    /// Fetch from remote origin
    pub fn fetch(&self) -> Result<()> {
        tracing::debug!("Fetching from origin");

        // CRITICAL: Ensure index is closed before fetch operation
        // This prevents "index is locked" errors when fetch is called after cherry-pick/commit
        self.ensure_index_closed()?;

        let mut remote = self
            .repo
            .find_remote("origin")
            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;

        // Configure callbacks with SSL settings from git config
        let callbacks = self.configure_remote_callbacks()?;

        // Fetch options with authentication and SSL config
        let mut fetch_options = git2::FetchOptions::new();
        fetch_options.remote_callbacks(callbacks);

        // Fetch with authentication
        match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
            Ok(_) => {
                tracing::debug!("Fetch completed successfully");
                Ok(())
            }
            Err(e) => {
                if self.should_retry_with_default_credentials(&e) {
                    tracing::debug!(
                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
                        e.class(), e.code(), e
                    );

                    // Retry with DefaultCredentials for corporate networks
                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
                    let mut fetch_options = git2::FetchOptions::new();
                    fetch_options.remote_callbacks(callbacks);

                    match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
                        Ok(_) => {
                            tracing::debug!("Fetch succeeded with DefaultCredentials");
                            return Ok(());
                        }
                        Err(retry_error) => {
                            tracing::debug!(
                                "DefaultCredentials retry failed: {}, falling back to git CLI",
                                retry_error
                            );
                            return self.fetch_with_git_cli();
                        }
                    }
                }

                if self.should_fallback_to_git_cli(&e) {
                    tracing::debug!(
                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
                        e.class(), e.code(), e
                    );
                    return self.fetch_with_git_cli();
                }
                Err(CascadeError::Git(e))
            }
        }
    }

    /// Fetch from remote with exponential backoff retry logic
    /// This is critical for force push safety checks to prevent data loss from stale refs
    pub fn fetch_with_retry(&self) -> Result<()> {
        const MAX_RETRIES: u32 = 3;
        const BASE_DELAY_MS: u64 = 500;

        let mut last_error = None;

        for attempt in 0..MAX_RETRIES {
            match self.fetch() {
                Ok(_) => return Ok(()),
                Err(e) => {
                    last_error = Some(e);

                    if attempt < MAX_RETRIES - 1 {
                        let delay_ms = BASE_DELAY_MS * 2_u64.pow(attempt);
                        debug!(
                            "Fetch attempt {} failed, retrying in {}ms...",
                            attempt + 1,
                            delay_ms
                        );
                        std::thread::sleep(std::time::Duration::from_millis(delay_ms));
                    }
                }
            }
        }

        // All retries failed - this is CRITICAL for force push safety
        Err(CascadeError::Git(git2::Error::from_str(&format!(
            "Critical: Failed to fetch remote refs after {} attempts. Cannot safely proceed with force push - \
             stale remote refs could cause data loss. Error: {}. Please check network connection.",
            MAX_RETRIES,
            last_error.unwrap()
        ))))
    }

    /// Fetch and fast-forward a local branch ref to match origin, without checkout.
    /// Works safely in worktrees where the branch may be checked out elsewhere.
    pub fn update_local_branch_from_remote(&self, branch: &str) -> Result<()> {
        tracing::debug!(
            "Updating local branch '{}' from remote (worktree-safe)",
            branch
        );

        // Retry fetch with backoff to handle transient index locks (e.g. an IDE or Git GUI)
        let mut last_error = None;
        for attempt in 0..3u32 {
            match self.fetch() {
                Ok(_) => {
                    last_error = None;
                    break;
                }
                Err(e) => {
                    let is_locked = e.to_string().contains("Locked")
                        || e.to_string().contains("index is locked");
                    last_error = Some(e);
                    if is_locked && attempt < 2 {
                        let delay = std::time::Duration::from_millis(500 * 2_u64.pow(attempt));
                        tracing::debug!(
                            "Index locked on fetch attempt {}, retrying in {:?}...",
                            attempt + 1,
                            delay
                        );
                        std::thread::sleep(delay);
                    } else {
                        break;
                    }
                }
            }
        }
        if let Some(e) = last_error {
            return Err(e);
        }

        let remote_ref = format!("refs/remotes/origin/{branch}");
        let remote_oid = self.repo.refname_to_id(&remote_ref).map_err(|e| {
            CascadeError::branch(format!("Remote branch 'origin/{branch}' not found: {e}"))
        })?;

        let local_ref = format!("refs/heads/{branch}");
        let local_oid = self.repo.refname_to_id(&local_ref).ok();

        if let Some(local_oid) = local_oid {
            if local_oid == remote_oid {
                tracing::debug!("{branch} already up to date");
                return Ok(());
            }

            let merge_base = self
                .repo
                .merge_base(local_oid, remote_oid)
                .map_err(CascadeError::Git)?;

            if merge_base != local_oid {
                return Err(CascadeError::branch(format!(
                    "Branch '{branch}' has diverged from 'origin/{branch}'. \
                     Local has commits not in remote. Try: git reset --hard origin/{branch}"
                )));
            }
        }

        self.repo
            .reference(
                &local_ref,
                remote_oid,
                true,
                "sync: fast-forward from origin",
            )
            .map_err(|e| CascadeError::branch(format!("Failed to update '{branch}': {e}")))?;

        tracing::debug!("Fast-forwarded {branch} to {remote_oid}");
        Ok(())
    }

    /// Pull changes from remote (fetch + merge)
    pub fn pull(&self, branch: &str) -> Result<()> {
        tracing::debug!("Pulling branch: {}", branch);

        // First fetch - this now includes TLS fallback
        match self.fetch() {
            Ok(_) => {}
            Err(e) => {
                // If fetch failed even with CLI fallback, try full git pull as last resort
                let error_string = e.to_string();
                if error_string.contains("TLS stream") || error_string.contains("SSL") {
                    tracing::warn!(
                        "git2 error detected: {}, falling back to git CLI for pull operation",
                        e
                    );
                    return self.pull_with_git_cli(branch);
                }
                return Err(e);
            }
        }

        // Get remote tracking branch
        let remote_branch_name = format!("origin/{branch}");
        let remote_oid = self
            .repo
            .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
            .map_err(|e| {
                CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
            })?;

        let remote_commit = self
            .repo
            .find_commit(remote_oid)
            .map_err(CascadeError::Git)?;

        // Get local branch tip (not HEAD — we may be on a different branch)
        let local_refname = format!("refs/heads/{branch}");
        let local_oid = self
            .repo
            .refname_to_id(&local_refname)
            .map_err(|e| CascadeError::branch(format!("Local branch {branch} not found: {e}")))?;
        let head_commit = self
            .repo
            .find_commit(local_oid)
            .map_err(CascadeError::Git)?;

        // Check if already up to date
        if head_commit.id() == remote_commit.id() {
            tracing::debug!("Already up to date");
            return Ok(());
        }

        // Check if we can fast-forward (local is ancestor of remote)
        let merge_base_oid = self
            .repo
            .merge_base(head_commit.id(), remote_commit.id())
            .map_err(CascadeError::Git)?;

        if merge_base_oid == head_commit.id() {
            // Fast-forward: local is direct ancestor of remote, just move pointer
            tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());

            // Update the branch reference to point to remote commit
            self.repo
                .reference(&local_refname, remote_oid, true, "pull: Fast-forward")
                .map_err(CascadeError::Git)?;

            // Only update HEAD and working directory if we're on this branch
            let on_this_branch = self
                .repo
                .head()
                .ok()
                .and_then(|h| h.shorthand().map(|s| s.to_string()))
                .as_deref()
                == Some(branch);

            if on_this_branch {
                self.repo
                    .set_head(&local_refname)
                    .map_err(CascadeError::Git)?;
                self.repo
                    .checkout_head(Some(
                        git2::build::CheckoutBuilder::new()
                            .force()
                            .remove_untracked(false),
                    ))
                    .map_err(CascadeError::Git)?;
            }

            tracing::debug!("Fast-forwarded to {}", remote_commit.id());
            return Ok(());
        }

        // If we can't fast-forward, the local branch has diverged
        // This should NOT happen on protected branches!
        Err(CascadeError::branch(format!(
            "Branch '{}' has diverged from remote. Local has commits not in remote. \
             Protected branches should not have local commits. \
             Try: git reset --hard origin/{}",
            branch, branch
        )))
    }

    /// Push current branch to remote
    pub fn push(&self, branch: &str) -> Result<()> {
        // Pushing branch to remote

        let mut remote = self
            .repo
            .find_remote("origin")
            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;

        let remote_url = remote.url().unwrap_or("unknown").to_string();
        tracing::debug!("Remote URL: {}", remote_url);

        let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
        tracing::debug!("Push refspec: {}", refspec);

        // Configure callbacks with enhanced SSL settings and error handling
        let mut callbacks = self.configure_remote_callbacks()?;

        // Add enhanced progress and error callbacks for better debugging
        callbacks.push_update_reference(|refname, status| {
            if let Some(msg) = status {
                tracing::debug!("Push failed for ref {}: {}", refname, msg);
                return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
            }
            tracing::debug!("Push succeeded for ref: {}", refname);
            Ok(())
        });

        // Push options with authentication and SSL config
        let mut push_options = git2::PushOptions::new();
        push_options.remote_callbacks(callbacks);

        // Attempt push with enhanced error reporting
        match remote.push(&[&refspec], Some(&mut push_options)) {
            Ok(_) => {
                tracing::debug!("Push completed successfully for branch: {}", branch);
                Ok(())
            }
            Err(e) => {
                tracing::debug!(
                    "git2 push error: {} (class: {:?}, code: {:?})",
                    e,
                    e.class(),
                    e.code()
                );

                if self.should_retry_with_default_credentials(&e) {
                    tracing::debug!(
                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
                        e.class(), e.code(), e
                    );

                    // Retry with DefaultCredentials for corporate networks
                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
                    let mut push_options = git2::PushOptions::new();
                    push_options.remote_callbacks(callbacks);

                    match remote.push(&[&refspec], Some(&mut push_options)) {
                        Ok(_) => {
                            tracing::debug!("Push succeeded with DefaultCredentials");
                            return Ok(());
                        }
                        Err(retry_error) => {
                            tracing::debug!(
                                "DefaultCredentials retry failed: {}, falling back to git CLI",
                                retry_error
                            );
                            return self.push_with_git_cli(branch);
                        }
                    }
                }

                if self.should_fallback_to_git_cli(&e) {
                    tracing::debug!(
                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
                        e.class(), e.code(), e
                    );
                    return self.push_with_git_cli(branch);
                }

                // Create concise error message
                let error_msg = if e.to_string().contains("authentication") {
                    format!(
                        "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
                    )
                } else {
                    format!("Failed to push branch '{branch}': {e}")
                };

                Err(CascadeError::branch(error_msg))
            }
        }
    }

    /// Fallback push method using git CLI instead of git2
    /// This is used when git2 has TLS/SSL or auth issues but git CLI works fine
    fn push_with_git_cli(&self, branch: &str) -> Result<()> {
        // Ensure index is closed before CLI command
        self.ensure_index_closed()?;

        let output = std::process::Command::new("git")
            .args(["push", "origin", branch])
            .current_dir(&self.path)
            .output()
            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;

        if output.status.success() {
            // Silent success - no need to log when fallback works
            Ok(())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let _stdout = String::from_utf8_lossy(&output.stdout);
            // Extract the most relevant error message
            let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
                "Network error: Unable to connect to repository (VPN may be required)".to_string()
            } else if stderr.contains("repository") && stderr.contains("not found") {
                "Repository not found - check your Bitbucket configuration".to_string()
            } else if stderr.contains("authentication") || stderr.contains("403") {
                "Authentication failed - check your credentials".to_string()
            } else {
                // For other errors, just show the stderr without the verbose prefix
                stderr.trim().to_string()
            };
            Err(CascadeError::branch(error_msg))
        }
    }

    /// Fallback fetch method using git CLI instead of git2
    /// This is used when git2 has TLS/SSL issues but git CLI works fine
    fn fetch_with_git_cli(&self) -> Result<()> {
        tracing::debug!("Using git CLI fallback for fetch operation");

        // Ensure index is closed before CLI command
        self.ensure_index_closed()?;

        let output = std::process::Command::new("git")
            .args(["fetch", "origin"])
            .current_dir(&self.path)
            .output()
            .map_err(|e| {
                CascadeError::Git(git2::Error::from_str(&format!(
                    "Failed to execute git command: {e}"
                )))
            })?;

        if output.status.success() {
            tracing::debug!("Git CLI fetch succeeded");
            Ok(())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            let error_msg = format!(
                "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
                output.status, stdout, stderr
            );
            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
        }
    }

    /// Fallback pull method using git CLI instead of git2
    /// This is used when git2 has TLS/SSL issues but git CLI works fine
    fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
        tracing::debug!("Using git CLI fallback for pull operation: {}", branch);

        // Ensure index is closed before CLI command
        self.ensure_index_closed()?;

        let output = std::process::Command::new("git")
            .args(["pull", "origin", branch])
            .current_dir(&self.path)
            .output()
            .map_err(|e| {
                CascadeError::Git(git2::Error::from_str(&format!(
                    "Failed to execute git command: {e}"
                )))
            })?;

        if output.status.success() {
            tracing::debug!("Git CLI pull succeeded for branch: {}", branch);
            Ok(())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            let error_msg = format!(
                "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
                branch, output.status, stdout, stderr
            );
            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
        }
    }

    /// Fallback force push method using git CLI instead of git2
    /// This is used when git2 has TLS/SSL issues but git CLI works fine
    fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
        tracing::debug!(
            "Using git CLI fallback for force push operation: {}",
            branch
        );

        let output = std::process::Command::new("git")
            .args(["push", "--force", "origin", branch])
            .current_dir(&self.path)
            .output()
            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;

        if output.status.success() {
            tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
            Ok(())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            let error_msg = format!(
                "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
                branch, output.status, stdout, stderr
            );
            Err(CascadeError::branch(error_msg))
        }
    }

    /// Delete a local branch
    pub fn delete_branch(&self, name: &str) -> Result<()> {
        self.delete_branch_with_options(name, false)
    }

    /// Delete a local branch with force option to bypass safety checks
    pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
        self.delete_branch_with_options(name, true)
    }

    /// Internal branch deletion implementation with safety options
    fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
        debug!("Attempting to delete branch: {}", name);

        // Enhanced safety check: Detect unpushed commits before deletion
        if !force_unsafe {
            let safety_result = self.check_branch_deletion_safety(name)?;
            if let Some(safety_info) = safety_result {
                // Branch has unpushed commits, get user confirmation
                self.handle_branch_deletion_confirmation(name, &safety_info)?;
            }
        }

        let mut branch = self
            .repo
            .find_branch(name, git2::BranchType::Local)
            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;

        branch
            .delete()
            .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;

        debug!("Successfully deleted branch '{}'", name);
        Ok(())
    }

    /// Get commits between two references
    pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
        let from_oid = self
            .repo
            .refname_to_id(&format!("refs/heads/{from}"))
            .or_else(|_| Oid::from_str(from))
            .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;

        let to_oid = self
            .repo
            .refname_to_id(&format!("refs/heads/{to}"))
            .or_else(|_| Oid::from_str(to))
            .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;

        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;

        revwalk.push(to_oid).map_err(CascadeError::Git)?;
        revwalk.hide(from_oid).map_err(CascadeError::Git)?;

        let mut commits = Vec::new();
        for oid in revwalk {
            let oid = oid.map_err(CascadeError::Git)?;
            let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
            commits.push(commit);
        }

        Ok(commits)
    }

    /// Force push one branch's content to another branch name
    /// This is used to preserve PR history while updating branch contents after rebase
    pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
        self.force_push_branch_with_options(target_branch, source_branch, false)
    }

    /// Force push with explicit force flag to bypass safety checks
    pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
        self.force_push_branch_with_options(target_branch, source_branch, true)
    }

    /// Internal force push implementation with safety options
    fn force_push_branch_with_options(
        &self,
        target_branch: &str,
        source_branch: &str,
        force_unsafe: bool,
    ) -> Result<()> {
        debug!(
            "Force pushing {} content to {} to preserve PR history",
            source_branch, target_branch
        );

        // Enhanced safety check: Detect potential data loss and get user confirmation
        if !force_unsafe {
            let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
            if let Some(backup_info) = safety_result {
                // Create backup branch before force push
                self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
                Output::sub_item(format!(
                    "Created backup branch: {}",
                    backup_info.backup_branch_name
                ));
            }
        }

        // First, ensure we have the latest changes for the source branch
        let source_ref = self
            .repo
            .find_reference(&format!("refs/heads/{source_branch}"))
            .map_err(|e| {
                CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
            })?;
        let _source_commit = source_ref.peel_to_commit().map_err(|e| {
            CascadeError::config(format!(
                "Failed to get commit for source branch {source_branch}: {e}"
            ))
        })?;

        // Force push to remote without modifying local target branch
        let mut remote = self
            .repo
            .find_remote("origin")
            .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;

        // Push source branch content to remote target branch
        let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");

        // Configure callbacks with SSL settings from git config
        let callbacks = self.configure_remote_callbacks()?;

        // Push options for force push with SSL config
        let mut push_options = git2::PushOptions::new();
        push_options.remote_callbacks(callbacks);

        match remote.push(&[&refspec], Some(&mut push_options)) {
            Ok(_) => {}
            Err(e) => {
                if self.should_retry_with_default_credentials(&e) {
                    tracing::debug!(
                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
                        e.class(), e.code(), e
                    );

                    // Retry with DefaultCredentials for corporate networks
                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
                    let mut push_options = git2::PushOptions::new();
                    push_options.remote_callbacks(callbacks);

                    match remote.push(&[&refspec], Some(&mut push_options)) {
                        Ok(_) => {
                            tracing::debug!("Force push succeeded with DefaultCredentials");
                            // Success - continue to normal success path
                        }
                        Err(retry_error) => {
                            tracing::debug!(
                                "DefaultCredentials retry failed: {}, falling back to git CLI",
                                retry_error
                            );
                            return self.force_push_with_git_cli(target_branch);
                        }
                    }
                } else if self.should_fallback_to_git_cli(&e) {
                    tracing::debug!(
                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
                        e.class(), e.code(), e
                    );
                    return self.force_push_with_git_cli(target_branch);
                } else {
                    return Err(CascadeError::config(format!(
                        "Failed to force push {target_branch}: {e}"
                    )));
                }
            }
        }

        tracing::debug!(
            "Successfully force pushed {} to preserve PR history",
            target_branch
        );
        Ok(())
    }

    /// Enhanced safety check for force push operations with user confirmation
    /// Returns backup info if data would be lost and user confirms
    fn check_force_push_safety_enhanced(
        &self,
        target_branch: &str,
    ) -> Result<Option<ForceBackupInfo>> {
        // First fetch latest remote changes to ensure we have up-to-date information
        match self.fetch() {
            Ok(_) => {}
            Err(e) => {
                // If fetch fails, warn but don't block the operation
                debug!("Could not fetch latest changes for safety check: {}", e);
            }
        }

        // Check if there are commits on the remote that would be lost
        let remote_ref = format!("refs/remotes/origin/{target_branch}");
        let local_ref = format!("refs/heads/{target_branch}");

        // Try to find both local and remote references
        let local_commit = match self.repo.find_reference(&local_ref) {
            Ok(reference) => reference.peel_to_commit().ok(),
            Err(_) => None,
        };

        let remote_commit = match self.repo.find_reference(&remote_ref) {
            Ok(reference) => reference.peel_to_commit().ok(),
            Err(_) => None,
        };

        // If we have both commits, check for divergence
        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
            if local.id() != remote.id() {
                // Check if the remote has commits that the local doesn't have
                let merge_base_oid = self
                    .repo
                    .merge_base(local.id(), remote.id())
                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;

                // If merge base != remote commit, remote has commits that would be lost
                if merge_base_oid != remote.id() {
                    let commits_to_lose = self.count_commits_between(
                        &merge_base_oid.to_string(),
                        &remote.id().to_string(),
                    )?;

                    // Create backup branch name with timestamp
                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");

                    debug!(
                        "Force push to '{}' would overwrite {} commits on remote",
                        target_branch, commits_to_lose
                    );

                    // Check if we're in a non-interactive environment (CI/testing)
                    if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
                    {
                        info!(
                            "Non-interactive environment detected, proceeding with backup creation"
                        );
                        return Ok(Some(ForceBackupInfo {
                            backup_branch_name,
                            remote_commit_id: remote.id().to_string(),
                            commits_that_would_be_lost: commits_to_lose,
                        }));
                    }

                    // Automatically create backup - this is normal stacked diff workflow
                    return Ok(Some(ForceBackupInfo {
                        backup_branch_name,
                        remote_commit_id: remote.id().to_string(),
                        commits_that_would_be_lost: commits_to_lose,
                    }));
                }
            }
        }

        Ok(None)
    }

    /// Check force push safety without user confirmation (auto-creates backup)
    /// Used for automated operations like sync where user already confirmed the operation
    ///
    /// When skip_fetch=false: Fetches latest remote state before checking (default behavior)
    /// When skip_fetch=true: Assumes fetch already done (batch operations)
    fn check_force_push_safety_auto_no_fetch(
        &self,
        target_branch: &str,
    ) -> Result<Option<ForceBackupInfo>> {
        // Check if there are commits on the remote that would be lost
        let remote_ref = format!("refs/remotes/origin/{target_branch}");
        let local_ref = format!("refs/heads/{target_branch}");

        // Try to find both local and remote references
        let local_commit = match self.repo.find_reference(&local_ref) {
            Ok(reference) => reference.peel_to_commit().ok(),
            Err(_) => None,
        };

        let remote_commit = match self.repo.find_reference(&remote_ref) {
            Ok(reference) => reference.peel_to_commit().ok(),
            Err(_) => None,
        };

        // If we have both commits, check for divergence
        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
            if local.id() != remote.id() {
                // Check if the remote has commits that the local doesn't have
                let merge_base_oid = self
                    .repo
                    .merge_base(local.id(), remote.id())
                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;

                // If merge base != remote commit, remote has commits that would be lost
                if merge_base_oid != remote.id() {
                    let commits_to_lose = self.count_commits_between(
                        &merge_base_oid.to_string(),
                        &remote.id().to_string(),
                    )?;

                    // Create backup branch name with timestamp
                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");

                    tracing::debug!(
                        "Auto-creating backup '{}' for force push to '{}' (would overwrite {} commits)",
                        backup_branch_name, target_branch, commits_to_lose
                    );

                    // Automatically create backup without confirmation
                    return Ok(Some(ForceBackupInfo {
                        backup_branch_name,
                        remote_commit_id: remote.id().to_string(),
                        commits_that_would_be_lost: commits_to_lose,
                    }));
                }
            }
        }

        Ok(None)
    }

    /// Create a backup branch pointing to the remote commit that would be lost
    fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
        let backup_branch_name = format!("{original_branch}_backup_{timestamp}");

        // Parse the commit ID
        let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
            CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
        })?;

        // Find the commit
        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
            CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
        })?;

        // Create the backup branch
        self.repo
            .branch(&backup_branch_name, &commit, false)
            .map_err(|e| {
                CascadeError::config(format!(
                    "Failed to create backup branch {backup_branch_name}: {e}"
                ))
            })?;

        debug!(
            "Created backup branch '{}' pointing to {}",
            backup_branch_name,
            &remote_commit_id[..8]
        );
        Ok(())
    }

    /// Check if branch deletion is safe by detecting unpushed commits
    /// Returns safety info if there are concerns that need user attention
    fn check_branch_deletion_safety(
        &self,
        branch_name: &str,
    ) -> Result<Option<BranchDeletionSafety>> {
        // First, try to fetch latest remote changes
        match self.fetch() {
            Ok(_) => {}
            Err(e) => {
                warn!(
                    "Could not fetch latest changes for branch deletion safety check: {}",
                    e
                );
            }
        }

        // Find the branch
        let branch = self
            .repo
            .find_branch(branch_name, git2::BranchType::Local)
            .map_err(|e| {
                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
            })?;

        let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
            CascadeError::branch(format!(
                "Could not get commit for branch '{branch_name}': {e}"
            ))
        })?;

        // Determine the main branch (try common names)
        let main_branch_name = self.detect_main_branch()?;

        // Check if branch is merged to main
        let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;

        // Find the upstream/remote tracking branch
        let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);

        let mut unpushed_commits = Vec::new();

        // Check for unpushed commits compared to remote tracking branch
        if let Some(ref remote_branch) = remote_tracking_branch {
            match self.get_commits_between(remote_branch, branch_name) {
                Ok(commits) => {
                    unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
                }
                Err(_) => {
                    // If we can't compare with remote, check against main branch
                    if !is_merged_to_main {
                        if let Ok(commits) =
                            self.get_commits_between(&main_branch_name, branch_name)
                        {
                            unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
                        }
                    }
                }
            }
        } else if !is_merged_to_main {
            // No remote tracking branch, check against main
            if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
                unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
            }
        }

        // If there are concerns, return safety info
        if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
        {
            Ok(Some(BranchDeletionSafety {
                unpushed_commits,
                remote_tracking_branch,
                is_merged_to_main,
                main_branch_name,
            }))
        } else {
            Ok(None)
        }
    }

    /// Handle user confirmation for branch deletion with safety concerns
    fn handle_branch_deletion_confirmation(
        &self,
        branch_name: &str,
        safety_info: &BranchDeletionSafety,
    ) -> Result<()> {
        // Check if we're in a non-interactive environment
        if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
            return Err(CascadeError::branch(
                format!(
                    "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
                    safety_info.unpushed_commits.len()
                )
            ));
        }

        // Interactive warning and confirmation
        println!();
        Output::warning("BRANCH DELETION WARNING");
        println!("Branch '{branch_name}' has potential issues:");

        if !safety_info.unpushed_commits.is_empty() {
            println!(
                "\n🔍 Unpushed commits ({} total):",
                safety_info.unpushed_commits.len()
            );

            // Show details of unpushed commits
            for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
                if let Ok(oid) = Oid::from_str(commit_id) {
                    if let Ok(commit) = self.repo.find_commit(oid) {
                        let short_hash = &commit_id[..8];
                        let summary = commit.summary().unwrap_or("<no message>");
                        println!("  {}. {} - {}", i + 1, short_hash, summary);
                    }
                }
            }

            if safety_info.unpushed_commits.len() > 5 {
                println!(
                    "  ... and {} more commits",
                    safety_info.unpushed_commits.len() - 5
                );
            }
        }

        if !safety_info.is_merged_to_main {
            println!();
            crate::cli::output::Output::section("Branch status");
            crate::cli::output::Output::bullet(format!(
                "Not merged to '{}'",
                safety_info.main_branch_name
            ));
            if let Some(ref remote) = safety_info.remote_tracking_branch {
                crate::cli::output::Output::bullet(format!("Remote tracking branch: {remote}"));
            } else {
                crate::cli::output::Output::bullet("No remote tracking branch");
            }
        }

        println!();
        crate::cli::output::Output::section("Safer alternatives");
        if !safety_info.unpushed_commits.is_empty() {
            if let Some(ref _remote) = safety_info.remote_tracking_branch {
                println!("  • Push commits first: git push origin {branch_name}");
            } else {
                println!("  • Create and push to remote: git push -u origin {branch_name}");
            }
        }
        if !safety_info.is_merged_to_main {
            println!(
                "  • Merge to {} first: git checkout {} && git merge {branch_name}",
                safety_info.main_branch_name, safety_info.main_branch_name
            );
        }

        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Do you want to proceed with deleting this branch?")
            .default(false)
            .interact()
            .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;

        if !confirmed {
            return Err(CascadeError::branch(
                "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
            ));
        }

        Ok(())
    }

    /// Detect the main branch name (main, master, develop)
    pub fn detect_main_branch(&self) -> Result<String> {
        let main_candidates = ["main", "master", "develop", "trunk"];

        for candidate in &main_candidates {
            if self
                .repo
                .find_branch(candidate, git2::BranchType::Local)
                .is_ok()
            {
                return Ok(candidate.to_string());
            }
        }

        // Fallback to HEAD's target if it's a symbolic reference
        if let Ok(head) = self.repo.head() {
            if let Some(name) = head.shorthand() {
                return Ok(name.to_string());
            }
        }

        // Final fallback
        Ok("main".to_string())
    }

    /// Check if a branch is merged to the main branch
    fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
        // Get the commits between main and the branch
        match self.get_commits_between(main_branch, branch_name) {
            Ok(commits) => Ok(commits.is_empty()),
            Err(_) => {
                // If we can't determine, assume not merged for safety
                Ok(false)
            }
        }
    }

    /// Get the remote tracking branch for a local branch
    fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
        // Try common remote tracking branch patterns
        let remote_candidates = [
            format!("origin/{branch_name}"),
            format!("remotes/origin/{branch_name}"),
        ];

        for candidate in &remote_candidates {
            if self
                .repo
                .find_reference(&format!(
                    "refs/remotes/{}",
                    candidate.replace("remotes/", "")
                ))
                .is_ok()
            {
                return Some(candidate.clone());
            }
        }

        None
    }

    /// Check if checkout operation is safe
    fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
        // Check if there are uncommitted changes
        let is_dirty = self.is_dirty()?;
        if !is_dirty {
            // No uncommitted changes, checkout is safe
            return Ok(None);
        }

        // Get current branch for context
        let current_branch = self.get_current_branch().ok();

        // Get detailed information about uncommitted changes
        let modified_files = self.get_modified_files()?;
        let staged_files = self.get_staged_files()?;
        let untracked_files = self.get_untracked_files()?;

        let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();

        if has_uncommitted_changes || !untracked_files.is_empty() {
            return Ok(Some(CheckoutSafety {
                has_uncommitted_changes,
                modified_files,
                staged_files,
                untracked_files,
                stash_created: None,
                current_branch,
            }));
        }

        Ok(None)
    }

    /// Handle user confirmation for checkout operations with uncommitted changes
    fn handle_checkout_confirmation(
        &self,
        target: &str,
        safety_info: &CheckoutSafety,
    ) -> Result<()> {
        // Check if we're in a non-interactive environment FIRST (before any output)
        let is_ci = std::env::var("CI").is_ok();
        let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
        let is_non_interactive = is_ci || no_confirm;

        if is_non_interactive {
            return Err(CascadeError::branch(
                format!(
                    "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
                )
            ));
        }

        // Interactive warning and confirmation
        println!("\nCHECKOUT WARNING");
        println!("Attempting to checkout: {}", target);
        println!("You have uncommitted changes that could be lost:");

        if !safety_info.modified_files.is_empty() {
            println!("\nModified files ({}):", safety_info.modified_files.len());
            for file in safety_info.modified_files.iter().take(10) {
                println!("   - {file}");
            }
            if safety_info.modified_files.len() > 10 {
                println!("   ... and {} more", safety_info.modified_files.len() - 10);
            }
        }

        if !safety_info.staged_files.is_empty() {
            println!("\nStaged files ({}):", safety_info.staged_files.len());
            for file in safety_info.staged_files.iter().take(10) {
                println!("   - {file}");
            }
            if safety_info.staged_files.len() > 10 {
                println!("   ... and {} more", safety_info.staged_files.len() - 10);
            }
        }

        if !safety_info.untracked_files.is_empty() {
            println!("\nUntracked files ({}):", safety_info.untracked_files.len());
            for file in safety_info.untracked_files.iter().take(5) {
                println!("   - {file}");
            }
            if safety_info.untracked_files.len() > 5 {
                println!("   ... and {} more", safety_info.untracked_files.len() - 5);
            }
        }

        println!("\nOptions:");
        println!("1. Stash changes and checkout (recommended)");
        println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
        println!("3. Cancel checkout");

        // Use proper selection dialog instead of y/n confirmation
        let selection = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("Choose an action")
            .items(&[
                "Stash changes and checkout (recommended)",
                "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
                "Cancel checkout",
            ])
            .default(0)
            .interact()
            .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;

        match selection {
            0 => {
                // Option 1: Stash changes and checkout
                let stash_message = format!(
                    "Auto-stash before checkout to {} at {}",
                    target,
                    chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
                );

                match self.create_stash(&stash_message) {
                    Ok(stash_id) => {
                        crate::cli::output::Output::success(format!(
                            "Created stash: {stash_message} ({stash_id})"
                        ));
                        crate::cli::output::Output::tip("You can restore with: git stash pop");
                    }
                    Err(e) => {
                        crate::cli::output::Output::error(format!("Failed to create stash: {e}"));

                        // If stash failed, provide better options
                        use dialoguer::Select;
                        let stash_failed_options = vec![
                            "Commit staged changes and proceed",
                            "Force checkout (WILL LOSE CHANGES)",
                            "Cancel and handle manually",
                        ];

                        let stash_selection = Select::with_theme(&ColorfulTheme::default())
                            .with_prompt("Stash failed. What would you like to do?")
                            .items(&stash_failed_options)
                            .default(0)
                            .interact()
                            .map_err(|e| {
                                CascadeError::branch(format!("Could not get user selection: {e}"))
                            })?;

                        match stash_selection {
                            0 => {
                                // Try to commit staged changes
                                let staged_files = self.get_staged_files()?;
                                if !staged_files.is_empty() {
                                    println!(
                                        "📝 Committing {} staged files...",
                                        staged_files.len()
                                    );
                                    match self
                                        .commit_staged_changes("WIP: Auto-commit before checkout")
                                    {
                                        Ok(Some(commit_hash)) => {
                                            crate::cli::output::Output::success(format!(
                                                "Committed staged changes as {}",
                                                &commit_hash[..8]
                                            ));
                                            crate::cli::output::Output::tip(
                                                "You can undo with: git reset HEAD~1",
                                            );
                                        }
                                        Ok(None) => {
                                            crate::cli::output::Output::info(
                                                "No staged changes found to commit",
                                            );
                                        }
                                        Err(commit_err) => {
                                            println!(
                                                "❌ Failed to commit staged changes: {commit_err}"
                                            );
                                            return Err(CascadeError::branch(
                                                "Could not commit staged changes".to_string(),
                                            ));
                                        }
                                    }
                                } else {
                                    println!("No staged changes to commit");
                                }
                            }
                            1 => {
                                // Force checkout anyway
                                Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
                            }
                            2 => {
                                // Cancel
                                return Err(CascadeError::branch(
                                    "Checkout cancelled. Please handle changes manually and try again.".to_string(),
                                ));
                            }
                            _ => unreachable!(),
                        }
                    }
                }
            }
            1 => {
                // Option 2: Force checkout (lose changes)
                Output::warning(
                    "Proceeding with force checkout - uncommitted changes will be lost!",
                );
            }
            2 => {
                // Option 3: Cancel
                return Err(CascadeError::branch(
                    "Checkout cancelled by user".to_string(),
                ));
            }
            _ => unreachable!(),
        }

        Ok(())
    }

    /// Create a stash with uncommitted changes
    fn create_stash(&self, message: &str) -> Result<String> {
        use crate::cli::output::Output;

        tracing::debug!("Creating stash: {}", message);

        // Use git CLI for stashing since git2 stashing is complex and unreliable
        let output = std::process::Command::new("git")
            .args(["stash", "push", "-m", message])
            .current_dir(&self.path)
            .output()
            .map_err(|e| {
                CascadeError::branch(format!("Failed to execute git stash command: {e}"))
            })?;

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);

            // Extract stash hash if available (git stash outputs like "Saved working directory and index state WIP on branch: message")
            let stash_id = if stdout.contains("Saved working directory") {
                // Get the most recent stash ID
                let stash_list_output = std::process::Command::new("git")
                    .args(["stash", "list", "-n", "1", "--format=%H"])
                    .current_dir(&self.path)
                    .output()
                    .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;

                if stash_list_output.status.success() {
                    String::from_utf8_lossy(&stash_list_output.stdout)
                        .trim()
                        .to_string()
                } else {
                    "stash@{0}".to_string() // fallback
                }
            } else {
                "stash@{0}".to_string() // fallback
            };

            Output::success(format!("Created stash: {} ({})", message, stash_id));
            Output::tip("You can restore with: git stash pop");
            Ok(stash_id)
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);

            // Check for common stash failure reasons
            if stderr.contains("No local changes to save")
                || stdout.contains("No local changes to save")
            {
                return Err(CascadeError::branch("No local changes to save".to_string()));
            }

            Err(CascadeError::branch(format!(
                "Failed to create stash: {}\nStderr: {}\nStdout: {}",
                output.status, stderr, stdout
            )))
        }
    }

    /// Get modified files in working directory
    fn get_modified_files(&self) -> Result<Vec<String>> {
        let mut opts = git2::StatusOptions::new();
        opts.include_untracked(false).include_ignored(false);

        let statuses = self
            .repo
            .statuses(Some(&mut opts))
            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;

        let mut modified_files = Vec::new();
        for status in statuses.iter() {
            let flags = status.status();
            if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
            {
                if let Some(path) = status.path() {
                    modified_files.push(path.to_string());
                }
            }
        }

        Ok(modified_files)
    }

    /// Get staged files in index
    pub fn get_staged_files(&self) -> Result<Vec<String>> {
        let mut opts = git2::StatusOptions::new();
        opts.include_untracked(false).include_ignored(false);

        let statuses = self
            .repo
            .statuses(Some(&mut opts))
            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;

        let mut staged_files = Vec::new();
        for status in statuses.iter() {
            let flags = status.status();
            if flags.contains(git2::Status::INDEX_MODIFIED)
                || flags.contains(git2::Status::INDEX_NEW)
                || flags.contains(git2::Status::INDEX_DELETED)
            {
                if let Some(path) = status.path() {
                    staged_files.push(path.to_string());
                }
            }
        }

        Ok(staged_files)
    }

    /// Count commits between two references
    fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
        let commits = self.get_commits_between(from, to)?;
        Ok(commits.len())
    }

    /// Resolve a reference (branch name, tag, or commit hash) to a commit
    pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
        // Try to parse as commit hash first
        if let Ok(oid) = Oid::from_str(reference) {
            if let Ok(commit) = self.repo.find_commit(oid) {
                return Ok(commit);
            }
        }

        // Try to resolve as a reference (branch, tag, etc.)
        let obj = self.repo.revparse_single(reference).map_err(|e| {
            CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
        })?;

        obj.peel_to_commit().map_err(|e| {
            CascadeError::branch(format!(
                "Reference '{reference}' does not point to a commit: {e}"
            ))
        })
    }

    /// Reset HEAD to a specific reference (soft reset)
    pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
        let target_commit = self.resolve_reference(target_ref)?;

        self.repo
            .reset(target_commit.as_object(), git2::ResetType::Soft, None)
            .map_err(CascadeError::Git)?;

        Ok(())
    }

    /// Reset working directory and index to match HEAD (hard reset)
    /// This clears all uncommitted changes and staged files
    pub fn reset_to_head(&self) -> Result<()> {
        tracing::debug!("Resetting working directory and index to HEAD");

        let repo_path = self.path();

        // Use lock retry wrapper to handle stale locks automatically
        crate::utils::git_lock::with_lock_retry(repo_path, || {
            let head = self.repo.head()?;
            let head_commit = head.peel_to_commit()?;

            // Hard reset: resets index and working tree
            let mut checkout_builder = git2::build::CheckoutBuilder::new();
            checkout_builder.force(); // Force checkout to overwrite any local changes
            checkout_builder.remove_untracked(false); // Don't remove untracked files

            self.repo.reset(
                head_commit.as_object(),
                git2::ResetType::Hard,
                Some(&mut checkout_builder),
            )?;

            Ok(())
        })?;

        tracing::debug!("Successfully reset working directory to HEAD");
        Ok(())
    }

    /// Find which branch contains a specific commit
    pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
        let oid = Oid::from_str(commit_hash).map_err(|e| {
            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
        })?;

        // Get all local branches
        let branches = self
            .repo
            .branches(Some(git2::BranchType::Local))
            .map_err(CascadeError::Git)?;

        for branch_result in branches {
            let (branch, _) = branch_result.map_err(CascadeError::Git)?;

            if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
                // Check if this branch contains the commit
                if let Ok(branch_head) = branch.get().peel_to_commit() {
                    // Walk the commit history from this branch's HEAD
                    let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
                    revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;

                    for commit_oid in revwalk {
                        let commit_oid = commit_oid.map_err(CascadeError::Git)?;
                        if commit_oid == oid {
                            return Ok(branch_name.to_string());
                        }
                    }
                }
            }
        }

        // If not found in any branch, might be on current HEAD
        Err(CascadeError::branch(format!(
            "Commit {commit_hash} not found in any local branch"
        )))
    }

    // Async wrappers for potentially blocking operations

    /// Fetch from remote origin (async)
    pub async fn fetch_async(&self) -> Result<()> {
        let repo_path = self.path.clone();
        crate::utils::async_ops::run_git_operation(move || {
            let repo = GitRepository::open(&repo_path)?;
            repo.fetch()
        })
        .await
    }

    /// Pull changes from remote (async)
    pub async fn pull_async(&self, branch: &str) -> Result<()> {
        let repo_path = self.path.clone();
        let branch_name = branch.to_string();
        crate::utils::async_ops::run_git_operation(move || {
            let repo = GitRepository::open(&repo_path)?;
            repo.pull(&branch_name)
        })
        .await
    }

    /// Push branch to remote (async)
    pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
        let repo_path = self.path.clone();
        let branch = branch_name.to_string();
        crate::utils::async_ops::run_git_operation(move || {
            let repo = GitRepository::open(&repo_path)?;
            repo.push(&branch)
        })
        .await
    }

    /// Cherry-pick commit (async)
    pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
        let repo_path = self.path.clone();
        let hash = commit_hash.to_string();
        crate::utils::async_ops::run_git_operation(move || {
            let repo = GitRepository::open(&repo_path)?;
            repo.cherry_pick(&hash)
        })
        .await
    }

    /// Get commit hashes between two refs (async)
    pub async fn get_commit_hashes_between_async(
        &self,
        from: &str,
        to: &str,
    ) -> Result<Vec<String>> {
        let repo_path = self.path.clone();
        let from_str = from.to_string();
        let to_str = to.to_string();
        crate::utils::async_ops::run_git_operation(move || {
            let repo = GitRepository::open(&repo_path)?;
            let commits = repo.get_commits_between(&from_str, &to_str)?;
            Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
        })
        .await
    }

    /// Reset a branch to point to a specific commit
    pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
        info!(
            "Resetting branch '{}' to commit {}",
            branch_name,
            &commit_hash[..8]
        );

        // Find the target commit
        let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
        })?;

        let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
        })?;

        // Find the branch
        let _branch = self
            .repo
            .find_branch(branch_name, git2::BranchType::Local)
            .map_err(|e| {
                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
            })?;

        // Update the branch reference to point to the target commit
        let branch_ref_name = format!("refs/heads/{branch_name}");
        self.repo
            .reference(
                &branch_ref_name,
                target_oid,
                true,
                &format!("Reset {branch_name} to {commit_hash}"),
            )
            .map_err(|e| {
                CascadeError::branch(format!(
                    "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
                ))
            })?;

        tracing::info!(
            "Successfully reset branch '{}' to commit {}",
            branch_name,
            &commit_hash[..8]
        );
        Ok(())
    }

    /// Detect the parent branch of the current branch using multiple strategies
    pub fn detect_parent_branch(&self) -> Result<Option<String>> {
        let current_branch = self.get_current_branch()?;

        // Strategy 1: Check if current branch has an upstream tracking branch
        if let Ok(Some(upstream)) = self.get_upstream_branch(&current_branch) {
            // Extract the branch name from "origin/branch-name" format
            if let Some(branch_name) = upstream.split('/').nth(1) {
                if self.branch_exists(branch_name) {
                    tracing::debug!(
                        "Detected parent branch '{}' from upstream tracking",
                        branch_name
                    );
                    return Ok(Some(branch_name.to_string()));
                }
            }
        }

        // Strategy 2: Use git's default branch detection
        if let Ok(default_branch) = self.detect_main_branch() {
            // Don't suggest the current branch as its own parent
            if current_branch != default_branch {
                tracing::debug!(
                    "Detected parent branch '{}' as repository default",
                    default_branch
                );
                return Ok(Some(default_branch));
            }
        }

        // Strategy 3: Find the branch with the most recent common ancestor
        // Get all local branches and find the one with the shortest commit distance
        if let Ok(branches) = self.list_branches() {
            let current_commit = self.get_head_commit()?;
            let current_commit_hash = current_commit.id().to_string();
            let current_oid = current_commit.id();

            let mut best_candidate = None;
            let mut best_distance = usize::MAX;

            for branch in branches {
                // Skip the current branch and any branches that look like version branches
                if branch == current_branch
                    || branch.contains("-v")
                    || branch.ends_with("-v2")
                    || branch.ends_with("-v3")
                {
                    continue;
                }

                if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
                    if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
                        // Find merge base between current branch and this branch
                        if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
                            // Count commits from merge base to current head
                            if let Ok(distance) = self.count_commits_between(
                                &merge_base_oid.to_string(),
                                &current_commit_hash,
                            ) {
                                // Prefer branches with shorter distances (more recent common ancestor)
                                // Also prefer branches that look like base branches
                                let is_likely_base = self.is_likely_base_branch(&branch);
                                let adjusted_distance = if is_likely_base {
                                    distance
                                } else {
                                    distance + 1000
                                };

                                if adjusted_distance < best_distance {
                                    best_distance = adjusted_distance;
                                    best_candidate = Some(branch.clone());
                                }
                            }
                        }
                    }
                }
            }

            if let Some(ref candidate) = best_candidate {
                tracing::debug!(
                    "Detected parent branch '{}' with distance {}",
                    candidate,
                    best_distance
                );
            }

            return Ok(best_candidate);
        }

        tracing::debug!("Could not detect parent branch for '{}'", current_branch);
        Ok(None)
    }

    /// Check if a branch name looks like a typical base branch
    fn is_likely_base_branch(&self, branch_name: &str) -> bool {
        let base_patterns = [
            "main",
            "master",
            "develop",
            "dev",
            "development",
            "staging",
            "stage",
            "release",
            "production",
            "prod",
        ];

        base_patterns.contains(&branch_name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::process::Command;
    use tempfile::TempDir;

    fn create_test_repo() -> (TempDir, PathBuf) {
        let temp_dir = TempDir::new().unwrap();
        let repo_path = temp_dir.path().to_path_buf();

        // Initialize git repository
        Command::new("git")
            .args(["init"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Create initial commit
        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "Initial commit"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        (temp_dir, repo_path)
    }

    fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
        let file_path = repo_path.join(filename);
        std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();

        Command::new("git")
            .args(["add", filename])
            .current_dir(repo_path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", message])
            .current_dir(repo_path)
            .output()
            .unwrap();
    }

    #[test]
    fn test_repository_info() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        let info = repo.get_info().unwrap();
        assert!(!info.is_dirty); // Should be clean after commit
        assert!(
            info.head_branch == Some("master".to_string())
                || info.head_branch == Some("main".to_string()),
            "Expected default branch to be 'master' or 'main', got {:?}",
            info.head_branch
        );
        assert!(info.head_commit.is_some()); // Just check it exists
        assert!(info.untracked_files.is_empty()); // Should be empty after commit
    }

    #[test]
    fn test_force_push_branch_basic() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Get the actual default branch name
        let default_branch = repo.get_current_branch().unwrap();

        // Create source branch with commits
        create_commit(&repo_path, "Feature commit 1", "feature1.rs");
        Command::new("git")
            .args(["checkout", "-b", "source-branch"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        create_commit(&repo_path, "Feature commit 2", "feature2.rs");

        // Create target branch
        Command::new("git")
            .args(["checkout", &default_branch])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["checkout", "-b", "target-branch"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        create_commit(&repo_path, "Target commit", "target.rs");

        // Test force push from source to target
        let result = repo.force_push_branch("target-branch", "source-branch");

        // Should succeed in test environment (even though it doesn't actually push to remote)
        // The important thing is that the function doesn't panic and handles the git2 operations
        assert!(result.is_ok() || result.is_err()); // Either is acceptable for unit test
    }

    #[test]
    fn test_force_push_branch_nonexistent_branches() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Get the actual default branch name
        let default_branch = repo.get_current_branch().unwrap();

        // Test force push with nonexistent source branch
        let result = repo.force_push_branch("target", "nonexistent-source");
        assert!(result.is_err());

        // Test force push with nonexistent target branch
        let result = repo.force_push_branch("nonexistent-target", &default_branch);
        assert!(result.is_err());
    }

    #[test]
    fn test_force_push_workflow_simulation() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Simulate the smart force push workflow:
        // 1. Original branch exists with PR
        Command::new("git")
            .args(["checkout", "-b", "feature-auth"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        create_commit(&repo_path, "Add authentication", "auth.rs");

        // 2. Rebase creates versioned branch
        Command::new("git")
            .args(["checkout", "-b", "feature-auth-v2"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        create_commit(&repo_path, "Fix auth validation", "auth.rs");

        // 3. Smart force push: update original branch from versioned branch
        let result = repo.force_push_branch("feature-auth", "feature-auth-v2");

        // Verify the operation is handled properly (success or expected error)
        match result {
            Ok(_) => {
                // Force push succeeded - verify branch state if possible
                Command::new("git")
                    .args(["checkout", "feature-auth"])
                    .current_dir(&repo_path)
                    .output()
                    .unwrap();
                let log_output = Command::new("git")
                    .args(["log", "--oneline", "-2"])
                    .current_dir(&repo_path)
                    .output()
                    .unwrap();
                let log_str = String::from_utf8_lossy(&log_output.stdout);
                assert!(
                    log_str.contains("Fix auth validation")
                        || log_str.contains("Add authentication")
                );
            }
            Err(_) => {
                // Expected in test environment without remote - that's fine
                // The important thing is we tested the code path without panicking
            }
        }
    }

    #[test]
    fn test_branch_operations() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Test get current branch - accept either main or master
        let current = repo.get_current_branch().unwrap();
        assert!(
            current == "master" || current == "main",
            "Expected default branch to be 'master' or 'main', got '{current}'"
        );

        // Test create branch
        Command::new("git")
            .args(["checkout", "-b", "test-branch"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let current = repo.get_current_branch().unwrap();
        assert_eq!(current, "test-branch");
    }

    #[test]
    fn test_commit_operations() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Test get head commit
        let head = repo.get_head_commit().unwrap();
        assert_eq!(head.message().unwrap().trim(), "Initial commit");

        // Test get commit by hash
        let hash = head.id().to_string();
        let same_commit = repo.get_commit(&hash).unwrap();
        assert_eq!(head.id(), same_commit.id());
    }

    #[test]
    fn test_checkout_safety_clean_repo() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create a test branch
        create_commit(&repo_path, "Second commit", "test.txt");
        Command::new("git")
            .args(["checkout", "-b", "test-branch"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Test checkout safety with clean repo
        let safety_result = repo.check_checkout_safety("main");
        assert!(safety_result.is_ok());
        assert!(safety_result.unwrap().is_none()); // Clean repo should return None
    }

    #[test]
    fn test_checkout_safety_with_modified_files() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create a test branch
        Command::new("git")
            .args(["checkout", "-b", "test-branch"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Modify a file to create uncommitted changes
        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();

        // Test checkout safety with modified files
        let safety_result = repo.check_checkout_safety("main");
        assert!(safety_result.is_ok());
        let safety_info = safety_result.unwrap();
        assert!(safety_info.is_some());

        let info = safety_info.unwrap();
        assert!(!info.modified_files.is_empty());
        assert!(info.modified_files.contains(&"README.md".to_string()));
    }

    #[test]
    fn test_unsafe_checkout_methods() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create a test branch
        create_commit(&repo_path, "Second commit", "test.txt");
        Command::new("git")
            .args(["checkout", "-b", "test-branch"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Modify a file to create uncommitted changes
        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();

        // Test unsafe checkout methods bypass safety checks
        let _result = repo.checkout_branch_unsafe("main");
        // Note: This might still fail due to git2 restrictions, but shouldn't hit our safety code
        // The important thing is that it doesn't trigger our safety confirmation

        // Test unsafe commit checkout
        let head_commit = repo.get_head_commit().unwrap();
        let commit_hash = head_commit.id().to_string();
        let _result = repo.checkout_commit_unsafe(&commit_hash);
        // Similar to above - testing that safety is bypassed
    }

    #[test]
    fn test_get_modified_files() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Initially should have no modified files
        let modified = repo.get_modified_files().unwrap();
        assert!(modified.is_empty());

        // Modify a file
        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();

        // Should now detect the modified file
        let modified = repo.get_modified_files().unwrap();
        assert_eq!(modified.len(), 1);
        assert!(modified.contains(&"README.md".to_string()));
    }

    #[test]
    fn test_get_staged_files() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Initially should have no staged files
        let staged = repo.get_staged_files().unwrap();
        assert!(staged.is_empty());

        // Create and stage a new file
        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
        Command::new("git")
            .args(["add", "staged.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Should now detect the staged file
        let staged = repo.get_staged_files().unwrap();
        assert_eq!(staged.len(), 1);
        assert!(staged.contains(&"staged.txt".to_string()));
    }

    #[test]
    fn test_create_stash_fallback() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Test stash creation - newer git versions allow empty stashes
        let result = repo.create_stash("test stash");

        // Either succeeds (newer git with empty stash) or fails with helpful message
        match result {
            Ok(stash_id) => {
                // Modern git allows empty stashes, verify we got a stash ID
                assert!(!stash_id.is_empty());
                assert!(stash_id.contains("stash") || stash_id.len() >= 7); // SHA or stash@{n}
            }
            Err(error) => {
                // Older git should fail with helpful message
                let error_msg = error.to_string();
                assert!(
                    error_msg.contains("No local changes to save")
                        || error_msg.contains("git stash push")
                );
            }
        }
    }

    #[test]
    fn test_delete_branch_unsafe() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create a test branch
        create_commit(&repo_path, "Second commit", "test.txt");
        Command::new("git")
            .args(["checkout", "-b", "test-branch"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Add another commit to the test branch to make it different from main
        create_commit(&repo_path, "Branch-specific commit", "branch.txt");

        // Go back to main
        Command::new("git")
            .args(["checkout", "main"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Test unsafe delete bypasses safety checks
        // Note: This may still fail if the branch has unpushed commits, but it should bypass our safety confirmation
        let result = repo.delete_branch_unsafe("test-branch");
        // Even if it fails, the key is that it didn't prompt for user confirmation
        // So we just check that it attempted the operation without interactive prompts
        let _ = result; // Don't assert success since delete may fail for git reasons
    }

    #[test]
    fn test_force_push_unsafe() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create a test branch
        create_commit(&repo_path, "Second commit", "test.txt");
        Command::new("git")
            .args(["checkout", "-b", "test-branch"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Test unsafe force push bypasses safety checks
        // Note: This will likely fail due to no remote, but it tests the safety bypass
        let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
        // The key is that it doesn't trigger safety confirmation dialogs
    }

    #[test]
    fn test_cherry_pick_basic() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create a branch with a commit to cherry-pick
        repo.create_branch("source", None).unwrap();
        repo.checkout_branch("source").unwrap();

        std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "Cherry commit"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let cherry_commit = repo.get_head_commit_hash().unwrap();

        // Switch back to previous branch (where source was created from)
        // Using `git checkout -` is environment-agnostic
        Command::new("git")
            .args(["checkout", "-"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        repo.create_branch("target", None).unwrap();
        repo.checkout_branch("target").unwrap();

        // Cherry-pick the commit
        let new_commit = repo.cherry_pick(&cherry_commit).unwrap();

        // Verify cherry-pick succeeded (commit exists)
        repo.repo
            .find_commit(git2::Oid::from_str(&new_commit).unwrap())
            .unwrap();

        // Verify file exists on target branch
        assert!(
            repo_path.join("cherry.txt").exists(),
            "Cherry-picked file should exist"
        );

        // Verify source branch is unchanged
        repo.checkout_branch("source").unwrap();
        let source_head = repo.get_head_commit_hash().unwrap();
        assert_eq!(
            source_head, cherry_commit,
            "Source branch should be unchanged"
        );
    }

    #[test]
    fn test_cherry_pick_preserves_commit_message() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create commit with specific message
        repo.create_branch("msg-test", None).unwrap();
        repo.checkout_branch("msg-test").unwrap();

        std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit_msg = "Test: Special commit message\n\nWith body";
        Command::new("git")
            .args(["commit", "-m", commit_msg])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let original_commit = repo.get_head_commit_hash().unwrap();

        // Cherry-pick to another branch (use previous branch via git checkout -)
        Command::new("git")
            .args(["checkout", "-"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let new_commit = repo.cherry_pick(&original_commit).unwrap();

        // Get commit message of new commit
        let output = Command::new("git")
            .args(["log", "-1", "--format=%B", &new_commit])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let new_msg = String::from_utf8_lossy(&output.stdout);
        assert!(
            new_msg.contains("Special commit message"),
            "Should preserve commit message"
        );
    }

    #[test]
    fn test_cherry_pick_handles_conflicts() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create conflicting content
        std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "Add conflict file"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Create branch with different content
        repo.create_branch("conflict-branch", None).unwrap();
        repo.checkout_branch("conflict-branch").unwrap();

        std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "Modify conflict file"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let conflict_commit = repo.get_head_commit_hash().unwrap();

        // Try to cherry-pick (should fail due to conflict)
        // Go back to previous branch
        Command::new("git")
            .args(["checkout", "-"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "Different change"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Cherry-pick should fail with conflict
        let result = repo.cherry_pick(&conflict_commit);
        assert!(result.is_err(), "Cherry-pick with conflict should fail");
    }

    #[test]
    fn test_reset_to_head_clears_staged_files() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create and stage some files
        std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
        std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();

        Command::new("git")
            .args(["add", "staged1.txt", "staged2.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Verify files are staged
        let staged_before = repo.get_staged_files().unwrap();
        assert_eq!(staged_before.len(), 2, "Should have 2 staged files");

        // Reset to HEAD
        repo.reset_to_head().unwrap();

        // Verify no files are staged after reset
        let staged_after = repo.get_staged_files().unwrap();
        assert_eq!(
            staged_after.len(),
            0,
            "Should have no staged files after reset"
        );
    }

    #[test]
    fn test_reset_to_head_clears_modified_files() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Modify an existing file
        std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();

        // Stage the modification
        Command::new("git")
            .args(["add", "README.md"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Verify file is modified and staged
        assert!(repo.is_dirty().unwrap(), "Repo should be dirty");

        // Reset to HEAD
        repo.reset_to_head().unwrap();

        // Verify repo is clean
        assert!(
            !repo.is_dirty().unwrap(),
            "Repo should be clean after reset"
        );

        // Verify file content is restored
        let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
        assert_eq!(
            content, "# Test",
            "File should be restored to original content"
        );
    }

    #[test]
    fn test_reset_to_head_preserves_untracked_files() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create untracked file
        std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();

        // Stage some other file
        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
        Command::new("git")
            .args(["add", "staged.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Reset to HEAD
        repo.reset_to_head().unwrap();

        // Verify untracked file still exists
        assert!(
            repo_path.join("untracked.txt").exists(),
            "Untracked file should be preserved"
        );

        // Verify staged file was removed (since it was never committed)
        assert!(
            !repo_path.join("staged.txt").exists(),
            "Staged but uncommitted file should be removed"
        );
    }

    #[test]
    fn test_cherry_pick_does_not_modify_source() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create source branch with multiple commits
        repo.create_branch("feature", None).unwrap();
        repo.checkout_branch("feature").unwrap();

        // Add multiple commits
        for i in 1..=3 {
            std::fs::write(
                repo_path.join(format!("file{i}.txt")),
                format!("Content {i}"),
            )
            .unwrap();
            Command::new("git")
                .args(["add", "."])
                .current_dir(&repo_path)
                .output()
                .unwrap();

            Command::new("git")
                .args(["commit", "-m", &format!("Commit {i}")])
                .current_dir(&repo_path)
                .output()
                .unwrap();
        }

        // Get source branch state
        let source_commits = Command::new("git")
            .args(["log", "--format=%H", "feature"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();

        // Cherry-pick middle commit to another branch
        let commits: Vec<&str> = source_state.lines().collect();
        let middle_commit = commits[1];

        // Go back to previous branch
        Command::new("git")
            .args(["checkout", "-"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        repo.create_branch("target", None).unwrap();
        repo.checkout_branch("target").unwrap();

        repo.cherry_pick(middle_commit).unwrap();

        // Verify source branch is completely unchanged
        let after_commits = Command::new("git")
            .args(["log", "--format=%H", "feature"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();

        assert_eq!(
            source_state, after_state,
            "Source branch should be completely unchanged after cherry-pick"
        );
    }

    #[test]
    fn test_detect_parent_branch() {
        let (_temp_dir, repo_path) = create_test_repo();
        let repo = GitRepository::open(&repo_path).unwrap();

        // Create a custom base branch (not just main/master)
        repo.create_branch("dev123", None).unwrap();
        repo.checkout_branch("dev123").unwrap();
        create_commit(&repo_path, "Base commit on dev123", "base.txt");

        // Create feature branch from dev123
        repo.create_branch("feature-branch", None).unwrap();
        repo.checkout_branch("feature-branch").unwrap();
        create_commit(&repo_path, "Feature commit", "feature.txt");

        // Should detect dev123 as parent since it's the most recent common ancestor
        let detected_parent = repo.detect_parent_branch().unwrap();

        // The algorithm should find dev123 through either Strategy 2 (default branch)
        // or Strategy 3 (common ancestor analysis)
        assert!(detected_parent.is_some(), "Should detect a parent branch");

        // Since we can't guarantee which strategy will work in the test environment,
        // just verify it returns something reasonable
        let parent = detected_parent.unwrap();
        assert!(
            parent == "dev123" || parent == "main" || parent == "master",
            "Parent should be dev123, main, or master, got: {parent}"
        );
    }
}