git-surgeon 0.1.15

Surgical git hunk control for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
use anyhow::{Context, Result};
use std::collections::{HashMap, HashSet};
use std::process::Command;

use crate::diff::DiffHunk;
use crate::hunk_id::assign_ids;
use crate::patch::{
    ApplyMode, apply_patch, build_patch, slice_hunk, slice_hunk_multi, slice_hunk_with_state,
};

const MAX_PREVIEW_LINES: usize = 4;

pub fn list_hunks(
    staged: bool,
    file: Option<&str>,
    commit: Option<&str>,
    full: bool,
    blame: bool,
) -> Result<()> {
    let diff_output = match commit {
        Some(c) => crate::diff::run_git_diff_commit(c, file)?,
        None => crate::diff::run_git_diff(staged, file)?,
    };
    let hunks = crate::diff::parse_diff(&diff_output);
    let identified = assign_ids(&hunks);

    if identified.is_empty() {
        return Ok(());
    }

    for (id, hunk) in &identified {
        let additions = hunk.lines.iter().filter(|l| l.starts_with('+')).count();
        let deletions = hunk.lines.iter().filter(|l| l.starts_with('-')).count();

        // Extract function context from @@ header (text after the closing @@)
        let func_ctx = hunk
            .header
            .find("@@ ")
            .and_then(|start| {
                let rest = &hunk.header[start + 3..];
                rest.find("@@ ").map(|end| rest[end + 3..].trim())
            })
            .unwrap_or("");

        let func_part = if func_ctx.is_empty() {
            String::new()
        } else {
            format!(" {}", func_ctx)
        };

        println!(
            "{} {}{} (+{} -{})",
            id, hunk.file, func_part, additions, deletions
        );

        if blame {
            // Blame mode: show all lines with blame hashes (takes precedence over full)
            print_blamed_lines(hunk, commit)?;
        } else if full {
            // Full mode: show all lines with line numbers (like show command)
            let width = hunk.lines.len().to_string().len();
            for (i, line) in hunk.lines.iter().enumerate() {
                println!("{:>w$}:{}", i + 1, line, w = width);
            }
        } else {
            // Preview mode: show up to MAX_PREVIEW_LINES changed lines
            let changed: Vec<&String> = hunk
                .lines
                .iter()
                .filter(|l| l.starts_with('+') || l.starts_with('-'))
                .collect();

            let show = changed.len().min(MAX_PREVIEW_LINES);
            for line in &changed[..show] {
                println!("  {}", line);
            }
            if changed.len() > MAX_PREVIEW_LINES {
                println!("  ... (+{} more lines)", changed.len() - MAX_PREVIEW_LINES);
            }
        }
        println!();
    }

    Ok(())
}

fn print_blamed_lines(hunk: &crate::diff::DiffHunk, commit: Option<&str>) -> Result<()> {
    use crate::blame::{get_blame, parse_hunk_header};

    let (old_from, old_count, new_from, new_count) =
        parse_hunk_header(&hunk.header).unwrap_or((1, 0, 1, 0));

    // Determine blame revisions based on diff type
    // For commit diffs: old = commit^, new = commit
    // For unstaged/staged: old = HEAD, new = working tree (returns 0000000)
    let (old_rev_str, new_rev): (String, Option<&str>) = match commit {
        Some(c) => (format!("{}^", c), Some(c)),
        None => ("HEAD".to_string(), None),
    };

    // Get blame for old side (for context and removed lines)
    let old_blame = if hunk.old_file != "dev/null" && old_count > 0 {
        get_blame(&hunk.old_file, old_from, old_count, Some(&old_rev_str)).unwrap_or_default()
    } else {
        Vec::new()
    };

    // Get blame for new side (for context and added lines)
    let new_blame = if hunk.new_file != "dev/null" && new_count > 0 {
        get_blame(&hunk.new_file, new_from, new_count, new_rev).unwrap_or_default()
    } else {
        Vec::new()
    };

    // Walk through lines with indices
    let mut old_idx = 0usize;
    let mut new_idx = 0usize;

    for line in &hunk.lines {
        let hash = if line.starts_with(' ') {
            // Context line: use new side blame (exists in both)
            let h = new_blame
                .get(new_idx)
                .map(|s| s.as_str())
                .unwrap_or("0000000");
            old_idx += 1;
            new_idx += 1;
            h.to_string()
        } else if line.starts_with('-') {
            // Removed line: use old side blame
            let h = old_blame
                .get(old_idx)
                .map(|s| s.as_str())
                .unwrap_or("0000000");
            old_idx += 1;
            h.to_string()
        } else if line.starts_with('+') {
            // Added line: use new side blame (0000000 for uncommitted)
            let h = new_blame
                .get(new_idx)
                .map(|s| s.as_str())
                .unwrap_or("0000000");
            new_idx += 1;
            h.to_string()
        } else {
            // Unknown line type (e.g., "\ No newline"), skip blame
            println!("  {}", line);
            continue;
        };

        // Keep indentation to match existing preview line style
        println!("  {} {}", hash, line);
    }

    Ok(())
}

pub fn show_hunk(id: &str, commit: Option<&str>) -> Result<()> {
    let hunk = match commit {
        Some(c) => find_hunk_in_commit(id, c)?,
        None => find_hunk_by_id(id, false).or_else(|_| find_hunk_by_id(id, true))?,
    };

    println!("{}", hunk.header);
    let width = hunk.lines.len().to_string().len();
    for (i, line) in hunk.lines.iter().enumerate() {
        println!("{:>w$}:{}", i + 1, line, w = width);
    }
    Ok(())
}

fn find_hunk_in_commit(id: &str, commit: &str) -> Result<DiffHunk> {
    let diff_output = crate::diff::run_git_diff_commit(commit, None)?;
    let hunks = crate::diff::parse_diff(&diff_output);
    let identified = assign_ids(&hunks);
    identified
        .into_iter()
        .find(|(hunk_id, _)| hunk_id == id)
        .map(|(_, hunk)| hunk.clone())
        .ok_or_else(|| anyhow::anyhow!("hunk {} not found in commit {}", id, commit))
}

/// Find a hunk by ID in either staged or unstaged diff.
fn find_hunk_by_id(id: &str, staged: bool) -> Result<DiffHunk> {
    let diff_output = crate::diff::run_git_diff(staged, None)?;
    let hunks = crate::diff::parse_diff(&diff_output);
    let identified = assign_ids(&hunks);

    identified
        .into_iter()
        .find(|(hunk_id, _)| hunk_id == id)
        .map(|(_, hunk)| hunk.clone())
        .ok_or_else(|| anyhow::anyhow!("hunk {} not found (re-run 'hunks')", id))
}

