gitwig 1.2.7

a rust based tui, an alternative to sourcetree and gitui
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
//! Filesystem + git repository inspection.
//!
//! This module owns both the "is this a git repo?" classification used by
//! the per-card indicator AND the richer detail collection used by the
//! Detail view. They share a single `collect_summary` helper so the same
//! libgit2 work doesn't run twice.
//!
//! The cheap `is_dir()` + `.git`-existence check still gates everything —
//! we only spin up libgit2 when both checks pass.

use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use git2::{Repository, StatusOptions, StatusShow};

// ── Card-level status ──────────────────────────────────────────────────────

/// Per-item filesystem classification carried alongside `config.items`.
/// `GitRepo`'s inner `Option` is `None` when `.git` exists but libgit2
/// couldn't open or read the repo — we know it's a repo, we just can't
/// summarize its state.
#[derive(Debug, Clone)]
pub enum ItemStatus {
    Missing,
    Directory,
    GitRepo(Option<RepoSummary>),
}

/// Compact summary used to draw the per-card indicator. Also embedded in
/// `RepoInfo` so the Detail view doesn't re-collect the same data.
#[derive(Debug, Default, Clone)]
pub struct RepoSummary {
    /// Current branch shorthand (e.g. `"main"`). `None` for detached HEAD
    /// or when the ref cannot be read.
    pub branch: Option<String>,
    pub staged: usize,
    pub modified: usize,
    pub untracked: usize,
    pub conflicted: usize,
    pub ahead: usize,
    pub behind: usize,
}

impl RepoSummary {
    pub fn is_clean(&self) -> bool {
        self.staged + self.modified + self.untracked + self.conflicted == 0
    }
    pub fn is_synced(&self) -> bool {
        self.ahead + self.behind == 0
    }
    pub fn unchanged(&self) -> bool {
        self.is_clean() && self.is_synced()
    }
}

// ── Detail view ────────────────────────────────────────────────────────────

#[derive(Debug)]
pub enum ItemDetail {
    Missing {
        resolved: PathBuf,
    },
    Directory {
        resolved: PathBuf,
    },
    Repo {
        resolved: PathBuf,
        info: Box<RepoInfo>,
    },
    Error {
        resolved: PathBuf,
        message: String,
    },
}

#[derive(Debug, Clone, Default)]
pub struct BranchInfo {
    pub name: String,
    pub is_head: bool,
    pub short_sha: String,
    pub short_message: String,
}

#[derive(Debug, Clone, Default)]
pub struct StashInfo {
    pub index: usize,
    pub message: String,
    pub commit_id: String,
    pub files: Vec<FileEntry>,
}

#[derive(Debug, Clone, Default)]
pub struct CommitterStat {
    pub name: String,
    pub email: String,
    pub count: usize,
}

#[derive(Debug, Default)]
pub struct RepoInfo {
    pub branch: Option<String>,
    pub head: Option<HeadInfo>,
    pub remotes: Vec<RemoteInfo>,
    /// Configured upstream branch (e.g. "origin/main") if HEAD tracks one.
    pub upstream: Option<String>,
    pub summary: RepoSummary,
    /// File-level changes, populated by `collect_info` for the Detail view.
    pub changes: WorktreeChanges,
    /// Recent commits in this repository.
    pub commits: Vec<CommitEntry>,
    /// Graph view lines for the repository.
    pub graph_lines: Vec<GraphLine>,
    /// Local branches in the repository.
    pub local_branches: Vec<BranchInfo>,
    /// Remote branches in the repository.
    pub remote_branches: Vec<BranchInfo>,
    /// Local tags in the repository.
    pub local_tags: Vec<BranchInfo>,
    /// Remote tags in the repository.
    pub remote_tags: Vec<BranchInfo>,
    /// Whether remote tags have been loaded from the remote repository.
    pub remote_tags_loaded: bool,
    /// Whether a remote tag fetch has been attempted in this session.
    pub remote_tags_attempted: bool,
    /// Tracked files in the repository.
    pub files: Vec<String>,
    /// Available stashes in the repository.
    pub stashes: Vec<StashInfo>,
    /// Committer statistics.
    pub committer_stats: Vec<CommitterStat>,
    /// Whether the committer statistics walk was capped by the limit.
    pub committer_stats_limit_reached: bool,
}

#[derive(Debug)]
pub struct HeadInfo {
    pub short_id: String,
    pub summary: String,
    pub author: String,
    pub when: String,
}

#[derive(Debug, Clone)]
pub struct RemoteInfo {
    pub name: String,
    pub url: String,
    pub push_url: Option<String>,
    pub refspecs: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct CommitEntry {
    /// Short 7-char display ID.
    pub id: String,
    /// Full 40-char hex OID — used for diff lookup.
    pub oid: String,
    pub author: String,
    pub when: String,
    pub date: String,
    pub summary: String,
    pub message: String,
    /// Local branch names and tags pointing at this commit.
    /// Tags are prefixed with `"tag:"`, remote branches with `"remote:"`.
    pub refs: Vec<String>,
    /// Files changed in this commit (diff against first parent, or empty tree).
    pub files: Vec<FileEntry>,
    /// GPG/SSH signature status.
    pub signature_status: String,
}

#[derive(Debug, Clone)]
pub struct GraphLine {
    pub graph: String,
    pub commit: Option<GraphCommit>,
}

#[derive(Debug, Clone)]
pub struct GraphCommit {
    pub oid: String,
    pub decoration: String,
    pub summary: String,
    pub author: String,
    pub date: String,
    /// GPG/SSH signature status.
    pub signature_status: String,
}

/// One changed file in the working tree or index.
#[derive(Debug, Clone)]
pub struct FileEntry {
    /// Path relative to the repository root.
    pub path: String,
    /// Short human-readable label: "N", "M", "D", "R", "T", "?", or "C".
    pub label: &'static str,
}

/// File-level working-tree state collected for the Detail view.
/// Split into four buckets so the UI can render them as separate sections.
#[derive(Debug, Default, Clone)]
pub struct WorktreeChanges {
    pub staged: Vec<FileEntry>,
    pub unstaged: Vec<FileEntry>,
    pub untracked: Vec<FileEntry>,
    pub conflicted: Vec<FileEntry>,
}

// ── Per-file diff ──────────────────────────────────────────────────────────

/// The type of a single line in a unified diff.
#[derive(Debug, Clone, PartialEq)]
pub enum DiffLineKind {
    /// `@@ ... @@` hunk header.
    Header,
    /// `+` added line.
    Added,
    /// `-` removed line.
    Removed,
    /// Unchanged context line.
    Context,
    /// Line in OURS section of a conflict.
    ConflictOurs,
    /// Line in THEIRS section of a conflict.
    ConflictTheirs,
    /// Conflict marker line (<<<<<<<, =======, >>>>>>>).
    ConflictSeparator,
}

/// One line of a unified diff, as rendered in the Diff panel.
#[derive(Debug, Clone)]
pub struct DiffLine {
    pub kind: DiffLineKind,
    /// Raw content (already includes the leading +/−/space prefix character).
    pub content: String,
}

/// Return the unified diff of `file_path` as it changed in `commit_oid`
/// (hex string) inside the repository at `repo_path`.
/// Returns an empty Vec on any error.
pub fn get_commit_file_diff(repo_path: &Path, commit_oid: &str, file_path: &str) -> Vec<DiffLine> {
    get_file_diff_inner(repo_path, commit_oid, file_path).unwrap_or_default()
}

/// Return the diff for `file_path` in the working tree.
///
/// - `staged = true`:  diff between HEAD and the index (what would be committed).
/// - `staged = false`: diff between the index and the working directory (unstaged changes).
///
/// Returns an empty Vec on any error.
pub fn get_worktree_file_diff(repo_path: &Path, file_path: &str, staged: bool) -> Vec<DiffLine> {
    get_worktree_diff_inner(repo_path, file_path, staged).unwrap_or_default()
}

/// Add `file_path` to the index (equivalent to `git add <file>`).
/// Returns a human-readable error string on failure.
pub fn stage_file(repo_path: &Path, file_path: &str) -> Result<(), String> {
    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
    let mut index = repo.index().map_err(|e| e.to_string())?;
    let full_path = repo_path.join(file_path);
    if full_path.exists() {
        index
            .add_path(Path::new(file_path))
            .map_err(|e| e.to_string())?;
    } else {
        index
            .remove_path(Path::new(file_path))
            .map_err(|e| e.to_string())?;
    }
    index.write().map_err(|e| e.to_string())?;
    Ok(())
}

/// Remove `file_path` from the index (equivalent to `git restore --staged <file>`).
/// When HEAD exists the index entry is reset to the HEAD tree value; for a brand-new
/// repo with no commits the entry is simply removed from the index.
/// Returns a human-readable error string on failure.
pub fn unstage_file(repo_path: &Path, file_path: &str) -> Result<(), String> {
    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
    // Prefer reset_default (git reset HEAD -- <file>) when a HEAD commit exists.
    if let Some(commit) = repo.head().ok().and_then(|h| h.peel_to_commit().ok()) {
        repo.reset_default(Some(commit.as_object()), std::iter::once(file_path))
            .map_err(|e| e.to_string())?;
    } else {
        // New repo with no commits: just remove the entry from the index.
        let mut index = repo.index().map_err(|e| e.to_string())?;
        index
            .remove_path(Path::new(file_path))
            .map_err(|e| e.to_string())?;
        index.write().map_err(|e| e.to_string())?;
    }
    Ok(())
}

/// Stage all unstaged/untracked changes (equivalent to `git add -A`).
pub fn stage_all_changes(repo_path: &Path) -> Result<(), String> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("add")
        .arg("-A")
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;

    if output.status.success() {
        Ok(())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
    }
}

/// Unstage all staged changes (equivalent to `git reset`).
pub fn unstage_all_changes(repo_path: &Path) -> Result<(), String> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("reset")
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;

    if output.status.success() {
        Ok(())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
    }
}

/// Discard all staged, unstaged, and untracked changes in the repository.
pub fn discard_all_changes(repo_path: &Path) -> Result<(), String> {
    // 1. Unstage all first so everything is in the working tree
    let _ = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("reset")
        .current_dir(repo_path)
        .output();

    // 2. Discard all tracked modifications
    let checkout_out = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("checkout")
        .arg("--")
        .arg(".")
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;

    if !checkout_out.status.success() {
        return Err(String::from_utf8_lossy(&checkout_out.stderr)
            .trim()
            .to_string());
    }

    // 3. Clean all untracked files/folders
    let clean_out = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("clean")
        .arg("-fd")
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;

    if !clean_out.status.success() {
        return Err(String::from_utf8_lossy(&clean_out.stderr)
            .trim()
            .to_string());
    }

    Ok(())
}

/// Stage a single hunk of unstaged changes (equivalent to `git apply --cached -`).
pub fn stage_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
    apply_hunk_patch(repo_path, file_path, hunk, false, true)
}

/// Unstage a single hunk of staged changes (equivalent to `git apply --cached --reverse -`).
pub fn unstage_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
    apply_hunk_patch(repo_path, file_path, hunk, true, true)
}

/// Discard a single hunk of unstaged changes in the working tree (equivalent to `git apply --reverse -`).
pub fn discard_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
    apply_hunk_patch(repo_path, file_path, hunk, true, false)
}

/// Stage a single line from the Unstaged diff.
pub fn stage_line(
    repo_path: &Path,
    file_path: &str,
    hunk: &[DiffLine],
    selected_line_idx: usize,
) -> Result<(), String> {
    apply_line_patch_inner(
        repo_path,
        file_path,
        hunk,
        selected_line_idx,
        false,
        false,
        true,
    )
}

/// Unstage a single line from the Staged diff.
pub fn unstage_line(
    repo_path: &Path,
    file_path: &str,
    hunk: &[DiffLine],
    selected_line_idx: usize,
) -> Result<(), String> {
    apply_line_patch_inner(
        repo_path,
        file_path,
        hunk,
        selected_line_idx,
        true,
        true,
        true,
    )
}

/// Discard a single line from the Unstaged diff in the working tree.
pub fn discard_line(
    repo_path: &Path,
    file_path: &str,
    hunk: &[DiffLine],
    selected_line_idx: usize,
) -> Result<(), String> {
    apply_line_patch_inner(
        repo_path,
        file_path,
        hunk,
        selected_line_idx,
        true,
        true,
        false,
    )
}

fn parse_hunk_header(header: &str) -> Option<(usize, usize, usize, usize)> {
    if !header.starts_with("@@") {
        return None;
    }
    let parts: Vec<&str> = header.split("@@").collect();
    if parts.len() < 3 {
        return None;
    }
    let meta = parts[1].trim();
    let subparts: Vec<&str> = meta.split_whitespace().collect();
    if subparts.len() < 2 {
        return None;
    }

    let parse_part = |p: &str| -> (usize, usize) {
        let s = p.trim_start_matches(['-', '+']);
        let comps: Vec<&str> = s.split(',').collect();
        let start = comps[0].parse::<usize>().unwrap_or(0);
        let count = if comps.len() > 1 {
            comps[1].parse::<usize>().unwrap_or(1)
        } else {
            1
        };
        (start, count)
    };

    let (old_start, old_count) = parse_part(subparts[0]);
    let (new_start, new_count) = parse_part(subparts[1]);
    Some((old_start, old_count, new_start, new_count))
}

fn apply_line_patch_inner(
    repo_path: &Path,
    file_path: &str,
    hunk: &[DiffLine],
    selected_line_idx_in_hunk: usize,
    revert: bool,
    target_has_modification: bool,
    cached: bool,
) -> Result<(), String> {
    use std::io::Write;
    use std::process::{Command, Stdio};

    if hunk.is_empty() {
        return Err("Empty hunk".to_string());
    }

    let selected_line = match hunk.get(selected_line_idx_in_hunk) {
        Some(line) => line,
        None => return Err("Invalid line index".to_string()),
    };

    if selected_line.kind != DiffLineKind::Added && selected_line.kind != DiffLineKind::Removed {
        return Err("Selected line is not a modification (must be + or -)".to_string());
    }

    let header_line = &hunk[0];
    let (old_start, _old_count, new_start, _new_count) =
        match parse_hunk_header(&header_line.content) {
            Some(coords) => coords,
            None => return Err(format!("Invalid hunk header: {}", header_line.content)),
        };

    let mut patch_lines = Vec::new();
    let mut new_old_count = 0;
    let mut new_new_count = 0;

    for (i, line) in hunk.iter().enumerate() {
        if i == 0 {
            continue;
        }

        if i == selected_line_idx_in_hunk {
            if revert {
                match line.kind {
                    DiffLineKind::Added => {
                        patch_lines.push(DiffLine {
                            kind: DiffLineKind::Removed,
                            content: line.content.clone(),
                        });
                        new_old_count += 1;
                    }
                    DiffLineKind::Removed => {
                        patch_lines.push(DiffLine {
                            kind: DiffLineKind::Added,
                            content: line.content.clone(),
                        });
                        new_new_count += 1;
                    }
                    _ => {}
                }
            } else {
                match line.kind {
                    DiffLineKind::Added => {
                        patch_lines.push(DiffLine {
                            kind: DiffLineKind::Added,
                            content: line.content.clone(),
                        });
                        new_new_count += 1;
                    }
                    DiffLineKind::Removed => {
                        patch_lines.push(DiffLine {
                            kind: DiffLineKind::Removed,
                            content: line.content.clone(),
                        });
                        new_old_count += 1;
                    }
                    _ => {}
                }
            }
        } else {
            match line.kind {
                DiffLineKind::Context => {
                    patch_lines.push(line.clone());
                    new_old_count += 1;
                    new_new_count += 1;
                }
                DiffLineKind::Added => {
                    if target_has_modification {
                        patch_lines.push(DiffLine {
                            kind: DiffLineKind::Context,
                            content: line.content.clone(),
                        });
                        new_old_count += 1;
                        new_new_count += 1;
                    } else {
                        // Omit
                    }
                }
                DiffLineKind::Removed => {
                    if target_has_modification {
                        // Omit
                    } else {
                        patch_lines.push(DiffLine {
                            kind: DiffLineKind::Context,
                            content: line.content.clone(),
                        });
                        new_old_count += 1;
                        new_new_count += 1;
                    }
                }
                _ => {}
            }
        }
    }

    let mut patch = String::new();
    patch.push_str(&format!("diff --git a/{} b/{}\n", file_path, file_path));
    patch.push_str(&format!("--- a/{}\n", file_path));
    patch.push_str(&format!("+++ b/{}\n", file_path));
    patch.push_str(&format!(
        "@@ -{},{} +{},{} @@\n",
        old_start, new_old_count, new_start, new_new_count
    ));

    for line in patch_lines {
        let prefix = match line.kind {
            DiffLineKind::Added => "+",
            DiffLineKind::Removed => "-",
            DiffLineKind::Context => " ",
            DiffLineKind::Header => "",
            _ => "",
        };
        patch.push_str(prefix);
        patch.push_str(&line.content);
        patch.push('\n');
    }

    let mut args = vec!["apply"];
    if cached {
        args.push("--cached");
    }
    args.push("-");

    let mut cmd = Command::new("git");
    let mut child = cmd
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .args(&args)
        .current_dir(repo_path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("Failed to spawn git apply: {}", e))?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(patch.as_bytes())
            .map_err(|e| format!("Failed to write patch to stdin: {}", e))?;
    }

    let output = child
        .wait_with_output()
        .map_err(|e| format!("Failed to wait for git apply: {}", e))?;

    if !output.status.success() {
        let err_msg = String::from_utf8_lossy(&output.stderr).to_string();
        return Err(format!("git apply failed: {}", err_msg.trim()));
    }

    Ok(())
}

fn apply_hunk_patch(
    repo_path: &Path,
    file_path: &str,
    hunk: &[DiffLine],
    reverse: bool,
    cached: bool,
) -> Result<(), String> {
    use std::io::Write;
    use std::process::{Command, Stdio};

    let mut patch = String::new();
    patch.push_str(&format!("diff --git a/{} b/{}\n", file_path, file_path));
    patch.push_str(&format!("--- a/{}\n", file_path));
    patch.push_str(&format!("+++ b/{}\n", file_path));
    for line in hunk {
        let prefix = match line.kind {
            DiffLineKind::Added => "+",
            DiffLineKind::Removed => "-",
            DiffLineKind::Context => " ",
            DiffLineKind::Header => "",
            _ => "",
        };
        patch.push_str(prefix);
        patch.push_str(&line.content);
        patch.push('\n');
    }

    let mut args = vec!["apply"];
    if cached {
        args.push("--cached");
    }
    if reverse {
        args.push("--reverse");
    }
    args.push("-");

    let mut cmd = Command::new("git");
    let mut child = cmd
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .args(&args)
        .current_dir(repo_path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("Failed to spawn git apply: {}", e))?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(patch.as_bytes())
            .map_err(|e| format!("Failed to write patch to stdin: {}", e))?;
    }

    let output = child
        .wait_with_output()
        .map_err(|e| format!("Failed to wait for git apply: {}", e))?;

    if !output.status.success() {
        let err_msg = String::from_utf8_lossy(&output.stderr).to_string();
        return Err(format!("git apply failed: {}", err_msg.trim()));
    }

    Ok(())
}

/// Discards uncommitted changes in `file_path`.
/// - If the file is untracked, it is deleted from the filesystem.
/// - If the file is tracked and modified/deleted, it is restored from the index.
/// - If the file is staged, it is first unstaged (reset to HEAD) and then restored from index.
pub fn discard_file_changes(repo_path: &Path, file_path: &str, staged: bool) -> Result<(), String> {
    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;

    if staged {
        // First unstage it (reset to HEAD)
        unstage_file(repo_path, file_path)?;
    }

    // Now check if the file is untracked
    let is_untracked = if let Ok(status) = repo.status_file(Path::new(file_path)) {
        status.contains(git2::Status::WT_NEW)
    } else {
        false
    };

    if is_untracked {
        let full_path = repo_path.join(file_path);
        if full_path.exists() {
            if full_path.is_file() {
                std::fs::remove_file(&full_path).map_err(|e| e.to_string())?;
            } else if full_path.is_dir() {
                std::fs::remove_dir_all(&full_path).map_err(|e| e.to_string())?;
            }
        }
    } else {
        // Tracked file: checkout from index to working tree
        let mut checkout_opts = git2::build::CheckoutBuilder::new();
        checkout_opts.path(Path::new(file_path));
        checkout_opts.force();
        repo.checkout_index(None, Some(&mut checkout_opts))
            .map_err(|e| e.to_string())?;
    }

    Ok(())
}

/// Create a commit in the repository with the given message.
/// Returns a human-readable error string on failure.
pub fn commit_changes(repo_path: &Path, message: &str) -> Result<(), String> {
    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
    let mut index = repo.index().map_err(|e| e.to_string())?;
    let tree_id = index.write_tree().map_err(|e| e.to_string())?;
    let tree = repo.find_tree(tree_id).map_err(|e| e.to_string())?;

    let signature = repo.signature().map_err(|e| {
        format!(
            "Failed to get signature. Check user.name/email config: {}",
            e
        )
    })?;

    // Find parent commits
    let mut parents = Vec::new();
    let mut has_head = false;
    if let Ok(head) = repo.head() {
        if let Ok(parent_commit) = head.peel_to_commit() {
            has_head = true;
            // Check if there are changes staged compared to HEAD
            let parent_tree = parent_commit.tree().map_err(|e| e.to_string())?;
            if parent_tree.id() == tree_id {
                return Err("No staged changes to commit".to_string());
            }
            parents.push(parent_commit);
        }
    }

    if !has_head && index.is_empty() {
        return Err("No staged changes to commit (index is empty)".to_string());
    }

    let parent_refs: Vec<&git2::Commit> = parents.iter().collect();

    repo.commit(
        Some("HEAD"),
        &signature,
        &signature,
        message,
        &tree,
        &parent_refs,
    )
    .map_err(|e| e.to_string())?;

    Ok(())
}

// ── Public entry points ────────────────────────────────────────────────────

/// Expand a leading `~` or `~/` in a user-supplied path to the user's home
/// directory. Returns the input unchanged if there is no home dir or no
/// tilde to expand.
pub fn expand_tilde(s: &str) -> PathBuf {
    if s == "~" {
        return dirs::home_dir().unwrap_or_else(|| PathBuf::from(s));
    }
    if let Some(stripped) = s.strip_prefix("~/")
        && let Some(home) = dirs::home_dir()
    {
        return home.join(stripped);
    }
    PathBuf::from(s)
}