pub fn apply_hunks(ids: &[String], mode: ApplyMode, lines: Option<(usize, usize)>) -> Result<()> {
    if lines.is_some() && ids.len() != 1 {
        anyhow::bail!("--lines requires exactly one hunk ID");
    }

    let staged = matches!(mode, ApplyMode::Unstage);
    let diff_output = crate::diff::run_git_diff(staged, None)?;
    let hunks = crate::diff::parse_diff(&diff_output);
    let identified = assign_ids(&hunks);

    let mut combined_patch = String::new();
    for id in ids {
        let (_, hunk) = identified
            .iter()
            .find(|(hunk_id, _)| hunk_id == id)
            .ok_or_else(|| anyhow::anyhow!("hunk {} not found (re-run 'hunks')", id))?;

        crate::diff::check_supported(hunk, id)?;

        let reverse = matches!(mode, ApplyMode::Unstage | ApplyMode::Discard);
        let patched_hunk = if let Some((start, end)) = lines {
            slice_hunk(hunk, start, end, reverse)?
        } else {
            (*hunk).clone()
        };
        combined_patch.push_str(&build_patch(&patched_hunk));
        eprintln!("{}", id);
    }

    apply_patch(&combined_patch, &mode)?;
    Ok(())
}

/// Parse an ID that may contain inline range suffixes.
/// Supports: "id", "id:5", "id:1-11", "id:2,5-6,34" (comma-separated).
/// Returns (id, vector of ranges). Empty vector means "whole hunk".
fn parse_id_range(raw: &str) -> Result<(&str, Vec<(usize, usize)>)> {
    if let Some((id, range_str)) = raw.split_once(':') {
        let mut ranges = Vec::new();
        for part in range_str.split(',') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            let (start, end) = if let Some((a, b)) = part.split_once('-') {
                let start: usize = a
                    .parse()
                    .map_err(|_| anyhow::anyhow!("invalid start number in '{}'", raw))?;
                let end: usize = b
                    .parse()
                    .map_err(|_| anyhow::anyhow!("invalid end number in '{}'", raw))?;
                (start, end)
            } else {
                let n: usize = part
                    .parse()
                    .map_err(|_| anyhow::anyhow!("invalid line number in '{}'", raw))?;
                (n, n)
            };
            if start == 0 || end == 0 || start > end {
                anyhow::bail!("range must be 1-based and start <= end in '{}'", raw);
            }
            ranges.push((start, end));
        }
        Ok((id, ranges))
    } else {
        Ok((raw, Vec::new()))
    }
}

/// Check that the index has no staged changes.
fn require_clean_index() -> Result<()> {
    let status = Command::new("git")
        .args(["diff", "--cached", "--quiet"])
        .status()
        .context("failed to check staged changes")?;
    if !status.success() {
        anyhow::bail!("index already contains staged changes; commit or unstage them first");
    }
    Ok(())
}

/// A resolved hunk entry: (id, line ranges, hunk reference).
type HunkEntry<'a> = (String, Vec<(usize, usize)>, &'a DiffHunk);

/// Parsed hunk ranges ready for patch building.
struct ResolvedHunks<'a> {
    entries: Vec<HunkEntry<'a>>,
}

/// Resolve hunk IDs against the current working tree diff.
fn resolve_hunks<'a>(
    ids: &[String],
    identified: &'a [(String, &'a DiffHunk)],
) -> Result<ResolvedHunks<'a>> {
    let mut entries: Vec<HunkEntry> = Vec::new();
    for raw_id in ids {
        let (id, ranges) = parse_id_range(raw_id)?;
        if let Some(entry) = entries.iter_mut().find(|(eid, _, _)| eid == id) {
            entry.1.extend(ranges);
        } else {
            let (_, hunk) = identified
                .iter()
                .find(|(hunk_id, _)| hunk_id == id)
                .ok_or_else(|| anyhow::anyhow!("hunk {} not found (re-run 'hunks')", id))?;
            crate::diff::check_supported(hunk, id)?;
            entries.push((id.to_string(), ranges, hunk));
        }
    }
    Ok(ResolvedHunks { entries })
}

/// Build a combined patch from resolved hunks.
/// When `reverse` is true, slicing preserves context appropriate for discard/reverse-apply.
fn build_combined_patch(resolved: &ResolvedHunks, reverse: bool) -> Result<String> {
    let mut combined_patch = String::new();
    for (id, ranges, hunk) in &resolved.entries {
        let patched_hunk = if ranges.is_empty() {
            (*hunk).clone()
        } else {
            slice_hunk_multi(hunk, ranges, reverse)?
        };
        combined_patch.push_str(&build_patch(&patched_hunk));
        if !reverse {
            eprintln!("{}", id);
        }
    }
    Ok(combined_patch)
}

/// Build a combined patch from the given hunk IDs (with optional inline ranges).
/// Returns the patch string. Prints each matched hunk ID to stderr.
fn build_patch_from_ids(ids: &[String]) -> Result<String> {
    let diff_output = crate::diff::run_git_diff(false, None)?;
    let hunks = crate::diff::parse_diff(&diff_output);
    let identified = assign_ids(&hunks);
    let resolved = resolve_hunks(ids, &identified)?;
    build_combined_patch(&resolved, false)
}

/// Stage specified hunks and commit them. On commit failure, unstage to restore original state.
pub fn commit_hunks(ids: &[String], message: &str) -> Result<()> {
    require_clean_index()?;

    let combined_patch = build_patch_from_ids(ids)?;

    // Stage the hunks
    apply_patch(&combined_patch, &ApplyMode::Stage)?;

    // Commit
    let output = Command::new("git")
        .args(["commit", "-m", message])
        .output()
        .context("failed to run git commit")?;

    if !output.status.success() {
        // Unstage to restore original state
        let _ = apply_patch(&combined_patch, &ApplyMode::Unstage);
        anyhow::bail!(
            "git commit failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Commit selected working-tree hunks directly to another branch without checking it out.
pub fn commit_to_hunks(branch: &str, ids: &[String], message: &str) -> Result<()> {
    require_clean_index()?;

    // Resolve target branch and verify it exists
    let target_ref = format!("refs/heads/{}", branch);
    let target_sha =
        crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", "--verify", &target_ref]))
            .with_context(|| format!("branch '{}' not found", branch))?;
    let target_sha = target_sha.trim().to_string();

    // Reject if target is the current branch
    let current_ref = Command::new("git")
        .args(["symbolic-ref", "--quiet", "HEAD"])
        .output()
        .context("failed to check current branch")?;
    if current_ref.status.success() {
        let current = String::from_utf8_lossy(&current_ref.stdout)
            .trim()
            .to_string();
        if current == target_ref {
            anyhow::bail!(
                "target branch '{}' is currently checked out; use 'commit' instead",
                branch
            );
        }
    }

    // Build patches from selected hunks
    // We need two versions: forward (for applying to target index) and reverse-sliced (for discard)
    let diff_output = crate::diff::run_git_diff(false, None)?;
    let hunks = crate::diff::parse_diff(&diff_output);
    let identified = assign_ids(&hunks);
    let resolved = resolve_hunks(ids, &identified)?;

    let stage_patch = build_combined_patch(&resolved, false)?;
    if stage_patch.is_empty() {
        anyhow::bail!("no hunks selected");
    }
    let discard_patch = build_combined_patch(&resolved, true)?;

    // Create temp index file
    let git_dir = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", "--git-dir"]))?;
    let git_dir = git_dir.trim();
    let tmp_index =
        std::path::PathBuf::from(git_dir).join(format!("surgeon-tmp-index-{}", std::process::id()));

    // Ensure cleanup on all exit paths
    let result = commit_to_with_index(
        branch,
        &target_ref,
        &target_sha,
        &stage_patch,
        message,
        &tmp_index,
    );

    // Always clean up temp index
    let _ = std::fs::remove_file(&tmp_index);

    // If the commit succeeded, discard from working tree
    match result {
        Ok(()) => {
            apply_patch(&discard_patch, &ApplyMode::Discard).with_context(|| {
                format!(
                    "committed to {} but failed to discard local hunks; \
                     the changes are still in your working tree",
                    branch
                )
            })?;
            Ok(())
        }
        Err(e) => Err(e),
    }
}

fn commit_to_with_index(
    branch: &str,
    target_ref: &str,
    target_sha: &str,
    patch: &str,
    message: &str,
    tmp_index: &std::path::Path,
) -> Result<()> {
    use std::io::Write;
    use std::process::Stdio;

    // Read target branch tree into temp index
    let status = Command::new("git")
        .env("GIT_INDEX_FILE", tmp_index)
        .args(["read-tree", target_sha])
        .status()
        .context("failed to read target branch tree")?;
    if !status.success() {
        anyhow::bail!("git read-tree failed for {}", branch);
    }

    // Apply patch to temp index
    crate::patch::apply_patch_to_index(patch, &ApplyMode::Stage, tmp_index).with_context(|| {
        format!(
            "failed to apply patch to branch '{}'; changes may be incompatible with that branch",
            branch
        )
    })?;

    // Write tree from temp index
    let tree_sha = crate::diff::run_git_cmd(
        Command::new("git")
            .env("GIT_INDEX_FILE", tmp_index)
            .args(["write-tree"]),
    )?;
    let tree_sha = tree_sha.trim();

    // Create commit with message via stdin (-F -)
    let mut cmd = Command::new("git");
    cmd.args(["commit-tree", tree_sha, "-p", target_sha, "-F", "-"]);
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().context("failed to run git commit-tree")?;
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(message.as_bytes())?;
    let output = child.wait_with_output()?;
    if !output.status.success() {
        anyhow::bail!(
            "git commit-tree failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    let commit_sha = String::from_utf8_lossy(&output.stdout).trim().to_string();

    // Update branch ref with CAS (compare-and-swap)
    let output = Command::new("git")
        .args(["update-ref", target_ref, &commit_sha, target_sha])
        .output()
        .context("failed to update branch ref")?;
    if !output.status.success() {
        anyhow::bail!(
            "git update-ref failed (branch may have moved): {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    eprintln!(
        "committed to {}: {}",
        branch,
        &commit_sha[..7.min(commit_sha.len())]
    );
    Ok(())
}

pub fn undo_hunks(ids: &[String], commit: &str, lines: Option<(usize, usize)>) -> Result<()> {
    if lines.is_some() && ids.len() != 1 {
        anyhow::bail!("--lines requires exactly one hunk ID");
    }

    let diff_output = crate::diff::run_git_diff_commit(commit, None)?;
    let hunks = crate::diff::parse_diff(&diff_output);
    let identified = assign_ids(&hunks);

    let mut combined_patch = String::new();
    for id in ids {
        let (_, hunk) = identified
            .iter()
            .find(|(hunk_id, _)| hunk_id == id)
            .ok_or_else(|| anyhow::anyhow!("hunk {} not found in commit {}", id, commit))?;

        crate::diff::check_supported(hunk, id)?;

        let patched_hunk = if let Some((start, end)) = lines {
            slice_hunk(hunk, start, end, true)?
        } else {
            (*hunk).clone()
        };
        combined_patch.push_str(&build_patch(&patched_hunk));
        eprintln!("{}", id);
    }

    apply_patch(&combined_patch, &ApplyMode::Discard)?;
    Ok(())
}

pub fn undo_files(files: &[String], commit: &str) -> Result<()> {
    let diff_output = crate::diff::run_git_diff_commit(commit, None)?;
    let hunks = crate::diff::parse_diff(&diff_output);

    let mut combined_patch = String::new();
    let mut matched_files = HashSet::new();
    for hunk in &hunks {
        if files
            .iter()
            .any(|f| f == &hunk.file || f == &hunk.old_file || f == &hunk.new_file)
        {
            crate::diff::check_supported(hunk, &hunk.file)?;
            combined_patch.push_str(&build_patch(hunk));
            matched_files.extend(
                files
                    .iter()
                    .filter(|f| *f == &hunk.file || *f == &hunk.old_file || *f == &hunk.new_file),
            );
        }
    }

    for file in files {
        if !matched_files.contains(&file) {
            anyhow::bail!("file {} not found in commit {}", file, commit);
        }
        eprintln!("{}", file);
    }

    apply_patch(&combined_patch, &ApplyMode::Discard)?;
    Ok(())
}

fn has_staged_changes() -> Result<bool> {
    let output = Command::new("git")
        .args(["diff", "--cached", "--quiet"])
        .output()
        .context("failed to run git diff")?;

    match output.status.code() {
        Some(0) => Ok(false),
        Some(1) => Ok(true),
        _ => anyhow::bail!(
            "git diff --cached failed: {}",
            String::from_utf8_lossy(&output.stderr)
        ),
    }
}

/// Fold currently staged changes into an earlier commit via autosquash rebase.
/// If the target is HEAD, uses simple --amend instead.
pub fn amend(commit: &str) -> Result<()> {
    if !has_staged_changes()? {
        anyhow::bail!(
            "no staged changes to amend; to fold an existing commit, use `git-surgeon fold {commit}`"
        );
    }

    // Check no rebase/cherry-pick in progress
    check_no_rebase_in_progress()?;

    // Resolve the target commit SHA
    let target_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", commit]))?;
    let target_sha = target_sha.trim();

    let head_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", "HEAD"]))?;
    let head_sha = head_sha.trim();

    if target_sha == head_sha {
        // Simple case: amend HEAD
        let output = Command::new("git")
            .args(["commit", "--amend", "--no-edit"])
            .output()
            .context("failed to amend HEAD")?;
        if !output.status.success() {
            anyhow::bail!(
                "git commit --amend failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    } else {
        // Get target commit subject for fixup message
        let subject = crate::diff::run_git_cmd(Command::new("git").args([
            "log",
            "-1",
            "--format=%s",
            target_sha,
        ]))?;
        let subject = subject.trim();

        // Create fixup commit
        let output = Command::new("git")
            .args(["commit", "-m", &format!("fixup! {}", subject)])
            .output()
            .context("failed to create fixup commit")?;
        if !output.status.success() {
            anyhow::bail!(
                "git commit failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Check if target is root commit (has no parent)
        let is_root = Command::new("git")
            .args(["rev-parse", "--verify", &format!("{}^", target_sha)])
            .output()
            .map(|o| !o.status.success())
            .unwrap_or(false);

        // Non-interactive autosquash rebase
        let mut rebase_cmd = Command::new("git");
        rebase_cmd.args(["rebase", "-i", "--autosquash", "--autostash"]);
        if is_root {
            rebase_cmd.arg("--root");
        } else {
            rebase_cmd.arg(format!("{}~1", target_sha));
        }
        rebase_cmd.env("GIT_SEQUENCE_EDITOR", "true");

        let output = rebase_cmd.output().context("failed to run rebase")?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            eprintln!(
                "error: rebase conflict while fixing up {}",
                &target_sha[..7.min(target_sha.len())]
            );
            eprintln!("resolve conflicts and run: git rebase --continue");
            eprintln!("or abort with: git rebase --abort");
            anyhow::bail!("rebase failed: {}", stderr);
        }
    }

    // Print short sha + subject of the amended commit
    let info = crate::diff::run_git_cmd(Command::new("git").args([
        "log",
        "-1",
        "--format=%h %s",
        target_sha,
    ]));
    if let Ok(info) = info {
        eprintln!("amended {}", info.trim());
    }

    Ok(())
}

/// Rewrite a rebase todo file to move the source commit after the target and change it to fixup.
pub fn edit_todo(file: &str, sources: &[String], target: &str, mode: &str) -> Result<()> {
    let content = std::fs::read_to_string(file).context("failed to read todo file")?;
    let mut lines: Vec<String> = content.lines().map(String::from).collect();

    let target_short = &target[..7.min(target.len())];

    match mode {
        "fixup" => {
            // Build short SHA lookup set for all sources
            let source_shorts: Vec<&str> = sources.iter().map(|s| &s[..7.min(s.len())]).collect();

            // Extract source lines top-to-bottom (preserves chronological order)
            let mut extracted = Vec::new();
            let mut i = 0;
            while i < lines.len() {
                let trimmed = lines[i].trim().to_string();
                if !trimmed.starts_with('#')
                    && let Some(sha) = trimmed.split_whitespace().nth(1)
                {
                    let is_source = source_shorts.iter().any(|short| sha.starts_with(short))
                        || sources.iter().any(|full| full.starts_with(sha));
                    if is_source {
                        let mut line = lines.remove(i);
                        if let Some(rest) = line.strip_prefix("pick ") {
                            line = format!("fixup {}", rest);
                        }
                        extracted.push(line);
                        continue;
                    }
                }
                i += 1;
            }

            if extracted.len() != sources.len() {
                let found = extracted.len();
                anyhow::bail!(
                    "expected {} source commit(s) in todo but found {}",
                    sources.len(),
                    found
                );
            }

            // Find the target line and insert all fixup lines after it
            let target_idx = lines.iter().position(|l| {
                let l = l.trim();
                !l.starts_with('#')
                    && l.split_whitespace()
                        .nth(1)
                        .is_some_and(|sha| sha.starts_with(target_short) || target.starts_with(sha))
            });
            let target_idx = target_idx.ok_or_else(|| {
                anyhow::anyhow!("target commit {} not found in todo", target_short)
            })?;

            for (j, line) in extracted.into_iter().enumerate() {
                lines.insert(target_idx + 1 + j, line);
            }
        }
        "move" | "move-before" => {
            if sources.len() != 1 {
                anyhow::bail!("move mode requires exactly one source commit");
            }
            let source = &sources[0];
            let source_short = &source[..7.min(source.len())];

            // Find and remove the source line
            let source_idx = lines.iter().position(|l| {
                let l = l.trim();
                !l.starts_with('#')
                    && l.split_whitespace()
                        .nth(1)
                        .is_some_and(|sha| sha.starts_with(source_short) || source.starts_with(sha))
            });
            let source_idx = source_idx.ok_or_else(|| {
                anyhow::anyhow!("source commit {} not found in todo", source_short)
            })?;
            let source_line = lines.remove(source_idx);

            // Find the target line
            let target_idx = lines.iter().position(|l| {
                let l = l.trim();
                !l.starts_with('#')
                    && l.split_whitespace()
                        .nth(1)
                        .is_some_and(|sha| sha.starts_with(target_short) || target.starts_with(sha))
            });
            let target_idx = target_idx.ok_or_else(|| {
                anyhow::anyhow!("target commit {} not found in todo", target_short)
            })?;

            if mode == "move-before" {
                lines.insert(target_idx, source_line);
            } else {
                lines.insert(target_idx + 1, source_line);
            }
        }
        _ => anyhow::bail!("unknown edit-todo mode: {}", mode),
    }

    std::fs::write(file, lines.join("\n") + "\n").context("failed to write todo file")?;
    Ok(())
}

/// Move a commit to a different position in history.
pub fn move_commit(
    commit: &str,
    after: Option<&str>,
    before: Option<&str>,
    to_end: bool,
) -> Result<()> {
    check_no_rebase_in_progress()?;

    let source_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", commit]))?;
    let source_sha = source_sha.trim().to_string();

    let head_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", "HEAD"]))?;
    let head_sha = head_sha.trim().to_string();

    if source_sha == head_sha && to_end {
        // Already at end, nothing to do
        eprintln!("commit is already at HEAD");
        return Ok(());
    }

    // Determine target SHA and insertion mode
    let (target_sha, insert_after) = if to_end {
        (head_sha.clone(), true)
    } else if let Some(after_ref) = after {
        let sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", after_ref]))?;
        (sha.trim().to_string(), true)
    } else if let Some(before_ref) = before {
        let sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", before_ref]))?;
        (sha.trim().to_string(), false)
    } else {
        anyhow::bail!("one of --after, --before, or --to-end is required");
    };

    if source_sha == target_sha {
        anyhow::bail!("source and target are the same commit");
    }

    // Both commits must be ancestors of HEAD (i.e. in the current branch)
    for (label, sha) in [("source", &source_sha), ("target", &target_sha)] {
        let is_ancestor = Command::new("git")
            .args(["merge-base", "--is-ancestor", sha, &head_sha])
            .status()
            .context("failed to check ancestry")?;
        if !is_ancestor.success() {
            anyhow::bail!(
                "{} commit {} is not in the current branch",
                label,
                &sha[..7.min(sha.len())]
            );
        }
    }

    // Find the oldest commit involved to determine rebase range
    let oldest_sha = {
        let is_source_ancestor = Command::new("git")
            .args(["merge-base", "--is-ancestor", &source_sha, &target_sha])
            .status()
            .context("failed to check ancestry")?;
        if is_source_ancestor.success() {
            source_sha.clone()
        } else {
            target_sha.clone()
        }
    };

    // Check if oldest commit is root
    let is_root = Command::new("git")
        .args(["rev-parse", "--verify", &format!("{}^", oldest_sha)])
        .output()
        .map(|o| !o.status.success())
        .unwrap_or(false);

    // Check for merge commits in range
    let merges_range = if is_root {
        head_sha.clone()
    } else {
        format!("{}~1..{}", oldest_sha, head_sha)
    };
    let merges = Command::new("git")
        .args(["rev-list", "--merges", &merges_range])
        .output()
        .context("failed to check for merge commits")?;
    if !merges.status.success() {
        anyhow::bail!(
            "failed to check for merge commits: {}",
            String::from_utf8_lossy(&merges.stderr)
        );
    }
    if !String::from_utf8_lossy(&merges.stdout).trim().is_empty() {
        anyhow::bail!("range contains merge commits; move cannot proceed");
    }

    let (editor_target, editor_mode) = if insert_after {
        (target_sha.clone(), "move")
    } else {
        // For --before: we still use "move" mode but insert before target.
        // We need a special mode for this.
        (target_sha.clone(), "move-before")
    };

    let exe = std::env::current_exe().context("failed to get current executable path")?;

    let editor = format!(
        "{} _edit-todo --source {} --target {} --mode {}",
        exe.display(),
        source_sha,
        editor_target,
        editor_mode
    );

    let mut rebase_cmd = Command::new("git");
    rebase_cmd.args(["rebase", "-i", "--autostash"]);
    if is_root {
        rebase_cmd.arg("--root");
    } else {
        rebase_cmd.arg(format!("{}~1", oldest_sha));
    }
    rebase_cmd.env("GIT_SEQUENCE_EDITOR", &editor);

    let output = rebase_cmd.output().context("failed to run rebase")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!(
            "error: rebase conflict while moving {}",
            &source_sha[..7.min(source_sha.len())]
        );
        eprintln!("resolve conflicts and run: git rebase --continue");
        eprintln!("or abort with: git rebase --abort");
        anyhow::bail!("rebase failed: {}", stderr);
    }

    // Show the new commit order
    let mut log_cmd = Command::new("git");
    log_cmd.args(["log", "--oneline", "--reverse"]);
    if is_root {
        log_cmd.arg("HEAD");
    } else {
        log_cmd.arg(format!("{}~1..HEAD", oldest_sha));
    }
    if let Ok(log) = crate::diff::run_git_cmd(&mut log_cmd) {
        eprintln!("moved commit, new order:");
        for line in log.trim().lines() {
            eprintln!("  {}", line);
        }
    }

    Ok(())
}

/// Fold one or more commits into an earlier commit.
/// If sources is empty, defaults to HEAD.
pub fn fold(target: &str, sources: &[String]) -> Result<()> {
    check_no_rebase_in_progress()?;

    if has_staged_changes()? {
        anyhow::bail!(
            "index has staged changes; `fold` folds existing commits, not staged changes. Use `git-surgeon amend {target}` to fold staged changes."
        );
    }

    // Resolve target SHA
    let target_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", target]))?;
    let target_sha = target_sha.trim().to_string();

    let head_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", "HEAD"]))?;
    let head_sha = head_sha.trim().to_string();

    // Resolve source SHAs (default to HEAD if none given)
    let source_shas: Vec<String> = if sources.is_empty() {
        vec![head_sha.clone()]
    } else {
        let mut shas = Vec::new();
        for s in sources {
            let sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", s]))?;
            let sha = sha.trim().to_string();
            // Silent dedup
            if !shas.contains(&sha) {
                shas.push(sha);
            }
        }
        shas
    };

    // Validate: no source is the same as target
    for sha in &source_shas {
        if *sha == target_sha {
            anyhow::bail!("target and source are the same commit");
        }
    }

    // Verify target is ancestor of each source
    for sha in &source_shas {
        let is_ancestor = Command::new("git")
            .args(["merge-base", "--is-ancestor", &target_sha, sha])
            .status()
            .context("failed to check ancestry")?;
        if !is_ancestor.success() {
            anyhow::bail!(
                "commit {} is not an ancestor of {}",
                &target_sha[..7.min(target_sha.len())],
                &sha[..7.min(sha.len())]
            );
        }
    }

    // Verify all non-HEAD sources are ancestors of HEAD
    for sha in &source_shas {
        if *sha != head_sha {
            let is_ancestor = Command::new("git")
                .args(["merge-base", "--is-ancestor", sha, &head_sha])
                .status()
                .context("failed to check ancestry")?;
            if !is_ancestor.success() {
                anyhow::bail!(
                    "source commit {} is not an ancestor of HEAD",
                    &sha[..7.min(sha.len())]
                );
            }
        }
    }

    // Check for merge commits in the rebase range (target..HEAD)
    let merges = Command::new("git")
        .args(["rev-list", "--merges", &format!("{}..HEAD", target_sha)])
        .output()
        .context("failed to check for merge commits")?;
    if !String::from_utf8_lossy(&merges.stdout).trim().is_empty() {
        anyhow::bail!("range contains merge commits; fold cannot proceed");
    }

    // Fast path: single source that is HEAD
    if source_shas.len() == 1 && source_shas[0] == head_sha {
        let output = Command::new("git")
            .args(["reset", "--soft", "HEAD~1"])
            .output()
            .context("failed to reset HEAD")?;
        if !output.status.success() {
            anyhow::bail!(
                "git reset failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
        // Now staged changes contain the source commit's diff -- delegate to amend
        amend(&target_sha)?;
    } else {
        // Rebase path: use custom todo editor to mark all sources as fixup
        let exe = std::env::current_exe().context("failed to get current executable path")?;

        // Check if target is root commit
        let is_root = Command::new("git")
            .args(["rev-parse", "--verify", &format!("{}^", target_sha)])
            .output()
            .map(|o| !o.status.success())
            .unwrap_or(false);

        // Build editor command with repeated --source flags
        let source_args: String = source_shas
            .iter()
            .map(|s| format!(" --source {}", s))
            .collect();
        let editor = format!(
            "{} _edit-todo{} --target {}",
            exe.display(),
            source_args,
            target_sha
        );

        let mut rebase_cmd = Command::new("git");
        rebase_cmd.args(["rebase", "-i", "--autostash"]);
        if is_root {
            rebase_cmd.arg("--root");
        } else {
            rebase_cmd.arg(format!("{}~1", target_sha));
        }
        rebase_cmd.env("GIT_SEQUENCE_EDITOR", &editor);

        let output = rebase_cmd.output().context("failed to run rebase")?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            eprintln!(
                "error: rebase conflict while folding into {}",
                &target_sha[..7.min(target_sha.len())]
            );
            eprintln!("resolve conflicts and run: git rebase --continue");
            eprintln!("or abort with: git rebase --abort");
            anyhow::bail!("rebase failed: {}", stderr);
        }

        // Print result
        let distance = crate::diff::run_git_cmd(Command::new("git").args([
            "rev-list",
            "--count",
            &format!("{}..HEAD", target_sha),
        ]));
        // Use distance to find the rebased target commit
        if let Ok(d) = distance {
            let d: usize = d.trim().parse().unwrap_or(0);
            let ref_spec = if d == 0 {
                "HEAD".to_string()
            } else {
                format!("HEAD~{}", d)
            };
            let info = crate::diff::run_git_cmd(Command::new("git").args([
                "log",
                "-1",
                "--format=%h %s",
                &ref_spec,
            ]));
            if let Ok(info) = info {
                eprintln!("folded {}", info.trim());
            }
        }
    }

    Ok(())
}

/// Change the commit message of an existing commit.
pub fn reword(commit: &str, message: &str) -> Result<()> {
    // Check no rebase/cherry-pick in progress
    check_no_rebase_in_progress()?;

    // Resolve the target commit SHA
    let target_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", commit]))?;
    let target_sha = target_sha.trim();

    let head_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", "HEAD"]))?;
    let head_sha = head_sha.trim();

    // Track distance from target to HEAD for later (used to find new SHA after rebase)
    let distance = crate::diff::run_git_cmd(Command::new("git").args([
        "rev-list",
        "--count",
        &format!("{}..HEAD", target_sha),
    ]))?;
    let distance: usize = distance.trim().parse().unwrap_or(0);

    if target_sha == head_sha {
        // Simple case: amend HEAD with new message
        let output = Command::new("git")
            .args(["commit", "--amend", "-m", message])
            .output()
            .context("failed to amend HEAD")?;
        if !output.status.success() {
            anyhow::bail!(
                "git commit --amend failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    } else {
        // Get original commit subject for reword marker
        let subject = crate::diff::run_git_cmd(Command::new("git").args([
            "log",
            "-1",
            "--format=%s",
            target_sha,
        ]))?;
        let subject = subject.trim();

        // Create empty reword commit with new message
        let output = Command::new("git")
            .args([
                "commit",
                "--allow-empty",
                "-m",
                &format!("amend! {}\n\n{}", subject, message),
            ])
            .output()
            .context("failed to create reword commit")?;
        if !output.status.success() {
            anyhow::bail!(
                "git commit failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Check if target is root commit (has no parent)
        let is_root = Command::new("git")
            .args(["rev-parse", "--verify", &format!("{}^", target_sha)])
            .output()
            .map(|o| !o.status.success())
            .unwrap_or(false);

        // Non-interactive autosquash rebase
        let mut rebase_cmd = Command::new("git");
        rebase_cmd.args(["rebase", "-i", "--autosquash", "--autostash"]);
        if is_root {
            rebase_cmd.arg("--root");
        } else {
            rebase_cmd.arg(format!("{}~1", target_sha));
        }
        rebase_cmd.env("GIT_SEQUENCE_EDITOR", "true");

        let output = rebase_cmd.output().context("failed to run rebase")?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            eprintln!(
                "error: rebase conflict while rewording {}",
                &target_sha[..7.min(target_sha.len())]
            );
            eprintln!("resolve conflicts and run: git rebase --continue");
            eprintln!("or abort with: git rebase --abort");
            anyhow::bail!("rebase failed: {}", stderr);
        }
    }

    // Print short sha + new subject of the reworded commit
    // Use HEAD~distance to find the commit at the same position after rebase
    let ref_spec = if distance == 0 {
        "HEAD".to_string()
    } else {
        format!("HEAD~{}", distance)
    };
    let info = crate::diff::run_git_cmd(Command::new("git").args([
        "log",
        "-1",
        "--format=%h %s",
        &ref_spec,
    ]));
    if let Ok(info) = info {
        eprintln!("reworded {}", info.trim());
    }

    Ok(())
}

/// Split a commit into multiple commits by hunk selection.
pub fn split(
    commit: &str,
    pick_groups: &[crate::PickGroup],
    rest_message: Option<&[String]>,
) -> Result<()> {
    // Check working tree is clean
    let status = Command::new("git")
        .args(["status", "--porcelain"])
        .output()
        .context("failed to check git status")?;
    if !String::from_utf8_lossy(&status.stdout).trim().is_empty() {
        anyhow::bail!("working tree is dirty; commit or stash changes before splitting");
    }

    check_no_rebase_in_progress()?;

    // Resolve target commit
    let target_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", commit]))?;
    let target_sha = target_sha.trim().to_string();

    let head_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", "HEAD"]))?;
    let head_sha = head_sha.trim().to_string();

    let is_head = target_sha == head_sha;

    // Get hunks from the target commit and validate all pick IDs exist
    let diff_output = crate::diff::run_git_diff_commit(&target_sha, None)?;
    let hunks = crate::diff::parse_diff(&diff_output);
    let identified = assign_ids(&hunks);

    // Validate all referenced IDs exist and are supported
    for group in pick_groups {
        for (id, _) in &group.ids {
            let (_, hunk) = identified
                .iter()
                .find(|(hid, _)| hid == id)
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "hunk {} not found in commit {}",
                        id,
                        &target_sha[..7.min(target_sha.len())]
                    )
                })?;
            crate::diff::check_supported(hunk, id)?;
        }
    }

    // Get original commit message for rest-message default
    let original_message = crate::diff::run_git_cmd(Command::new("git").args([
        "log",
        "-1",
        "--format=%B",
        &target_sha,
    ]))?;
    let original_message = original_message.trim();
    let rest_msg_joined;
    let rest_msg = match rest_message {
        Some(parts) => {
            rest_msg_joined = parts.join("\n\n");
            rest_msg_joined.as_str()
        }
        None => original_message,
    };

    // Build stateful hunk tracking: original hunks with picked state
    // This keeps line ranges stable (always relative to original commit)
    struct HunkState {
        hunk: DiffHunk,
        picked: Vec<bool>, // which lines have been picked in previous groups
    }

    let mut hunk_states: HashMap<String, HunkState> = identified
        .iter()
        .map(|(id, hunk)| {
            (
                id.clone(),
                HunkState {
                    hunk: (*hunk).clone(),
                    picked: vec![false; hunk.lines.len()],
                },
            )
        })
        .collect();

    // Pre-validate all line ranges before modifying git state
    for group in pick_groups {
        // Group line ranges by hunk ID
        let mut hunk_ranges: HashMap<String, Vec<(usize, usize)>> = HashMap::new();
        for (id, lines_range) in &group.ids {
            if let Some(range) = lines_range {
                hunk_ranges.entry(id.clone()).or_default().push(*range);
            }
        }

        for (id, ranges) in &hunk_ranges {
            let state = hunk_states
                .get(id)
                .ok_or_else(|| anyhow::anyhow!("hunk {} not found", id))?;

            for (start, end) in ranges {
                if *start == 0 || *end == 0 {
                    anyhow::bail!("line ranges are 1-based, got {}:{}-{}", id, start, end);
                }
                if *end > state.hunk.lines.len() {
                    anyhow::bail!(
                        "line range {}:{}-{} exceeds hunk length ({})",
                        id,
                        start,
                        end,
                        state.hunk.lines.len()
                    );
                }
            }
        }
    }

    if !is_head {
        start_rebase_at_commit(&target_sha)?;
    } else {
        // HEAD: just reset
        let output = Command::new("git")
            .args(["reset", "HEAD~"])
            .output()
            .context("failed to reset HEAD")?;
        if !output.status.success() {
            anyhow::bail!(
                "git reset failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    // Now changes are in the working tree. Stage and commit each pick group
    // using the stateful approach (line ranges always relative to original commit).

    for group in pick_groups {
        let mut combined_patch = String::new();

        // Group line ranges by hunk ID so same-hunk entries produce one patch
        let mut hunk_ranges: Vec<(String, Vec<(usize, usize)>)> = Vec::new();
        for (id, lines_range) in &group.ids {
            if let Some(entry) = hunk_ranges.iter_mut().find(|(eid, _)| eid == id) {
                if let Some(range) = lines_range {
                    entry.1.push(*range);
                }
            } else {
                let ranges = match lines_range {
                    Some(range) => vec![*range],
                    None => vec![],
                };
                hunk_ranges.push((id.clone(), ranges));
            }
        }

        for (id, ranges) in &hunk_ranges {
            let state = hunk_states
                .get_mut(id)
                .ok_or_else(|| anyhow::anyhow!("hunk {} not found", id))?;

            // Build selection mask for this group
            let mut selected = vec![false; state.hunk.lines.len()];

            if ranges.is_empty() {
                // No line ranges: select all remaining change lines
                for (i, line) in state.hunk.lines.iter().enumerate() {
                    if (line.starts_with('+') || line.starts_with('-')) && !state.picked[i] {
                        selected[i] = true;
                    }
                }
            } else {
                // Select lines in specified ranges
                for (start, end) in ranges {
                    #[allow(clippy::needless_range_loop)]
                    for i in (*start - 1)..*end {
                        if i < state.hunk.lines.len() {
                            let line = &state.hunk.lines[i];
                            // Only select change lines, not context
                            if line.starts_with('+') || line.starts_with('-') {
                                if state.picked[i] {
                                    anyhow::bail!(
                                        "line {} in hunk {} was already picked in a previous group",
                                        i + 1,
                                        id
                                    );
                                }
                                selected[i] = true;
                            }
                        }
                    }
                }
            }

            // Check we're actually selecting something
            let has_changes = selected.iter().any(|&s| s);
            if !has_changes {
                // Skip this hunk if nothing to select
                continue;
            }

            // Build patch using stateful slicing
            let patched_hunk = slice_hunk_with_state(&state.hunk, &state.picked, &selected)?;
            combined_patch.push_str(&build_patch(&patched_hunk));

            // Mark selected lines as picked for next groups
            for (i, sel) in selected.iter().enumerate() {
                if *sel {
                    state.picked[i] = true;
                }
            }
        }

        if combined_patch.is_empty() {
            anyhow::bail!("no changes selected for commit");
        }

        apply_patch(&combined_patch, &ApplyMode::Stage)?;

        // Commit
        let message = group.message_parts.join("\n\n");
        let output = Command::new("git")
            .args(["commit", "-m", &message])
            .output()
            .context("failed to commit")?;
        if !output.status.success() {
            anyhow::bail!(
                "git commit failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Print only the subject line
        let subject = message.lines().next().unwrap_or(&message);
        eprintln!("committed: {}", subject);
    }

    // Stage and commit remaining changes (if any)
    // Build patches for all unpicked change lines
    let mut has_remaining = false;
    let mut combined_patch = String::new();

    for (id, state) in &hunk_states {
        // Check if any change lines remain unpicked
        let mut remaining_selected = vec![false; state.hunk.lines.len()];
        for (i, line) in state.hunk.lines.iter().enumerate() {
            if (line.starts_with('+') || line.starts_with('-')) && !state.picked[i] {
                remaining_selected[i] = true;
                has_remaining = true;
            }
        }

        if remaining_selected.iter().any(|&s| s) {
            let patched_hunk =
                slice_hunk_with_state(&state.hunk, &state.picked, &remaining_selected)?;
            combined_patch.push_str(&build_patch(&patched_hunk));

            // Mark as picked (for consistency, though we're done)
            for (i, sel) in remaining_selected.iter().enumerate() {
                if *sel {
                    // We'd update state.picked here but we're borrowing immutably
                    let _ = (id, sel, i); // suppress unused warnings
                }
            }
        }
    }

    if has_remaining {
        apply_patch(&combined_patch, &ApplyMode::Stage)?;

        let output = Command::new("git")
            .args(["commit", "-m", rest_msg])
            .output()
            .context("failed to commit remaining")?;
        if !output.status.success() {
            anyhow::bail!(
                "git commit failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Print only the subject line
        let subject = rest_msg.lines().next().unwrap_or(rest_msg);
        eprintln!("committed: {}", subject);
    }

    // Continue rebase if non-HEAD
    if !is_head {
        let output = Command::new("git")
            .args(["rebase", "--continue"])
            .output()
            .context("failed to continue rebase")?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            eprintln!("error: rebase continue failed");
            eprintln!("resolve conflicts and run: git rebase --continue");
            eprintln!("or abort with: git rebase --abort");
            anyhow::bail!("rebase continue failed: {}", stderr);
        }
    }

    Ok(())
}

fn check_no_rebase_in_progress() -> Result<()> {
    for dir_name in ["rebase-merge", "rebase-apply"] {
        let check = Command::new("git")
            .args(["rev-parse", "--git-path", dir_name])
            .output()
            .context("failed to check rebase state")?;
        let dir = String::from_utf8_lossy(&check.stdout).trim().to_string();
        if std::path::Path::new(&dir).exists() {
            anyhow::bail!("rebase already in progress");
        }
    }
    Ok(())
}

/// Squash commits from <commit>..HEAD into a single commit.
pub fn squash(commit: &str, message: &str, force: bool, preserve_author: bool) -> Result<()> {
    check_no_rebase_in_progress()?;

    // Autostash if working tree is dirty (tracked files only)
    let status = Command::new("git")
        .args(["status", "--porcelain", "--untracked-files=no"])
        .output()
        .context("failed to check git status")?;
    let needs_stash = !String::from_utf8_lossy(&status.stdout).trim().is_empty();

    if needs_stash {
        let output = Command::new("git")
            .args(["stash", "push", "-m", "git-surgeon squash autostash"])
            .output()
            .context("failed to stash changes")?;
        if !output.status.success() {
            anyhow::bail!(
                "git stash failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    // Resolve target commit SHA
    let target_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", commit]))
        .with_context(|| format!("could not resolve commit '{}'", commit))?;
    let target_sha = target_sha.trim();

    let head_sha = crate::diff::run_git_cmd(Command::new("git").args(["rev-parse", "HEAD"]))?;
    let head_sha = head_sha.trim();

    if target_sha == head_sha {
        anyhow::bail!("nothing to squash: target commit is HEAD");
    }

    // Extract author and date from target commit if preserving
    let (author, author_date) = if preserve_author {
        let ident = crate::diff::run_git_cmd(Command::new("git").args([
            "log",
            "-1",
            "--format=%an <%ae>",
            target_sha,
        ]))?
        .trim()
        .to_string();

        let date = crate::diff::run_git_cmd(Command::new("git").args([
            "log",
            "-1",
            "--format=%aI", // ISO 8601 format for unambiguous parsing
            target_sha,
        ]))?
        .trim()
        .to_string();

        (Some(ident), Some(date))
    } else {
        (None, None)
    };

    // Verify target is ancestor of HEAD
    let is_ancestor = Command::new("git")
        .args(["merge-base", "--is-ancestor", target_sha, "HEAD"])
        .status()
        .context("failed to check ancestry")?;
    if !is_ancestor.success() {
        anyhow::bail!(
            "commit {} is not an ancestor of HEAD",
            &target_sha[..7.min(target_sha.len())]
        );
    }

    // Check for merge commits in range (they will be flattened)
    if !force {
        let merges = Command::new("git")
            .args(["rev-list", "--merges", &format!("{}..HEAD", target_sha)])
            .output()
            .context("failed to check for merge commits")?;
        if !String::from_utf8_lossy(&merges.stdout).trim().is_empty() {
            anyhow::bail!(
                "range contains merge commits which will be flattened; use --force to proceed"
            );
        }
    }

    // Check if target is root commit
    let is_root = Command::new("git")
        .args(["rev-parse", "--verify", &format!("{}^", target_sha)])
        .output()
        .map(|o| !o.status.success())
        .unwrap_or(false);

    if is_root {
        // For root commit: delete HEAD ref to create orphan state, then commit
        // This preserves hooks and GPG signing (unlike commit-tree)
        let output = Command::new("git")
            .args(["update-ref", "-d", "HEAD"])
            .output()
            .context("failed to delete HEAD ref")?;
        if !output.status.success() {
            anyhow::bail!(
                "git update-ref failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Commit (git treats this as the first commit)
        let mut commit_cmd = Command::new("git");
        commit_cmd.args(["commit", "-m", message]);
        if let Some(ref auth) = author {
            commit_cmd.args(["--author", auth]);
        }
        if let Some(ref date) = author_date {
            commit_cmd.args(["--date", date]);
        }
        let output = commit_cmd.output().context("failed to commit")?;
        if !output.status.success() {
            anyhow::bail!(
                "git commit failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    } else {
        // Normal case: reset to parent of target
        let output = Command::new("git")
            .args(["reset", "--soft", &format!("{}^", target_sha)])
            .output()
            .context("failed to reset")?;
        if !output.status.success() {
            anyhow::bail!(
                "git reset failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Commit with new message
        let mut commit_cmd = Command::new("git");
        commit_cmd.args(["commit", "-m", message]);
        if let Some(ref auth) = author {
            commit_cmd.args(["--author", auth]);
        }
        if let Some(ref date) = author_date {
            commit_cmd.args(["--date", date]);
        }
        let output = commit_cmd.output().context("failed to commit")?;
        if !output.status.success() {
            anyhow::bail!(
                "git commit failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    // Count how many commits were squashed
    let count = crate::diff::run_git_cmd(Command::new("git").args([
        "rev-list",
        "--count",
        &format!("{}..{}", target_sha, head_sha),
    ]))?;
    let count: i32 = count.trim().parse().unwrap_or(0);

    eprintln!("squashed {} commits", count + 1);

    // Restore stashed changes
    if needs_stash {
        let output = Command::new("git")
            .args(["stash", "pop"])
            .output()
            .context("failed to pop stash")?;
        if !output.status.success() {
            eprintln!(
                "warning: stash pop failed (conflicts?), run 'git stash pop' manually: {}",
                String::from_utf8_lossy(&output.stderr).trim()
            );
        }
    }

    Ok(())
}

fn start_rebase_at_commit(target_sha: &str) -> Result<()> {
    let is_root = Command::new("git")
        .args(["rev-parse", "--verify", &format!("{}^", target_sha)])
        .output()
        .map(|o| !o.status.success())
        .unwrap_or(false);

    // We need a custom sequence editor that marks the target commit as "edit"
    let short_sha = &target_sha[..7.min(target_sha.len())];
    // Use sed to change "pick <sha>" to "edit <sha>" for the target commit
    let sed_script = format!("s/^pick {} /edit {} /", short_sha, short_sha);

    let mut rebase_cmd = Command::new("git");
    rebase_cmd.args(["rebase", "-i", "--autostash"]);
    if is_root {
        rebase_cmd.arg("--root");
    } else {
        rebase_cmd.arg(format!("{}~1", target_sha));
    }
    rebase_cmd.env(
        "GIT_SEQUENCE_EDITOR",
        format!("sed -i.bak '{}'", sed_script),
    );

    let output = rebase_cmd.output().context("failed to start rebase")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("rebase failed: {}", stderr);
    }

    // Now we should be paused at the target commit. Reset it.
    let output = Command::new("git")
        .args(["reset", "HEAD~"])
        .output()
        .context("failed to reset commit")?;
    if !output.status.success() {
        anyhow::bail!(
            "git reset failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}