/// Add a new git remote.
pub fn remote_add(repo_path: &std::path::Path, name: &str, url: &str) -> Result<(), git2::Error> {
    let repo = Repository::open(repo_path)?;
    repo.remote(name, url)?;
    Ok(())
}

/// Delete an existing git remote.
pub fn remote_delete(repo_path: &std::path::Path, name: &str) -> Result<(), git2::Error> {
    let repo = Repository::open(repo_path)?;
    repo.remote_delete(name)?;
    Ok(())
}

/// Classify `item` and produce a card-level summary. Used by the list view.
pub fn inspect_summary(item: &str) -> ItemStatus {
    let path = expand_tilde(item);
    if !path.is_dir() {
        return ItemStatus::Missing;
    }
    if !path.join(".git").exists() {
        return ItemStatus::Directory;
    }
    match Repository::open(&path) {
        Ok(repo) => ItemStatus::GitRepo(Some(collect_summary(&repo))),
        Err(_) => ItemStatus::GitRepo(None),
    }
}

/// Inspect `item` and produce the rich detail report shown on Enter.
pub fn inspect_detail(item: &str, commit_limit: usize) -> ItemDetail {
    let resolved = expand_tilde(item);
    if !resolved.is_dir() {
        return ItemDetail::Missing { resolved };
    }
    if !resolved.join(".git").exists() {
        return ItemDetail::Directory { resolved };
    }
    match collect_info(&resolved, commit_limit) {
        Ok(info) => ItemDetail::Repo {
            resolved,
            info: Box::new(info),
        },
        Err(e) => ItemDetail::Error {
            resolved,
            message: e.to_string(),
        },
    }
}

fn collect_signatures(repo_path: &Path, limit: usize) -> std::collections::HashMap<String, String> {
    let mut sigs = std::collections::HashMap::new();
    let mut cmd = std::process::Command::new("git");
    cmd.env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("log")
        .arg("--all");

    if limit > 0 {
        cmd.arg(format!("-n{}", limit));
    }

    cmd.arg("--pretty=format:%H %G?").current_dir(repo_path);

    if let Ok(out) = cmd.output() {
        if out.status.success() {
            let stdout_str = String::from_utf8_lossy(&out.stdout);
            for line in stdout_str.lines() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() == 2 {
                    sigs.insert(parts[0].to_string(), parts[1].to_string());
                } else if parts.len() == 1 {
                    sigs.insert(parts[0].to_string(), "N".to_string());
                }
            }
        }
    }
    sigs
}

fn collect_commits(
    repo: &Repository,
    limit: usize,
    ref_map: &std::collections::HashMap<git2::Oid, Vec<String>>,
    repo_path: &Path,
) -> Result<Vec<CommitEntry>, git2::Error> {
    let mut walk = repo.revwalk()?;
    if walk.push_head().is_err() {
        return Ok(Vec::new());
    }
    walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;

    let mut commits = Vec::new();
    let oids: Vec<Result<git2::Oid, git2::Error>> = if limit > 0 {
        walk.take(limit).collect()
    } else {
        walk.collect()
    };

    let sig_map = collect_signatures(repo_path, limit);

    for id in oids {
        let oid = id?;
        if let Ok(commit) = repo.find_commit(oid) {
            let short_id = format!("{:.7}", commit.id());
            let oid_str = commit.id().to_string();
            let summary = commit
                .summary()
                .ok()
                .flatten()
                .unwrap_or("(no commit message)")
                .to_string();
            let author = commit.author();
            let author_name = author.name().unwrap_or("?");
            let author_email = author.email().unwrap_or("?");
            let author_str = format!("{} <{}>", author_name, author_email);
            let when = format_relative_time(commit.time().seconds());
            let date = format_utc_date(commit.time().seconds());
            let refs = ref_map.get(&oid).cloned().unwrap_or_default();
            let files = commit_changed_files(repo, &commit);
            let message = commit
                .message()
                .unwrap_or("(no commit message)")
                .to_string();
            let sig_status = sig_map
                .get(&oid_str)
                .cloned()
                .unwrap_or_else(|| "N".to_string());
            commits.push(CommitEntry {
                id: short_id,
                oid: oid_str,
                author: author_str,
                when,
                date,
                summary,
                message,
                refs,
                files,
                signature_status: sig_status,
            });
        }
    }
    Ok(commits)
}

fn collect_committer_stats(
    repo: &Repository,
    limit: usize,
) -> Result<(Vec<CommitterStat>, bool), git2::Error> {
    let mut walk = repo.revwalk()?;
    if walk.push_head().is_err() {
        return Ok((Vec::new(), false));
    }
    let mut counts = std::collections::HashMap::new();
    let mut count = 0;
    let mut limit_reached = false;
    for id in walk {
        let oid = id?;
        if let Ok(commit) = repo.find_commit(oid) {
            let author = commit.author();
            let name = author.name().unwrap_or("?").to_string();
            let email = author.email().unwrap_or("?").to_string();
            let key = (name, email);
            *counts.entry(key).or_insert(0) += 1;
            count += 1;
            if count >= limit {
                limit_reached = true;
                break;
            }
        }
    }

    let mut stats: Vec<CommitterStat> = counts
        .into_iter()
        .map(|((name, email), count)| CommitterStat { name, email, count })
        .collect();

    stats.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));

    Ok((stats, limit_reached))
}

/// Diff `commit` against its first parent (or against an empty tree for the
/// initial commit) and return the list of changed files. Capped at
/// `MAX_FILES_PER_SECTION` entries.
fn commit_changed_files(repo: &Repository, commit: &git2::Commit) -> Vec<FileEntry> {
    let commit_tree = match commit.tree() {
        Ok(t) => t,
        Err(_) => return Vec::new(),
    };
    // For the initial commit parent_tree is None — libgit2 treats that as an
    // empty tree, so all files appear as "added".
    let parent_tree = commit.parent(0).ok().and_then(|p| p.tree().ok());

    let diff = match repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), None) {
        Ok(d) => d,
        Err(_) => return Vec::new(),
    };

    let mut files = Vec::new();
    for delta in diff.deltas() {
        if files.len() >= MAX_FILES_PER_SECTION {
            break;
        }
        let path = delta
            .new_file()
            .path()
            .or_else(|| delta.old_file().path())
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|| "(unknown)".to_string());

        let label: &'static str = match delta.status() {
            git2::Delta::Added => "N",
            git2::Delta::Deleted => "D",
            git2::Delta::Modified => "M",
            git2::Delta::Renamed => "R",
            git2::Delta::Typechange => "T",
            _ => "M",
        };
        files.push(FileEntry { path, label });
    }
    files
}

// ── Internal collection ────────────────────────────────────────────────────

fn collect_info(path: &Path, commit_limit: usize) -> Result<RepoInfo, git2::Error> {
    let mut repo = Repository::open(path)?;
    let summary = collect_summary(&repo);
    let mut info = RepoInfo {
        summary,
        ..RepoInfo::default()
    };

    if let Ok(head) = repo.head() {
        // git2 0.21: shorthand() returns Result<&str, Error>.
        info.branch = head.shorthand().ok().map(String::from);

        if let Ok(commit) = head.peel_to_commit() {
            let short_id = format!("{:.7}", commit.id());
            // summary() returns Result<Option<&str>, Error>.
            let summary_text = commit
                .summary()
                .ok()
                .flatten()
                .unwrap_or("(no commit message)")
                .to_string();
            let author = commit.author();
            let author_str = format!(
                "{} <{}>",
                author.name().unwrap_or("?"),
                author.email().unwrap_or("?")
            );
            let when = format_relative_time(commit.time().seconds());
            info.head = Some(HeadInfo {
                short_id,
                summary: summary_text,
                author: author_str,
                when,
            });
        }

        // Upstream branch (short form, "origin/main"). git2 0.21:
        // Reference::name returns Result<&str, Error>.
        if let Ok(head_name) = head.name() {
            info.upstream = upstream_short_name(&repo, head_name);
        }
    }

    if let Ok(remotes) = repo.remotes() {
        for name in remotes.iter() {
            let Ok(Some(name)) = name else { continue };
            if let Ok(remote) = repo.find_remote(name) {
                let push_url = remote.pushurl().ok().flatten().map(String::from);
                let mut refspecs = Vec::new();
                for r in remote.refspecs() {
                    if let Ok(s) = r.str() {
                        refspecs.push(s.to_string());
                    }
                }
                info.remotes.push(RemoteInfo {
                    name: name.to_string(),
                    url: remote.url().unwrap_or("(no url)").to_string(),
                    push_url,
                    refspecs,
                });
            }
        }
    }

    if let Ok(commits) = collect_commits(&repo, commit_limit, &build_ref_map(&repo), path) {
        info.commits = commits;
    }

    info.graph_lines = collect_graph_lines(path);

    populate_file_changes(&repo, &mut info);

    if let Ok((stats, limit_reached)) = collect_committer_stats(&repo, 10000) {
        info.committer_stats = stats;
        info.committer_stats_limit_reached = limit_reached;
    }

    let mut local_branches = Vec::new();
    if let Ok(branches) = repo.branches(Some(git2::BranchType::Local)) {
        for (branch, _) in branches.flatten() {
            if let Ok(Some(name)) = branch.name() {
                let is_head = branch.is_head();
                let mut short_sha = String::new();
                let mut short_message = String::new();
                if let Ok(target) = branch.get().peel_to_commit() {
                    let id = target.id();
                    short_sha = id.to_string()[..7.min(id.to_string().len())].to_string();
                    if let Ok(Some(summary)) = target.summary() {
                        short_message = summary.to_string();
                    }
                }
                local_branches.push(BranchInfo {
                    name: name.to_string(),
                    is_head,
                    short_sha,
                    short_message,
                });
            }
        }
    }
    local_branches.sort_by(|a, b| b.is_head.cmp(&a.is_head).then_with(|| a.name.cmp(&b.name)));
    info.local_branches = local_branches;

    let mut remote_branches = Vec::new();
    if let Ok(branches) = repo.branches(Some(git2::BranchType::Remote)) {
        for (branch, _) in branches.flatten() {
            if let Ok(Some(name)) = branch.name() {
                if !name.ends_with("/HEAD") {
                    let is_head = branch.is_head();
                    let mut short_sha = String::new();
                    let mut short_message = String::new();
                    if let Ok(target) = branch.get().peel_to_commit() {
                        let id = target.id();
                        short_sha = id.to_string()[..7.min(id.to_string().len())].to_string();
                        if let Ok(Some(summary)) = target.summary() {
                            short_message = summary.to_string();
                        }
                    }
                    remote_branches.push(BranchInfo {
                        name: name.to_string(),
                        is_head,
                        short_sha,
                        short_message,
                    });
                }
            }
        }
    }
    remote_branches.sort_by(|a, b| a.name.cmp(&b.name));
    info.remote_branches = remote_branches;

    let mut local_tags = Vec::new();
    if let Ok(tags) = repo.tag_names(None) {
        for tag_opt in tags.iter() {
            if let Ok(Some(tag)) = tag_opt {
                let mut short_sha = String::new();
                let mut short_message = String::new();
                if let Ok(reference) = repo.find_reference(&format!("refs/tags/{}", tag)) {
                    if let Ok(target) = reference.peel_to_commit() {
                        let id = target.id();
                        short_sha = id.to_string()[..7.min(id.to_string().len())].to_string();
                        if let Ok(Some(summary)) = target.summary() {
                            short_message = summary.to_string();
                        }
                    }
                }
                local_tags.push(BranchInfo {
                    name: tag.to_string(),
                    is_head: false,
                    short_sha,
                    short_message,
                });
            }
        }
    }
    local_tags.sort_by(|a, b| a.name.cmp(&b.name));
    info.local_tags = local_tags;
    info.remote_tags = Vec::new();
    info.remote_tags_loaded = false;
    info.remote_tags_attempted = false;

    let mut files = Vec::new();
    if let Ok(index) = repo.index() {
        for entry in index.iter() {
            if let Ok(path_str) = std::str::from_utf8(&entry.path) {
                files.push(path_str.to_string());
            }
        }
    }
    info.files = files;

    let mut temp_stashes = Vec::new();
    let _ = repo.stash_foreach(|index, message, oid| {
        temp_stashes.push((index, message.to_string(), *oid));
        true
    });

    let mut stashes = Vec::new();
    for (index, message, oid) in temp_stashes {
        let mut files = Vec::new();
        if let Ok(commit) = repo.find_commit(oid) {
            files = commit_changed_files(&repo, &commit);
        }
        stashes.push(StashInfo {
            index,
            message,
            commit_id: oid.to_string(),
            files,
        });
    }
    info.stashes = stashes;

    Ok(info)
}

/// Build a map from commit `Oid` → list of ref names that point to it.
/// Local branches are stored as plain names (e.g. `"main"`).
/// Lightweight and annotated tags are stored with a `"tag:"` prefix
/// (e.g. `"tag:v1.0"`) so the UI can colour them differently.
fn build_ref_map(repo: &Repository) -> std::collections::HashMap<git2::Oid, Vec<String>> {
    let mut map: std::collections::HashMap<git2::Oid, Vec<String>> =
        std::collections::HashMap::new();

    if let Ok(refs) = repo.references() {
        for reference in refs.flatten() {
            // Resolve to the underlying commit Oid (peeling through tags).
            let Ok(target) = reference.peel_to_commit() else {
                continue;
            };
            let oid = target.id();

            let Ok(full_name) = reference.name() else {
                continue;
            };

            let label = if let Some(branch) = full_name.strip_prefix("refs/heads/") {
                branch.to_string()
            } else if let Some(tag) = full_name.strip_prefix("refs/tags/") {
                format!("tag:{}", tag)
            } else if let Some(remote) = full_name.strip_prefix("refs/remotes/") {
                // Skip the symbolic HEAD pointer each remote keeps (e.g. origin/HEAD).
                if remote.ends_with("/HEAD") {
                    continue;
                }
                format!("remote:{}", remote)
            } else {
                continue;
            };

            map.entry(oid).or_default().push(label);
        }
    }
    map
}

/// Maximum file entries collected per bucket. Prevents pathologically large
/// working trees from overwhelming the detail view.
const MAX_FILES_PER_SECTION: usize = 100;

/// Walk the working-tree status once more and collect per-file info for
/// the Detail view. Called only from `collect_info` (i.e. once per Enter
/// press), never per frame.
fn populate_file_changes(repo: &Repository, info: &mut RepoInfo) {
    let mut opts = StatusOptions::new();
    opts.include_untracked(true)
        .renames_head_to_index(true)
        .recurse_untracked_dirs(true)
        .show(StatusShow::IndexAndWorkdir);
    let Ok(statuses) = repo.statuses(Some(&mut opts)) else {
        return;
    };
    for entry in statuses.iter() {
        let path = entry.path().unwrap_or("(unknown)").to_string();
        let flags = entry.status();

        // Skip directories to avoid showing folders in staging panels
        let path_buf = repo.workdir().unwrap_or(Path::new("")).join(&path);
        if path_buf.is_dir() {
            continue;
        }

        if flags.is_conflicted() {
            if info.changes.conflicted.len() < MAX_FILES_PER_SECTION {
                info.changes.conflicted.push(FileEntry {
                    path: path.clone(),
                    label: "C",
                });
            }
            continue;
        }

        // Index (staged) changes
        if (flags.is_index_new()
            || flags.is_index_modified()
            || flags.is_index_deleted()
            || flags.is_index_renamed()
            || flags.is_index_typechange())
            && info.changes.staged.len() < MAX_FILES_PER_SECTION
        {
            let label = if flags.is_index_new() {
                "N"
            } else if flags.is_index_deleted() {
                "D"
            } else if flags.is_index_renamed() {
                "R"
            } else if flags.is_index_typechange() {
                "T"
            } else {
                "M"
            };
            info.changes.staged.push(FileEntry {
                path: path.clone(),
                label,
            });
        }

        // Working-tree changes
        if flags.is_wt_new() {
            if info.changes.untracked.len() < MAX_FILES_PER_SECTION {
                info.changes.untracked.push(FileEntry {
                    path: path.clone(),
                    label: "?",
                });
            }
            if info.changes.unstaged.len() < MAX_FILES_PER_SECTION {
                info.changes.unstaged.push(FileEntry {
                    path: path.clone(),
                    label: "N",
                });
            }
        } else if (flags.is_wt_modified()
            || flags.is_wt_deleted()
            || flags.is_wt_renamed()
            || flags.is_wt_typechange())
            && info.changes.unstaged.len() < MAX_FILES_PER_SECTION
        {
            let label = if flags.is_wt_deleted() {
                "D"
            } else if flags.is_wt_renamed() {
                "R"
            } else if flags.is_wt_typechange() {
                "T"
            } else {
                "M"
            };
            info.changes.unstaged.push(FileEntry {
                path: path.clone(),
                label,
            });
        }
    }
}

/// Collect the branch name, worktree counts, and ahead/behind for an opened
/// repo. Used by both `inspect_summary` (card) and `collect_info` (detail)
/// so the values shown in both places always agree.
fn collect_summary(repo: &Repository) -> RepoSummary {
    let mut s = RepoSummary::default();
    // git2 0.21: head() + shorthand() = Result<&str, Error>.
    if let Ok(head) = repo.head() {
        s.branch = head.shorthand().ok().map(String::from);
    }
    populate_worktree(repo, &mut s);
    populate_ahead_behind(repo, &mut s);
    s
}

fn populate_worktree(repo: &Repository, s: &mut RepoSummary) {
    let mut opts = StatusOptions::new();
    opts.include_untracked(true)
        .renames_head_to_index(true)
        .show(StatusShow::IndexAndWorkdir);
    let Ok(statuses) = repo.statuses(Some(&mut opts)) else {
        return;
    };
    for entry in statuses.iter() {
        let flags = entry.status();
        if flags.is_conflicted() {
            s.conflicted += 1;
            continue;
        }
        if flags.is_wt_new() {
            s.untracked += 1;
        }
        if flags.is_wt_modified()
            || flags.is_wt_deleted()
            || flags.is_wt_renamed()
            || flags.is_wt_typechange()
        {
            s.modified += 1;
        }
        if flags.is_index_new()
            || flags.is_index_modified()
            || flags.is_index_deleted()
            || flags.is_index_renamed()
            || flags.is_index_typechange()
        {
            s.staged += 1;
        }
    }
}

/// Compute commits ahead/behind the upstream branch. Silently leaves
/// both at 0 if HEAD is detached, the branch has no upstream configured,
/// or any libgit2 lookup fails — the card simply shows no ↑/↓ then.
fn populate_ahead_behind(repo: &Repository, s: &mut RepoSummary) {
    let Ok(head) = repo.head() else { return };
    let Some(local_oid) = head.target() else {
        return;
    };
    let Ok(head_name) = head.name() else { return };
    let Ok(upstream_buf) = repo.branch_upstream_name(head_name) else {
        return;
    };
    let Ok(upstream_name) = std::str::from_utf8(&upstream_buf) else {
        return;
    };
    let Ok(upstream_ref) = repo.find_reference(upstream_name) else {
        return;
    };
    let Some(upstream_oid) = upstream_ref.target() else {
        return;
    };
    if let Ok((ahead, behind)) = repo.graph_ahead_behind(local_oid, upstream_oid) {
        s.ahead = ahead;
        s.behind = behind;
    }
}

/// `"origin/main"`-style short name for HEAD's upstream, or `None`.
fn upstream_short_name(repo: &Repository, head_name: &str) -> Option<String> {
    let buf = repo.branch_upstream_name(head_name).ok()?;
    let raw = std::str::from_utf8(&buf).ok()?;
    Some(raw.strip_prefix("refs/remotes/").unwrap_or(raw).to_string())
}

/// Format a unix-epoch timestamp as a relative time string ("3 days ago").
fn format_relative_time(secs: i64) -> String {
    if secs <= 0 {
        return "unknown".to_string();
    }
    let then = UNIX_EPOCH + Duration::from_secs(secs as u64);
    let now = SystemTime::now();
    let Ok(elapsed) = now.duration_since(then) else {
        return "in the future".to_string();
    };
    let secs = elapsed.as_secs();
    let (n, unit) = if secs < 60 {
        (secs, "second")
    } else if secs < 3600 {
        (secs / 60, "minute")
    } else if secs < 86_400 {
        (secs / 3600, "hour")
    } else if secs < 86_400 * 30 {
        (secs / 86_400, "day")
    } else if secs < 86_400 * 365 {
        (secs / (86_400 * 30), "month")
    } else {
        (secs / (86_400 * 365), "year")
    };
    let plural = if n == 1 { "" } else { "s" };
    format!("{} {}{} ago", n, unit, plural)
}

/// Format a unix-epoch timestamp as a UTC date string ("YYYY-MM-DD HH:MM:SS UTC").
fn format_utc_date(secs: i64) -> String {
    if secs <= 0 {
        return "unknown".to_string();
    }
    let seconds_in_day = 86400;
    let day_number = secs / seconds_in_day;
    let time_of_day = secs % seconds_in_day;

    let mut hour = time_of_day / 3600;
    let mut minute = (time_of_day % 3600) / 60;
    let mut second = time_of_day % 60;
    if hour < 0 {
        hour += 24;
    }
    if minute < 0 {
        minute += 60;
    }
    if second < 0 {
        second += 60;
    }

    // Howard Hinnant's civil date from epoch days algorithm
    let z = day_number + 719468;
    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
    let doe = (z - era * 146097) as u32;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = (yoe as i32) + (era as i32) * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = y + if m <= 2 { 1 } else { 0 };

    format!(
        "{:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC",
        y, m, d, hour, minute, second
    )
}

// ── Per-file diff (private) ────────────────────────────────────────────────

fn get_file_diff_inner(
    repo_path: &Path,
    commit_oid: &str,
    file_path: &str,
) -> Option<Vec<DiffLine>> {
    let repo = Repository::open(repo_path).ok()?;
    let oid = git2::Oid::from_str(commit_oid).ok()?;
    let commit = repo.find_commit(oid).ok()?;

    let commit_tree = commit.tree().ok()?;
    // For the initial commit, parent_tree is None; libgit2 treats it as empty.
    let parent_tree = commit.parent(0).ok().and_then(|p| p.tree().ok());

    let mut opts = git2::DiffOptions::new();
    opts.pathspec(file_path);

    let diff = repo
        .diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), Some(&mut opts))
        .ok()?;

    collect_diff_lines(&diff)
}

/// Diff a single file in the working tree.
///
/// `staged = true`:  HEAD-tree → index (what `git diff --cached` shows).
/// `staged = false`: index → working directory (what `git diff` shows).
fn get_worktree_diff_inner(
    repo_path: &Path,
    file_path: &str,
    staged: bool,
) -> Option<Vec<DiffLine>> {
    let repo = Repository::open(repo_path).ok()?;
    let mut opts = git2::DiffOptions::new();
    opts.pathspec(file_path);
    opts.include_untracked(true);
    opts.recurse_untracked_dirs(true);

    let diff = if staged {
        // Staged: diff HEAD tree (or empty tree for new repos) → index.
        let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok());
        repo.diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))
            .ok()?
    } else {
        // Unstaged: diff index → working directory.
        repo.diff_index_to_workdir(None, Some(&mut opts)).ok()?
    };

    collect_diff_lines(&diff)
}

/// Walk a libgit2 `Diff` and collect coloured `DiffLine` values.
fn collect_diff_lines(diff: &git2::Diff<'_>) -> Option<Vec<DiffLine>> {
    let mut lines: Vec<DiffLine> = Vec::new();
    diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
        let kind = match line.origin() {
            '+' => DiffLineKind::Added,
            '-' => DiffLineKind::Removed,
            'H' => DiffLineKind::Header,
            ' ' => DiffLineKind::Context,
            _ => return true, // skip file-header meta lines
        };
        let content = String::from_utf8_lossy(line.content())
            .trim_end_matches('\n')
            .trim_end_matches('\r')
            .to_string();
        lines.push(DiffLine { kind, content });
        true
    })
    .ok()?;
    Some(lines)
}

fn collect_graph_lines(repo_path: &Path) -> Vec<GraphLine> {
    let mut graph_lines = Vec::new();
    let format_str = "%H__TWIG_SEP__%d__TWIG_SEP__%s__TWIG_SEP__%an__TWIG_SEP__%ad__TWIG_SEP__%G?";

    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .args([
            "log",
            "--graph",
            "--all",
            "--date=relative",
            &format!("--pretty=format:{}", format_str),
            "--color=never",
        ])
        .current_dir(repo_path)
        .output();

    if let Ok(out) = output {
        if out.status.success() {
            let stdout_str = String::from_utf8_lossy(&out.stdout);
            for line in stdout_str.lines() {
                if line.contains("__TWIG_SEP__") {
                    let parts: Vec<&str> = line.split("__TWIG_SEP__").collect();
                    if parts.len() >= 5 {
                        let graph_and_hash = parts[0];
                        let decoration = parts[1].trim().to_string();
                        let summary = parts[2].trim().to_string();
                        let author = parts[3].trim().to_string();
                        let date = parts[4].trim().to_string();
                        let signature_status = if parts.len() >= 6 {
                            parts[5].trim().to_string()
                        } else {
                            "N".to_string()
                        };

                        let char_count = graph_and_hash.chars().count();
                        if char_count >= 40 {
                            let graph: String =
                                graph_and_hash.chars().take(char_count - 40).collect();
                            let oid: String =
                                graph_and_hash.chars().skip(char_count - 40).collect();
                            graph_lines.push(GraphLine {
                                graph,
                                commit: Some(GraphCommit {
                                    oid,
                                    decoration,
                                    summary,
                                    author,
                                    date,
                                    signature_status,
                                }),
                            });
                        } else {
                            graph_lines.push(GraphLine {
                                graph: graph_and_hash.to_string(),
                                commit: None,
                            });
                        }
                    }
                } else {
                    graph_lines.push(GraphLine {
                        graph: line.to_string(),
                        commit: None,
                    });
                }
            }
        }
    }
    graph_lines
}

pub fn checkout_local_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("checkout")
        .arg(branch_name)
        .current_dir(repo_path)
        .output()
        .map_err(|e| git2::Error::from_str(&e.to_string()))?;

    if !output.status.success() {
        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(git2::Error::from_str(&err));
    }
    Ok(())
}

pub fn checkout_remote_branch(
    repo_path: &Path,
    remote_branch_name: &str,
) -> Result<String, git2::Error> {
    let parts: Vec<&str> = remote_branch_name.splitn(2, '/').collect();
    if parts.len() < 2 {
        return Err(git2::Error::from_str("Invalid remote branch name"));
    }
    let local_name = parts[1];

    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("checkout")
        .arg(local_name)
        .current_dir(repo_path)
        .output()
        .map_err(|e| git2::Error::from_str(&e.to_string()))?;

    if output.status.success() {
        return Ok(format!("Switched to existing branch '{}'", local_name));
    }

    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("checkout")
        .arg("--track")
        .arg(remote_branch_name)
        .current_dir(repo_path)
        .output()
        .map_err(|e| git2::Error::from_str(&e.to_string()))?;

    if !output.status.success() {
        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(git2::Error::from_str(&err));
    }

    Ok(format!(
        "Created and switched to branch '{}' tracking '{}'",
        local_name, remote_branch_name
    ))
}

/// Creates a new local branch pointing at HEAD.
pub fn create_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
    let repo = Repository::open(repo_path)?;
    let head = repo.head()?;
    let target_commit = head.peel_to_commit()?;
    repo.branch(branch_name, &target_commit, false)?;
    Ok(())
}

/// Deletes a local branch.
pub fn delete_local_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
    let repo = Repository::open(repo_path)?;
    let mut branch = repo.find_branch(branch_name, git2::BranchType::Local)?;
    branch.delete()?;
    Ok(())
}

/// Deletes a remote-tracking branch locally.
pub fn delete_remote_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
    let repo = Repository::open(repo_path)?;
    let mut branch = repo.find_branch(branch_name, git2::BranchType::Remote)?;
    branch.delete()?;
    Ok(())
}

/// Creates a new lightweight tag pointing at the specified commit OID.
pub fn create_tag(
    repo_path: &Path,
    tag_name: &str,
    commit_oid_str: &str,
) -> Result<(), git2::Error> {
    let repo = Repository::open(repo_path)?;
    let oid = git2::Oid::from_str(commit_oid_str)?;
    let target_object = repo.find_object(oid, Some(git2::ObjectType::Commit))?;
    repo.tag_lightweight(tag_name, &target_object, false)?;
    Ok(())
}

/// Deletes a local tag.
pub fn delete_tag(repo_path: &Path, tag_name: &str) -> Result<(), git2::Error> {
    let repo = Repository::open(repo_path)?;
    repo.tag_delete(tag_name)?;
    Ok(())
}

/// Deletes a tag on the remote.
pub fn delete_remote_tag(
    repo_path: &Path,
    remote_name: &str,
    tag_name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("push")
        .arg(remote_name)
        .arg("--delete")
        .arg(tag_name)
        .current_dir(repo_path)
        .output()?;
    if !output.status.success() {
        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(err.into());
    }
    Ok(())
}

pub fn checkout_tag(repo_path: &Path, tag_name: &str) -> Result<(), git2::Error> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("checkout")
        .arg(tag_name)
        .current_dir(repo_path)
        .output()
        .map_err(|e| git2::Error::from_str(&e.to_string()))?;

    if !output.status.success() {
        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(git2::Error::from_str(&err));
    }
    Ok(())
}

/// Helper to run `git ls-remote --tags` and return parsed tag information.
pub fn get_remote_tags(
    repo_path: &Path,
    remote_name: &str,
) -> Result<Vec<BranchInfo>, Box<dyn std::error::Error>> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("ls-remote")
        .arg("--tags")
        .arg(remote_name)
        .current_dir(repo_path)
        .output()?;

    if !output.status.success() {
        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(err.into());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let repo = git2::Repository::open(repo_path)?;
    let mut tags_map = std::collections::HashMap::new();

    for line in stdout.lines() {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 2 {
            let sha = parts[0];
            let ref_name = parts[1];
            if ref_name.starts_with("refs/tags/") {
                let is_peeled = ref_name.ends_with("^{}");
                let clean_ref = if is_peeled {
                    &ref_name[..ref_name.len() - 3]
                } else {
                    ref_name
                };
                let tag_name = clean_ref.strip_prefix("refs/tags/").unwrap_or(clean_ref);
                let short_sha = if sha.len() >= 7 { &sha[..7] } else { sha };

                // Try to resolve the summary locally
                let mut short_message = String::new();
                if let Ok(oid) = git2::Oid::from_str(sha) {
                    if let Ok(commit) = repo.find_commit(oid) {
                        if let Ok(Some(summary)) = commit.summary() {
                            short_message = summary.to_string();
                        }
                    }
                }
                if short_message.is_empty() {
                    short_message = "(not fetched)".to_string();
                }

                if is_peeled {
                    tags_map.insert(tag_name.to_string(), (short_sha.to_string(), short_message));
                } else {
                    tags_map
                        .entry(tag_name.to_string())
                        .or_insert_with(|| (short_sha.to_string(), short_message));
                }
            }
        }
    }

    let mut tags = Vec::new();
    for (name, (short_sha, short_message)) in tags_map {
        tags.push(BranchInfo {
            name,
            is_head: false,
            short_sha,
            short_message,
        });
    }
    tags.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(tags)
}

pub fn serialize_tags(tags: &[BranchInfo]) -> String {
    let mut s = String::new();
    for tag in tags {
        s.push_str(&format!(
            "{}|{}|{}\n",
            tag.name, tag.short_sha, tag.short_message
        ));
    }
    s
}

pub fn deserialize_tags(s: &str) -> Vec<BranchInfo> {
    let mut tags = Vec::new();
    for line in s.lines() {
        let parts: Vec<&str> = line.split('|').collect();
        if parts.len() >= 3 {
            tags.push(BranchInfo {
                name: parts[0].to_string(),
                is_head: false,
                short_sha: parts[1].to_string(),
                short_message: parts[2].to_string(),
            });
        }
    }
    tags
}

pub fn delete_stash(repo_path: &Path, index: usize) -> Result<(), git2::Error> {
    let mut repo = Repository::open(repo_path)?;
    repo.stash_drop(index)?;
    Ok(())
}

pub fn apply_stash(repo_path: &Path, index: usize) -> Result<(), String> {
    let stash_ref = format!("stash@{{{}}}", index);
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("stash")
        .arg("apply")
        .arg(&stash_ref)
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;

    if !output.status.success() {
        let err_msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(err_msg);
    }
    Ok(())
}

pub fn save_stash(repo_path: &Path, message: &str) -> Result<(), String> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .arg("stash")
        .arg("push")
        .arg("-m")
        .arg(message)
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;

    if !output.status.success() {
        let err_msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(err_msg);
    }
    Ok(())
}

pub fn get_latest_change_time(item: &str) -> u64 {
    let path = expand_tilde(item);
    if !path.exists() {
        return 0;
    }

    if path.join(".git").exists() {
        if let Ok(repo) = Repository::open(&path) {
            if let Ok(head) = repo.head() {
                if let Ok(commit) = head.peel_to_commit() {
                    return commit.time().seconds() as u64;
                }
            }
        }
    }

    if let Ok(meta) = std::fs::metadata(&path) {
        if let Ok(modified) = meta.modified() {
            if let Ok(duration) = modified.duration_since(std::time::UNIX_EPOCH) {
                return duration.as_secs();
            }
        }
    }
    0
}

pub fn get_last_commit_message(repo_path: &Path) -> Option<String> {
    if let Ok(repo) = Repository::open(repo_path) {
        if let Ok(head) = repo.head() {
            if let Ok(commit) = head.peel_to_commit() {
                if let Ok(msg) = commit.message() {
                    return Some(msg.to_string());
                }
            }
        }
    }
    None
}

pub fn commit_amend(repo_path: &Path, message: &str) -> Result<(), String> {
    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
    let head = repo
        .head()
        .map_err(|e| format!("No HEAD commit to amend: {}", e))?;
    let head_commit = head.peel_to_commit().map_err(|e| e.to_string())?;

    let mut index = repo.index().map_err(|e| e.to_string())?;
    let tree_id = index.write_tree().map_err(|e| e.to_string())?;
    let tree = repo.find_tree(tree_id).map_err(|e| e.to_string())?;

    let signature = repo.signature().map_err(|e| {
        format!(
            "Failed to get signature. Check user.name/email config: {}",
            e
        )
    })?;

    head_commit
        .amend(
            Some("HEAD"),
            None,
            Some(&signature),
            None,
            Some(message),
            Some(&tree),
        )
        .map_err(|e| e.to_string())?;

    Ok(())
}

// ── Merge Conflict Helpers ──────────────────────────────────────────────────

/// Returns `true` when `.git/MERGE_HEAD` exists — i.e. a merge is in progress.
/// Cheap file-existence check, no libgit2 required.
pub fn is_merging(repo_path: &Path) -> bool {
    repo_path.join(".git/MERGE_HEAD").exists()
}

/// Returns the conflict-marker diff for a conflicted file by parsing the file on disk.
/// Colorizes conflict blocks using DiffLineKind variants.
pub fn get_conflict_markers_diff(repo_path: &Path, file_path: &str) -> Vec<DiffLine> {
    let full_path = repo_path.join(file_path);
    let content = match std::fs::read_to_string(&full_path) {
        Ok(s) => s,
        Err(_) => return Vec::new(),
    };

    let mut lines = Vec::new();
    let mut in_ours = false;
    let mut in_theirs = false;

    for line in content.lines() {
        if line.starts_with("<<<<<<<") {
            in_ours = true;
            in_theirs = false;
            lines.push(DiffLine {
                kind: DiffLineKind::ConflictSeparator,
                content: line.to_string(),
            });
        } else if line.starts_with("=======") {
            in_ours = false;
            in_theirs = true;
            lines.push(DiffLine {
                kind: DiffLineKind::ConflictSeparator,
                content: line.to_string(),
            });
        } else if line.starts_with(">>>>>>>") {
            in_ours = false;
            in_theirs = false;
            lines.push(DiffLine {
                kind: DiffLineKind::ConflictSeparator,
                content: line.to_string(),
            });
        } else if in_ours {
            lines.push(DiffLine {
                kind: DiffLineKind::ConflictOurs,
                content: line.to_string(),
            });
        } else if in_theirs {
            lines.push(DiffLine {
                kind: DiffLineKind::ConflictTheirs,
                content: line.to_string(),
            });
        } else {
            lines.push(DiffLine {
                kind: DiffLineKind::Context,
                content: line.to_string(),
            });
        }
    }
    lines
}

/// Accept the OURS (HEAD) version of a conflicted file.
/// Equivalent to: git checkout --ours <file> && git add <file>
pub fn resolve_ours(repo_path: &Path, file_path: &str) -> Result<(), String> {
    let output1 = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .args(["checkout", "--ours", file_path])
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;
    if !output1.status.success() {
        return Err(String::from_utf8_lossy(&output1.stderr).to_string());
    }
    stage_file(repo_path, file_path)?;
    Ok(())
}

/// Accept the THEIRS (incoming) version of a conflicted file.
/// Equivalent to: git checkout --theirs <file> && git add <file>
pub fn resolve_theirs(repo_path: &Path, file_path: &str) -> Result<(), String> {
    let output1 = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .args(["checkout", "--theirs", file_path])
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;
    if !output1.status.success() {
        return Err(String::from_utf8_lossy(&output1.stderr).to_string());
    }
    stage_file(repo_path, file_path)?;
    Ok(())
}

/// Mark the file as resolved (stage it) after manual edits.
pub fn mark_resolved(repo_path: &Path, file_path: &str) -> Result<(), String> {
    stage_file(repo_path, file_path)
}

/// Resolve a specific conflict hunk inside a file (Ours vs Theirs).
/// Replaces the hunk at index `hunk_idx` in the file on disk.
/// If no more conflicts remain in the file, it automatically stages the file.
pub fn resolve_conflict_hunk(
    repo_path: &Path,
    file_path: &str,
    hunk_idx: usize,
    accept_ours: bool,
) -> Result<(), String> {
    let full_path = repo_path.join(file_path);
    let content = std::fs::read_to_string(&full_path).map_err(|e| e.to_string())?;

    let mut new_lines = Vec::new();
    let mut lines_iter = content.lines().peekable();
    let mut current_hunk_idx = 0;

    while let Some(line) = lines_iter.next() {
        if line.starts_with("<<<<<<<") {
            let mut ours_block = Vec::new();
            let mut theirs_block = Vec::new();

            // Read ours block (until =======)
            let mut found_separator = false;
            while let Some(next_line) = lines_iter.peek() {
                if next_line.starts_with("=======") {
                    lines_iter.next(); // consume =======
                    found_separator = true;
                    break;
                }
                ours_block.push(lines_iter.next().unwrap().to_string());
            }

            // Read theirs block (until >>>>>>>)
            let mut found_end = false;
            let mut end_line_marker = ">>>>>>>".to_string();
            while let Some(next_line) = lines_iter.peek() {
                if next_line.starts_with(">>>>>>>") {
                    end_line_marker = lines_iter.next().unwrap().to_string(); // consume >>>>>>>
                    found_end = true;
                    break;
                }
                theirs_block.push(lines_iter.next().unwrap().to_string());
            }

            if current_hunk_idx == hunk_idx {
                if accept_ours {
                    new_lines.extend(ours_block);
                } else {
                    new_lines.extend(theirs_block);
                }
            } else {
                new_lines.push(line.to_string());
                new_lines.extend(ours_block);
                if found_separator {
                    new_lines.push("=======".to_string());
                }
                new_lines.extend(theirs_block);
                if found_end {
                    new_lines.push(end_line_marker);
                }
            }

            current_hunk_idx += 1;
        } else {
            new_lines.push(line.to_string());
        }
    }

    let mut new_content = new_lines.join("\n");
    if content.ends_with('\n') && !new_content.ends_with('\n') {
        new_content.push('\n');
    }
    std::fs::write(&full_path, new_content).map_err(|e| e.to_string())?;

    // Check if any conflict markers remain in the file
    let updated_content = std::fs::read_to_string(&full_path).map_err(|e| e.to_string())?;
    let has_conflict_markers = updated_content
        .lines()
        .any(|l| l.starts_with("<<<<<<<") || l.starts_with("=======") || l.starts_with(">>>>>>>"));

    if !has_conflict_markers {
        stage_file(repo_path, file_path)?;
    }

    Ok(())
}

/// Abort the in-progress merge.
pub fn abort_merge(repo_path: &Path) -> Result<(), String> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .args(["merge", "--abort"])
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;
    if !output.status.success() {
        return Err(String::from_utf8_lossy(&output.stderr).to_string());
    }
    Ok(())
}

/// Continue the merge after conflicts are resolved.
pub fn continue_merge(repo_path: &Path) -> Result<(), String> {
    let output = std::process::Command::new("git")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
        .args(["merge", "--continue"])
        .env("GIT_EDITOR", "true")
        .current_dir(repo_path)
        .output()
        .map_err(|e| e.to_string())?;
    if !output.status.success() {
        return Err(String::from_utf8_lossy(&output.stderr).to_string());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;

    #[test]
    fn test_commit_amend() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // Create initial file
        let file_path = temp_path.join("test.txt");
        let mut file = File::create(&file_path).unwrap();
        writeln!(file, "initial content").unwrap();

        // Stage and commit initial
        stage_file(&temp_path, "test.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // Verify message
        let msg = get_last_commit_message(&temp_path).unwrap();
        assert_eq!(msg, "initial commit");

        // Amend the commit message
        commit_amend(&temp_path, "amended commit").unwrap();

        // Verify amended message
        let amended_msg = get_last_commit_message(&temp_path).unwrap();
        assert_eq!(amended_msg, "amended commit");

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_commit_signatures_collection() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_sig_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // Create initial file
        let file_path = temp_path.join("test.txt");
        let mut file = File::create(&file_path).unwrap();
        writeln!(file, "initial content").unwrap();

        // Stage and commit initial
        stage_file(&temp_path, "test.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // 1. Test collect_signatures
        let sigs = collect_signatures(&temp_path, 0);
        assert_eq!(sigs.len(), 1);
        let head_oid = repo.head().unwrap().target().unwrap().to_string();
        let sig_status = sigs.get(&head_oid).unwrap();
        assert_eq!(sig_status, "N");

        // 2. Test collect_commits
        let commits = collect_commits(&repo, 0, &build_ref_map(&repo), &temp_path).unwrap();
        assert_eq!(commits.len(), 1);
        assert_eq!(commits[0].signature_status, "N");

        // 3. Test collect_graph_lines
        let graph = collect_graph_lines(&temp_path);
        assert_eq!(graph.len(), 1);
        assert!(graph[0].commit.is_some());
        assert_eq!(graph[0].commit.as_ref().unwrap().signature_status, "N");

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_get_latest_change_time() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        let change_time = get_latest_change_time(temp_path.to_str().unwrap());
        assert!(change_time > 0);

        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_committer_stats() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // Create initial file
        let file_path = temp_path.join("test.txt");
        let mut file = File::create(&file_path).unwrap();
        writeln!(file, "initial content").unwrap();

        // Stage and commit initial
        stage_file(&temp_path, "test.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // Collect stats
        let (stats, limit_reached) = collect_committer_stats(&repo, 10).unwrap();
        assert_eq!(stats.len(), 1);
        assert_eq!(stats[0].name, "Test User");
        assert_eq!(stats[0].email, "test@example.com");
        assert_eq!(stats[0].count, 1);
        assert!(!limit_reached);

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_untracked_files_in_unstaged() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let _repo = Repository::init(&temp_path).unwrap();

        // Create an untracked file
        let file_path = temp_path.join("untracked.txt");
        let mut file = File::create(&file_path).unwrap();
        writeln!(file, "hello untracked").unwrap();

        // Create an untracked directory and a file inside it
        let untracked_dir = temp_path.join("untracked_dir");
        std::fs::create_dir_all(&untracked_dir).unwrap();
        let nested_file_path = untracked_dir.join("nested.txt");
        std::fs::write(&nested_file_path, "nested untracked file").unwrap();

        // Inspect detail
        let detail = inspect_detail(temp_path.to_str().unwrap(), 0);
        match detail {
            ItemDetail::Repo { info, .. } => {
                // Verify no folders are in the unstaged/untracked list
                let unstaged_paths: Vec<String> = info
                    .changes
                    .unstaged
                    .iter()
                    .map(|f| f.path.clone())
                    .collect();
                let untracked_paths: Vec<String> = info
                    .changes
                    .untracked
                    .iter()
                    .map(|f| f.path.clone())
                    .collect();

                // Folder itself should NOT be listed
                assert!(!unstaged_paths.contains(&"untracked_dir".to_string()));
                assert!(!unstaged_paths.contains(&"untracked_dir/".to_string()));
                assert!(!untracked_paths.contains(&"untracked_dir".to_string()));
                assert!(!untracked_paths.contains(&"untracked_dir/".to_string()));

                // Untracked files (both root and nested) should be listed
                assert!(unstaged_paths.contains(&"untracked.txt".to_string()));
                assert!(unstaged_paths.contains(&"untracked_dir/nested.txt".to_string()));
                assert!(untracked_paths.contains(&"untracked.txt".to_string()));
                assert!(untracked_paths.contains(&"untracked_dir/nested.txt".to_string()));
            }
            _ => panic!("Expected ItemDetail::Repo"),
        }

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_stage_new_and_deleted_files() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // Create initial file & commit
        let init_file = temp_path.join("init.txt");
        std::fs::write(&init_file, "initial").unwrap();
        stage_file(&temp_path, "init.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // 1. Create a new file (untracked)
        let untracked_file = temp_path.join("untracked.txt");
        std::fs::write(&untracked_file, "new file content").unwrap();

        // Try staging untracked file
        stage_file(&temp_path, "untracked.txt").unwrap();

        // 2. Delete the initial file
        std::fs::remove_file(&init_file).unwrap();

        // Try staging deleted file
        stage_file(&temp_path, "init.txt").unwrap();

        // Check status of repo
        let detail = inspect_detail(temp_path.to_str().unwrap(), 0);
        match detail {
            ItemDetail::Repo { info, .. } => {
                // Both should be in staged changes
                assert_eq!(info.changes.staged.len(), 2);
                let paths: Vec<String> =
                    info.changes.staged.iter().map(|f| f.path.clone()).collect();
                assert!(paths.contains(&"untracked.txt".to_string()));
                assert!(paths.contains(&"init.txt".to_string()));
            }
            _ => panic!("Expected ItemDetail::Repo"),
        }

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_discard_file_changes_all_cases() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // Create and commit initial files
        let file_tracked = temp_path.join("tracked.txt");
        std::fs::write(&file_tracked, "original content\n").unwrap();
        stage_file(&temp_path, "tracked.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // Case 1: Untracked file
        let file_untracked = temp_path.join("untracked.txt");
        std::fs::write(&file_untracked, "new untracked file\n").unwrap();
        assert!(file_untracked.exists());
        discard_file_changes(&temp_path, "untracked.txt", false).unwrap();
        assert!(!file_untracked.exists());

        // Case 2: Tracked file with unstaged modification
        std::fs::write(&file_tracked, "unstaged modifications\n").unwrap();
        discard_file_changes(&temp_path, "tracked.txt", false).unwrap();
        assert_eq!(
            std::fs::read_to_string(&file_tracked).unwrap(),
            "original content\n"
        );

        // Case 3: Tracked file with staged modification
        std::fs::write(&file_tracked, "staged modifications\n").unwrap();
        stage_file(&temp_path, "tracked.txt").unwrap();
        // verify it's staged
        let detail = inspect_detail(temp_path.to_str().unwrap(), 0);
        match detail {
            ItemDetail::Repo { info, .. } => {
                assert!(!info.changes.staged.is_empty());
            }
            _ => panic!("Expected ItemDetail::Repo"),
        }
        discard_file_changes(&temp_path, "tracked.txt", true).unwrap();
        assert_eq!(
            std::fs::read_to_string(&file_tracked).unwrap(),
            "original content\n"
        );
        // verify it's no longer staged/unstaged (it's clean)
        let detail = inspect_detail(temp_path.to_str().unwrap(), 0);
        match detail {
            ItemDetail::Repo { info, .. } => {
                assert!(info.changes.staged.is_empty());
                assert!(info.changes.unstaged.is_empty());
            }
            _ => panic!("Expected ItemDetail::Repo"),
        }

        // Case 4: Tracked deleted file
        std::fs::remove_file(&file_tracked).unwrap();
        assert!(!file_tracked.exists());
        discard_file_changes(&temp_path, "tracked.txt", false).unwrap();
        assert!(file_tracked.exists());
        assert_eq!(
            std::fs::read_to_string(&file_tracked).unwrap(),
            "original content\n"
        );

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_stage_unstage_by_hunk() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // Create initial file with multiple lines
        let file_path = temp_path.join("multihunk.txt");
        let mut file = File::create(&file_path).unwrap();
        for i in 1..=20 {
            writeln!(file, "Line {}", i).unwrap();
        }
        drop(file);

        // Stage and commit initial
        stage_file(&temp_path, "multihunk.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // Now modify lines 2 and 18 to create two distinct hunks
        let mut file = File::create(&file_path).unwrap();
        for i in 1..=20 {
            if i == 2 || i == 18 {
                writeln!(file, "Line {} modified", i).unwrap();
            } else {
                writeln!(file, "Line {}", i).unwrap();
            }
        }
        drop(file);

        // Get the unstaged diff lines
        let diff_lines = get_worktree_file_diff(&temp_path, "multihunk.txt", false);
        // Identify hunk ranges. A hunk header starts with "@@"
        let mut hunk_ranges = Vec::new();
        let mut current_start = None;
        for (i, line) in diff_lines.iter().enumerate() {
            if line.kind == DiffLineKind::Header {
                if let Some(start) = current_start {
                    hunk_ranges.push(start..i);
                }
                current_start = Some(i);
            }
        }
        if let Some(start) = current_start {
            hunk_ranges.push(start..diff_lines.len());
        }

        // We expect exactly 2 hunks
        assert_eq!(hunk_ranges.len(), 2);

        // Stage the second hunk
        let hunk2 = &diff_lines[hunk_ranges[1].clone()];
        stage_hunk(&temp_path, "multihunk.txt", hunk2).unwrap();

        // Now check staged diff for the file: it should contain the second modification
        let staged_diff = get_worktree_file_diff(&temp_path, "multihunk.txt", true);
        let staged_content: String = staged_diff
            .iter()
            .map(|l| l.content.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(staged_content.contains("Line 18 modified"));
        assert!(!staged_content.contains("Line 2 modified"));

        // Check unstaged diff for the file: it should contain the first modification
        let unstaged_diff = get_worktree_file_diff(&temp_path, "multihunk.txt", false);
        let unstaged_content: String = unstaged_diff
            .iter()
            .map(|l| l.content.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(unstaged_content.contains("Line 2 modified"));
        assert!(!unstaged_content.contains("Line 18 modified"));

        // Unstage the staged hunk
        let staged_hunk_ranges = {
            let mut ranges = Vec::new();
            let mut current_start = None;
            for (i, line) in staged_diff.iter().enumerate() {
                if line.kind == DiffLineKind::Header {
                    if let Some(start) = current_start {
                        ranges.push(start..i);
                    }
                    current_start = Some(i);
                }
            }
            if let Some(start) = current_start {
                ranges.push(start..staged_diff.len());
            }
            ranges
        };
        assert_eq!(staged_hunk_ranges.len(), 1);
        let staged_hunk = &staged_diff[staged_hunk_ranges[0].clone()];
        unstage_hunk(&temp_path, "multihunk.txt", staged_hunk).unwrap();

        // Staged diff should now be empty
        let staged_diff_after = get_worktree_file_diff(&temp_path, "multihunk.txt", true);
        assert!(staged_diff_after.is_empty());

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_discard_hunk() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // Create initial file with multiple lines
        let file_path = temp_path.join("discardhunk.txt");
        let mut file = File::create(&file_path).unwrap();
        for i in 1..=20 {
            writeln!(file, "Line {}", i).unwrap();
        }
        drop(file);

        // Stage and commit initial
        stage_file(&temp_path, "discardhunk.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // Now modify lines 2 and 18 to create two distinct hunks
        let mut file = File::create(&file_path).unwrap();
        for i in 1..=20 {
            if i == 2 || i == 18 {
                writeln!(file, "Line {} modified", i).unwrap();
            } else {
                writeln!(file, "Line {}", i).unwrap();
            }
        }
        drop(file);

        // Get the unstaged diff lines
        let diff_lines = get_worktree_file_diff(&temp_path, "discardhunk.txt", false);
        // Identify hunk ranges
        let mut hunk_ranges = Vec::new();
        let mut current_start = None;
        for (i, line) in diff_lines.iter().enumerate() {
            if line.kind == DiffLineKind::Header {
                if let Some(start) = current_start {
                    hunk_ranges.push(start..i);
                }
                current_start = Some(i);
            }
        }
        if let Some(start) = current_start {
            hunk_ranges.push(start..diff_lines.len());
        }

        // We expect exactly 2 hunks
        assert_eq!(hunk_ranges.len(), 2);

        // Discard the second hunk (Line 18 modified)
        let hunk2 = &diff_lines[hunk_ranges[1].clone()];
        discard_hunk(&temp_path, "discardhunk.txt", hunk2).unwrap();

        // Now check file contents: line 18 should be reverted to "Line 18", while line 2 should remain "Line 2 modified"
        let contents = std::fs::read_to_string(&file_path).unwrap();
        assert!(contents.contains("Line 2 modified"));
        assert!(contents.contains("Line 18\n"));
        assert!(!contents.contains("Line 18 modified"));

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_stage_unstage_discard_line() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        let repo = Repository::init(&temp_path).unwrap();
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // 1. Create initial file
        let file_path = temp_path.join("line_test.txt");
        let mut file = File::create(&file_path).unwrap();
        writeln!(file, "line A").unwrap();
        writeln!(file, "line B").unwrap();
        writeln!(file, "line C").unwrap();
        drop(file);

        stage_file(&temp_path, "line_test.txt").unwrap();
        commit_changes(&temp_path, "initial").unwrap();

        // 2. Modify to introduce two distinct changes in one hunk
        let mut file = File::create(&file_path).unwrap();
        writeln!(file, "line A modified").unwrap();
        writeln!(file, "line B").unwrap();
        writeln!(file, "line C modified").unwrap();
        drop(file);

        let diff_lines = get_worktree_file_diff(&temp_path, "line_test.txt", false);
        let mut hunk_ranges = Vec::new();
        let mut current_start = None;
        for (i, line) in diff_lines.iter().enumerate() {
            if line.kind == DiffLineKind::Header {
                if let Some(start) = current_start {
                    hunk_ranges.push(start..i);
                }
                current_start = Some(i);
            }
        }
        if let Some(start) = current_start {
            hunk_ranges.push(start..diff_lines.len());
        }

        assert_eq!(hunk_ranges.len(), 1);
        let hunk0 = &diff_lines[hunk_ranges[0].clone()];

        assert_eq!(hunk0[2].content, "line A modified");
        assert_eq!(hunk0[5].content, "line C modified");

        // A) Stage line A modified (relative index 2)
        stage_line(&temp_path, "line_test.txt", hunk0, 2).unwrap();

        // Check staged diff
        let staged_diff = get_worktree_file_diff(&temp_path, "line_test.txt", true);
        assert!(
            staged_diff
                .iter()
                .any(|l| l.kind == DiffLineKind::Added && l.content == "line A modified")
        );
        assert!(
            !staged_diff
                .iter()
                .any(|l| l.kind == DiffLineKind::Added && l.content == "line C modified")
        );

        // Check unstaged diff
        let unstaged_diff = get_worktree_file_diff(&temp_path, "line_test.txt", false);
        assert!(
            !unstaged_diff
                .iter()
                .any(|l| l.kind == DiffLineKind::Added && l.content == "line A modified")
        );
        assert!(
            unstaged_diff
                .iter()
                .any(|l| l.kind == DiffLineKind::Added && l.content == "line C modified")
        );

        // B) Unstage line A modified
        assert_eq!(staged_diff[2].content, "line A modified");
        unstage_line(&temp_path, "line_test.txt", &staged_diff, 2).unwrap();

        // Staged diff should now be empty
        assert!(get_worktree_file_diff(&temp_path, "line_test.txt", true).is_empty());

        // C) Discard line C modified (index 5) in unstaged diff
        let unstaged_diff2 = get_worktree_file_diff(&temp_path, "line_test.txt", false);
        assert_eq!(unstaged_diff2[5].content, "line C modified");
        discard_line(&temp_path, "line_test.txt", &unstaged_diff2, 5).unwrap();

        let unstaged_diff3 = get_worktree_file_diff(&temp_path, "line_test.txt", false);
        let remove_idx = unstaged_diff3
            .iter()
            .position(|l| l.kind == DiffLineKind::Removed && l.content == "line C")
            .unwrap();
        discard_line(&temp_path, "line_test.txt", &unstaged_diff3, remove_idx).unwrap();

        // File contents check
        let contents = std::fs::read_to_string(&file_path).unwrap();
        assert!(contents.contains("line A modified"));
        assert!(contents.contains("line B"));
        assert!(contents.contains("line C\n"));
        assert!(!contents.contains("line C modified"));

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_stage_unstage_discard_all_changes() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_all_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // Create initial file & commit it
        let file_path = temp_path.join("tracked.txt");
        std::fs::write(&file_path, "original content\n").unwrap();
        stage_file(&temp_path, "tracked.txt").unwrap();
        commit_changes(&temp_path, "initial").unwrap();

        // 1. Make a modification and create a new untracked file
        std::fs::write(&file_path, "modified content\n").unwrap();
        let untracked_path = temp_path.join("untracked.txt");
        std::fs::write(&untracked_path, "untracked content\n").unwrap();

        // Verify status has unstaged changes
        let status = repo.statuses(None).unwrap();
        assert_eq!(status.len(), 2);

        // Stage all changes
        stage_all_changes(&temp_path).unwrap();

        // Verify all changes are staged
        let status = repo.statuses(None).unwrap();
        for entry in status.iter() {
            assert!(
                entry
                    .status()
                    .intersects(git2::Status::INDEX_MODIFIED | git2::Status::INDEX_NEW)
            );
        }

        // Unstage all changes
        unstage_all_changes(&temp_path).unwrap();

        // Verify all changes are unstaged again
        let status = repo.statuses(None).unwrap();
        for entry in status.iter() {
            assert!(
                entry
                    .status()
                    .intersects(git2::Status::WT_MODIFIED | git2::Status::WT_NEW)
            );
        }

        // Discard all changes
        discard_all_changes(&temp_path).unwrap();

        // Verify repo is completely clean
        let status = repo.statuses(None).unwrap();
        assert_eq!(status.len(), 0);

        // Verify tracked file is reset and untracked file is removed
        let contents = std::fs::read_to_string(&file_path).unwrap();
        assert_eq!(contents, "original content\n");
        assert!(!untracked_path.exists());

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_merge_conflicts_flow() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_conflict_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // 1. Initial commit on main
        let file_path = temp_path.join("conflict.txt");
        std::fs::write(&file_path, "line 1\nline 2\nline 3\n").unwrap();
        stage_file(&temp_path, "conflict.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // Get the main branch name first
        let output = std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["symbolic-ref", "--short", "HEAD"])
            .current_dir(&temp_path)
            .output()
            .unwrap();
        let main_branch = String::from_utf8_lossy(&output.stdout).trim().to_string();

        // 2. Create feature branch and edit
        std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["checkout", "-b", "feature"])
            .current_dir(&temp_path)
            .output()
            .unwrap();

        std::fs::write(&file_path, "line 1\nline 2 on feature\nline 3\n").unwrap();
        stage_file(&temp_path, "conflict.txt").unwrap();
        commit_changes(&temp_path, "feature commit").unwrap();

        // 3. Checkout main/master and edit differently
        std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["checkout", &main_branch])
            .current_dir(&temp_path)
            .output()
            .unwrap();

        std::fs::write(&file_path, "line 1\nline 2 on main\nline 3\n").unwrap();
        stage_file(&temp_path, "conflict.txt").unwrap();
        commit_changes(&temp_path, "main commit").unwrap();

        // 4. Merge feature into main -> conflict
        assert!(!is_merging(&temp_path));
        let merge_output = std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["merge", "feature"])
            .current_dir(&temp_path)
            .output()
            .unwrap();

        assert!(!merge_output.status.success());
        assert!(is_merging(&temp_path));

        // 5. Check conflict markers diff
        let diff = get_conflict_markers_diff(&temp_path, "conflict.txt");
        assert!(!diff.is_empty());
        let has_separator = diff
            .iter()
            .any(|l| matches!(l.kind, DiffLineKind::ConflictSeparator));
        let has_ours = diff
            .iter()
            .any(|l| matches!(l.kind, DiffLineKind::ConflictOurs));
        let has_theirs = diff
            .iter()
            .any(|l| matches!(l.kind, DiffLineKind::ConflictTheirs));
        assert!(has_separator);
        assert!(has_ours);
        assert!(has_theirs);

        // 6. Abort merge and verify
        abort_merge(&temp_path).unwrap();
        assert!(!is_merging(&temp_path));

        // 7. Conflict again to test resolve_ours/resolve_theirs
        std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["merge", "feature"])
            .current_dir(&temp_path)
            .output()
            .unwrap();
        assert!(is_merging(&temp_path));

        // Test resolve_ours
        resolve_ours(&temp_path, "conflict.txt").unwrap();
        let contents = std::fs::read_to_string(&file_path).unwrap();
        assert!(contents.contains("line 2 on main"));
        assert!(!contents.contains("<<<<<<<"));

        // Since it's resolved, we can continue merge
        continue_merge(&temp_path).unwrap();
        assert!(!is_merging(&temp_path));

        // 8. Test resolve_theirs by resetting main to before the merge
        std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["reset", "--hard", "HEAD~1"])
            .current_dir(&temp_path)
            .output()
            .unwrap();

        std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["merge", "feature"])
            .current_dir(&temp_path)
            .output()
            .unwrap();
        assert!(is_merging(&temp_path));

        resolve_theirs(&temp_path, "conflict.txt").unwrap();
        let contents_theirs = std::fs::read_to_string(&file_path).unwrap();
        assert!(contents_theirs.contains("line 2 on feature"));
        assert!(!contents_theirs.contains("<<<<<<<"));

        continue_merge(&temp_path).unwrap();
        assert!(!is_merging(&temp_path));

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }

    #[test]
    fn test_resolve_conflict_hunk() {
        let mut temp_path = std::env::temp_dir();
        temp_path.push(format!(
            "twig_test_hunk_conflict_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_path).unwrap();

        // Init repo
        let repo = Repository::init(&temp_path).unwrap();

        // Configure author
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();

        // 1. Initial commit on main
        let file_path = temp_path.join("conflict.txt");
        let initial_lines = "line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\n";
        std::fs::write(&file_path, initial_lines).unwrap();
        stage_file(&temp_path, "conflict.txt").unwrap();
        commit_changes(&temp_path, "initial commit").unwrap();

        // Get the main branch name first
        let output = std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["symbolic-ref", "--short", "HEAD"])
            .current_dir(&temp_path)
            .output()
            .unwrap();
        let main_branch = String::from_utf8_lossy(&output.stdout).trim().to_string();

        // 2. Create feature branch and edit line 2 and line 11
        std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["checkout", "-b", "feature"])
            .current_dir(&temp_path)
            .output()
            .unwrap();
        let feature_lines = "line 1\nline 2 on feature\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11 on feature\nline 12\n";
        std::fs::write(&file_path, feature_lines).unwrap();
        stage_file(&temp_path, "conflict.txt").unwrap();
        commit_changes(&temp_path, "feature commit").unwrap();

        // 3. Checkout main/master and edit line 2 and line 11 differently
        std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["checkout", &main_branch])
            .current_dir(&temp_path)
            .output()
            .unwrap();
        let main_lines = "line 1\nline 2 on main\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11 on main\nline 12\n";
        std::fs::write(&file_path, main_lines).unwrap();
        stage_file(&temp_path, "conflict.txt").unwrap();
        commit_changes(&temp_path, "main commit").unwrap();

        // 4. Merge feature into main -> conflict
        let merge_output = std::process::Command::new("git")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new")
            .args(["merge", "feature"])
            .current_dir(&temp_path)
            .output()
            .unwrap();
        assert!(!merge_output.status.success());
        assert!(is_merging(&temp_path));

        // 5. Resolve first hunk as Ours
        resolve_conflict_hunk(&temp_path, "conflict.txt", 0, true).unwrap();
        let contents_after_first = std::fs::read_to_string(&file_path).unwrap();
        // Line 2 should be resolved to main
        assert!(contents_after_first.contains("line 2 on main"));
        assert!(!contents_after_first.contains("line 2 on feature"));
        // Line 11 should still have conflict markers
        assert!(contents_after_first.contains("<<<<<<<"));
        assert!(contents_after_first.contains("line 11 on main"));
        assert!(contents_after_first.contains("line 11 on feature"));

        // Repo should still be in a merging state because 1 conflict hunk remains
        assert!(is_merging(&temp_path));

        // 6. Resolve second hunk (which is now hunk 0, since hunk 0 was resolved and removed)
        // Wait, did the hunk count change? Yes, the first conflict block was removed,
        // so the remaining conflict block at line 11 becomes the 0th hunk in the file!
        // Let's call resolve_conflict_hunk with hunk_idx 0!
        resolve_conflict_hunk(&temp_path, "conflict.txt", 0, false).unwrap();
        let contents_after_second = std::fs::read_to_string(&file_path).unwrap();
        // Both lines should be resolved, no conflict markers left
        assert!(contents_after_second.contains("line 2 on main"));
        assert!(contents_after_second.contains("line 11 on feature"));
        assert!(!contents_after_second.contains("<<<<<<<"));

        // File is fully resolved so it should have been automatically staged
        let status = repo.statuses(None).unwrap();
        assert_eq!(status.len(), 1);
        assert!(
            status
                .get(0)
                .unwrap()
                .status()
                .contains(git2::Status::INDEX_MODIFIED)
        );

        // Continue and finalize the merge
        continue_merge(&temp_path).unwrap();
        assert!(!is_merging(&temp_path));

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_path);
    }
}