stax 0.89.0

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

use crate::commands::staging::{self, ContinueLabel, StagingAction};
use crate::config::Config;
use crate::engine::{BranchMetadata, Stack};
use crate::git::GitRepo;
use crate::progress::LiveTimer;
use crate::remote;
use anyhow::{Context, Result, bail};
use colored::Colorize;
use console::Term;
use dialoguer::{Input, Select, theme::ColorfulTheme};
use serde::Deserialize;
use std::io::IsTerminal;
use std::io::Write;
use std::path::Path;
use std::process::{Command, ExitStatus, Output, Stdio};
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StageMode {
    /// No staging (plain `stax create <name>` or wizard empty-branch choice).
    None,
    /// `-m` was passed without `-a`: prompt if nothing is staged, otherwise
    /// commit what's already in the index.
    ExistingOnly,
    /// `-a/--all` was passed: force-stage everything.
    All,
}

struct CreatePlacement {
    parent_branch: String,
    below_current_meta: Option<BranchMetadata>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct AiCreateTargets {
    branch: bool,
    message: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct AiCreateDetails {
    branch: Option<String>,
    message: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RawAiCreateDetails {
    branch: Option<String>,
    branch_name: Option<String>,
    message: Option<String>,
    commit_message: Option<String>,
}

const MAX_AI_CREATE_DIFF_BYTES: usize = 80_000;

fn resolve_ai_create_targets(
    ai: bool,
    name: Option<&str>,
    message: Option<&str>,
    all: bool,
    has_staged_changes: bool,
    has_uncommitted_changes: bool,
    can_prompt_for_staging: bool,
) -> Result<Option<AiCreateTargets>> {
    if !ai {
        return Ok(None);
    }

    let targets = AiCreateTargets {
        branch: name.is_none(),
        message: message.is_none()
            && (all || has_staged_changes || (has_uncommitted_changes && can_prompt_for_staging)),
    };

    Ok((targets.branch || targets.message).then_some(targets))
}

fn generate_ai_create_details(
    workdir: &Path,
    config: &mut Config,
    targets: AiCreateTargets,
    stage_all: bool,
    non_interactive: bool,
) -> Result<AiCreateDetails> {
    use crate::commands::generate;

    let (agent, model) = if non_interactive {
        let agent = generate::resolve_agent_non_interactive(None, config, "generate")?;
        let model = generate::resolve_model(None, config, &agent, "generate")?;
        (agent, model)
    } else if config.ai.generate.agent.is_some() {
        let agent = config
            .ai
            .agent_for("generate")
            .context("No AI agent configured for create generation")?
            .to_string();
        let model = generate::resolve_model(None, config, &agent, "generate")?;
        (agent, model)
    } else {
        generate::prompt_for_feature_ai(config, "generate")?
    };

    generate::print_using_agent(&agent, model.as_deref());

    let context_timer = LiveTimer::maybe_new(true, "Collecting branch context...");
    let status = git_stdout(workdir, &["status", "--short", "--untracked-files=all"]);
    let staged_diff = git_stdout(workdir, &["diff", "--cached"]);
    let unstaged_diff = git_stdout(workdir, &["diff"]);
    LiveTimer::maybe_finish_ok(context_timer, "done");

    let prompt =
        build_ai_create_details_prompt(&status, &staged_diff, &unstaged_diff, targets, stage_all);

    let generation_timer = LiveTimer::maybe_new(true, "Generating AI create details...");
    let raw = match generate::invoke_ai_agent(&agent, model.as_deref(), &prompt) {
        Ok(raw) => raw,
        Err(err) => {
            LiveTimer::maybe_finish_warn(generation_timer, "failed");
            return Err(err);
        }
    };

    match parse_ai_create_details(&raw, targets) {
        Ok(details) => {
            LiveTimer::maybe_finish_ok(generation_timer, "done");
            Ok(details)
        }
        Err(err) => {
            LiveTimer::maybe_finish_warn(generation_timer, "failed");
            Err(err)
        }
    }
}

fn resolve_ai_create_details_for_use(
    mut details: AiCreateDetails,
    targets: AiCreateTargets,
    auto_accept: bool,
) -> Result<AiCreateDetails> {
    if auto_accept {
        return Ok(details);
    }

    if targets.branch {
        let suggested = details
            .branch
            .clone()
            .context("AI agent did not return a branch")?;
        let branch: String = Input::with_theme(&ColorfulTheme::default())
            .with_prompt("Branch name")
            .default(suggested)
            .interact_text()?;
        details.branch = Some(require_non_empty(branch, "branch")?);
    }

    if targets.message {
        let suggested = details
            .message
            .clone()
            .context("AI agent did not return a commit message")?;
        let message: String = Input::with_theme(&ColorfulTheme::default())
            .with_prompt("Commit message")
            .default(suggested)
            .interact_text()?;
        details.message = Some(require_non_empty(message, "commit message")?);
    }

    Ok(details)
}

fn parse_ai_create_details(raw: &str, targets: AiCreateTargets) -> Result<AiCreateDetails> {
    let json = extract_ai_json(raw);
    let parsed: RawAiCreateDetails = serde_json::from_str(&json)
        .context("AI agent did not return JSON create details with branch/message fields")?;

    let branch = parsed
        .branch
        .or(parsed.branch_name)
        .and_then(non_empty_trimmed);
    let message = parsed
        .message
        .or(parsed.commit_message)
        .and_then(non_empty_trimmed);

    if targets.branch && branch.is_none() {
        bail!("AI agent did not return a non-empty branch");
    }
    if targets.message && message.is_none() {
        bail!("AI agent did not return a non-empty commit message");
    }

    Ok(AiCreateDetails {
        branch: targets.branch.then_some(branch).flatten(),
        message: targets.message.then_some(message).flatten(),
    })
}

fn build_ai_create_details_prompt(
    status: &str,
    staged_diff: &str,
    unstaged_diff: &str,
    targets: AiCreateTargets,
    stage_all: bool,
) -> String {
    let mut prompt = String::new();

    match (targets.branch, targets.message) {
        (true, true) => prompt
            .push_str("Generate a branch name and first commit message for these changes.\n\n"),
        (true, false) => prompt.push_str("Generate a branch name for these changes.\n\n"),
        (false, true) => prompt.push_str("Generate a first commit message for these changes.\n\n"),
        (false, false) => prompt.push_str("Summarize these changes.\n\n"),
    }

    prompt.push_str("Return only a compact JSON object with these string fields: ");
    match (targets.branch, targets.message) {
        (true, true) => prompt.push_str("\"branch\" and \"message\""),
        (true, false) => prompt.push_str("\"branch\""),
        (false, true) => prompt.push_str("\"message\""),
        (false, false) => prompt.push_str(""),
    }
    prompt.push_str(". Do not include markdown fences or explanatory text.\n\n");

    if targets.branch {
        prompt.push_str(
            "Branch requirements:\n- Short lowercase slug suitable for a Git branch\n- No spaces\n- No prefix like feature/ unless the change clearly needs a nested branch name\n\n",
        );
    }

    if targets.message {
        prompt.push_str(
            "Commit message requirements:\n- Imperative mood\n- Concise subject line\n- No trailing period\n\n",
        );
    }

    if stage_all {
        prompt.push_str("The command will stage all changes before committing.\n\n");
    } else {
        prompt.push_str(
            "Only already-staged changes are guaranteed to be committed; unstaged changes may be used for naming context.\n\n",
        );
    }

    if !status.is_empty() {
        prompt.push_str("Git status:\n```\n");
        prompt.push_str(status);
        prompt.push_str("\n```\n\n");
    }

    if !staged_diff.is_empty() {
        prompt.push_str("Staged diff:\n```diff\n");
        prompt.push_str(&truncate_ai_create_diff(staged_diff));
        prompt.push_str("\n```\n\n");
    }

    if !unstaged_diff.is_empty() {
        prompt.push_str("Unstaged diff:\n```diff\n");
        prompt.push_str(&truncate_ai_create_diff(unstaged_diff));
        prompt.push_str("\n```\n\n");
    }

    prompt
}

fn git_stdout(workdir: &Path, args: &[&str]) -> String {
    Command::new("git")
        .args(args)
        .current_dir(workdir)
        .output()
        .ok()
        .filter(|output| output.status.success())
        .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
        .unwrap_or_default()
}

fn truncate_ai_create_diff(diff: &str) -> String {
    if diff.len() <= MAX_AI_CREATE_DIFF_BYTES {
        return diff.to_string();
    }

    let safe_end = safe_char_boundary(diff, MAX_AI_CREATE_DIFF_BYTES);
    let safe = &diff[..safe_end];
    let cut = safe.rfind('\n').unwrap_or(safe.len());
    format!(
        "{}\n\n... (diff truncated, showing first ~80KB of {} total) ...",
        &safe[..cut],
        format_ai_bytes(diff.len())
    )
}

fn safe_char_boundary(value: &str, max: usize) -> usize {
    let mut end = max.min(value.len());
    while end > 0 && !value.is_char_boundary(end) {
        end -= 1;
    }
    end
}

fn format_ai_bytes(bytes: usize) -> String {
    if bytes >= 1_048_576 {
        format!("{:.1}MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.1}KB", bytes as f64 / 1024.0)
    } else {
        format!("{}B", bytes)
    }
}

fn extract_ai_json(raw: &str) -> String {
    let trimmed = raw.trim();
    let unfenced = if trimmed.starts_with("```") {
        let without_opening = trimmed.lines().skip(1).collect::<Vec<_>>().join("\n");
        without_opening
            .trim()
            .strip_suffix("```")
            .unwrap_or(without_opening.trim())
            .trim()
            .to_string()
    } else {
        trimmed.to_string()
    };

    if unfenced.starts_with('{') && unfenced.ends_with('}') {
        return unfenced;
    }

    match (unfenced.find('{'), unfenced.rfind('}')) {
        (Some(start), Some(end)) if start < end => unfenced[start..=end].to_string(),
        _ => unfenced,
    }
}

fn non_empty_trimmed(value: String) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

fn require_non_empty(value: String, field: &str) -> Result<String> {
    non_empty_trimmed(value).with_context(|| format!("{} cannot be empty", field))
}

#[allow(clippy::too_many_arguments)]
pub fn run(
    name: Option<String>,
    message: Option<String>,
    from: Option<String>,
    prefix: Option<String>,
    all: bool,
    insert: bool,
    below: bool,
    no_verify: bool,
    ai: bool,
    yes: bool,
) -> Result<()> {
    let repo = GitRepo::open()?;
    let mut config = Config::load()?;
    let current = repo.current_branch()?;
    let placement = resolve_create_placement(&repo, &current, from, insert, below)?;
    let parent_branch = placement.parent_branch;
    let below_current_meta = placement.below_current_meta;

    if repo.branch_commit(&parent_branch).is_err() {
        anyhow::bail!("Branch '{}' does not exist", parent_branch);
    }

    let workdir = repo.workdir()?;
    let has_staged_changes = !staging::is_staging_area_empty(workdir)?;
    let has_uncommitted_changes = staging::has_uncommitted_changes(workdir);
    let non_interactive =
        yes || !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal();
    let can_prompt_for_staging = !non_interactive;
    let ai_targets = resolve_ai_create_targets(
        ai,
        name.as_deref(),
        message.as_deref(),
        all,
        has_staged_changes,
        has_uncommitted_changes,
        can_prompt_for_staging,
    )?;
    let ai_details = match ai_targets {
        Some(targets) => {
            let details =
                generate_ai_create_details(workdir, &mut config, targets, all, non_interactive)?;
            Some(resolve_ai_create_details_for_use(
                details,
                targets,
                non_interactive,
            )?)
        }
        None => None,
    };
    let ai_branch = ai_details
        .as_ref()
        .and_then(|details| details.branch.clone());
    let ai_message = ai_details
        .as_ref()
        .and_then(|details| details.message.clone());

    // Get the branch name from either name or message
    // When using -m, the message is used for both branch name and commit message.
    // `stax create -m` respects already-staged changes. When nothing is staged
    // it offers an interactive menu (or bails in non-TTY). Use -a/--all to
    // skip the menu and force-stage.
    // When neither name nor message is provided, launch interactive wizard.
    let (input, commit_message, stage_mode, generated_branch_name) = if let Some(n) = &name {
        let commit_message = ai_message;
        let stage_mode = if commit_message.is_some() {
            if all {
                StageMode::All
            } else {
                StageMode::ExistingOnly
            }
        } else if all {
            StageMode::All
        } else {
            StageMode::None
        };
        (n.clone(), commit_message, stage_mode, false)
    } else if let Some(generated_branch) = ai_branch {
        let commit_message = message.clone().or(ai_message);
        let stage_mode = if commit_message.is_some() {
            if all {
                StageMode::All
            } else {
                StageMode::ExistingOnly
            }
        } else if all {
            StageMode::All
        } else {
            StageMode::None
        };
        (generated_branch, commit_message, stage_mode, true)
    } else if let Some(m) = &message {
        (
            m.clone(),
            Some(m.clone()),
            if all {
                StageMode::All
            } else {
                StageMode::ExistingOnly
            },
            true,
        )
    } else {
        if !Term::stderr().is_term() {
            bail!("Branch name required. Use: stax create <name> or stax create -m \"message\"");
        }
        // Launch interactive wizard
        let (wizard_name, wizard_msg, wizard_stage) = run_wizard(repo.workdir()?, &parent_branch)?;
        (wizard_name, wizard_msg, wizard_stage, false)
    };

    // Format the branch name according to config
    let branch_name = match prefix.as_deref() {
        Some(_) => config.format_branch_name_with_prefix_override(&input, prefix.as_deref()),
        None => config.format_branch_name(&input),
    };
    let existing_branches = repo.list_branches()?;
    let branch_name =
        resolve_branch_name_conflicts(&branch_name, &existing_branches, generated_branch_name)?;

    // Before creating the branch, resolve the staging question. Doing this
    // early means declining ("Abort" / empty `--patch` exit) is a clean no-op
    // — no orphaned branch, no refs touched.
    //
    // Returns (needs_stage_all, skip_commit):
    //   needs_stage_all — run `git add -A` before the commit.
    //   skip_commit     — the user picked "empty branch"; drop the message and
    //                     create an empty branch instead of committing.
    let (needs_stage_all, skip_commit) = if stage_mode == StageMode::ExistingOnly {
        let workdir = repo.workdir()?;
        if staging::is_staging_area_empty(workdir)? && staging::has_uncommitted_changes(workdir) {
            match staging::prompt_action(
                workdir,
                ContinueLabel::EmptyBranch,
                "Stage files with `git add` first, or use `stax create -a -m \"message\"`.",
            )? {
                StagingAction::All => (true, false),
                StagingAction::Patch => {
                    staging::stage_patch(workdir)?;
                    if staging::is_staging_area_empty(workdir)? {
                        staging::print_patch_empty_notice();
                        return Ok(());
                    }
                    (false, false)
                }
                StagingAction::Continue => (false, true),
                StagingAction::Abort => {
                    println!(
                        "{}",
                        "Aborted. Stage files with `git add` first, or use `stax create -a -m \"message\"`."
                            .dimmed()
                    );
                    return Ok(());
                }
            }
        } else {
            (false, false)
        }
    } else {
        (false, false)
    };

    let commit_message = if skip_commit { None } else { commit_message };

    // Commit-first path: when the user supplied -m, run the commit BEFORE
    // creating or switching to the destination branch. If pre-commit hooks fail
    // (or the user hits Ctrl+C) we exit with no destination refs touched: no
    // orphan branch, no name drift to `-2`/`-3`, and the user can retry the same
    // command. Only after a successful commit do we create metadata and move
    // into the requested placement.
    if let Some(msg) = commit_message.as_deref() {
        return run_commit_first(
            &repo,
            &config,
            &current,
            &parent_branch,
            &branch_name,
            msg,
            stage_mode,
            needs_stage_all,
            insert,
            below_current_meta.as_ref(),
            no_verify,
        );
    }

    create_branch_with_banner(
        &repo,
        &config,
        &current,
        &parent_branch,
        &branch_name,
        insert,
        below_current_meta.as_ref(),
        !staging::is_staging_area_empty(workdir)?,
    )?;

    // Stage/commit behavior:
    // - StageMode::All / needs_stage_all => run `git add -A`
    // - StageMode::ExistingOnly (files already staged) => keep current index
    // - StageMode::None => no staging/committing
    if stage_mode != StageMode::None {
        let workdir = repo.workdir()?;

        if stage_mode == StageMode::All || needs_stage_all {
            if let Err(e) = staging::stage_all(workdir) {
                rollback_create_and_restore(
                    &repo,
                    &current,
                    &branch_name,
                    below_current_meta.as_ref(),
                );
                return Err(e);
            }
        }

        if stage_mode == StageMode::All {
            println!("{}", "Changes staged".dimmed());
        }
    }

    if config.ui.tips {
        println!(
            "{}",
            "Hint: Run `st ss` to submit, or add changes with `st modify -a -m \"message\"`"
                .dimmed()
        );
    }

    Ok(())
}

/// Best-effort rollback: unstage changes, checkout the original branch,
/// delete the new branch and its metadata.
/// Errors during rollback are intentionally ignored (matching the pattern in split_hunk/app.rs).
fn rollback_create(repo: &GitRepo, original_branch: &str, new_branch: &str) {
    if let Ok(workdir) = repo.workdir() {
        // Reset index first so staged changes from stage_all don't block checkout
        // or leak onto the original branch. This preserves working tree files.
        let _ = Command::new("git")
            .args(["reset"])
            .current_dir(workdir)
            .status();
        let _ = Command::new("git")
            .args(["checkout", original_branch])
            .current_dir(workdir)
            .status();
    }
    let _ = repo.delete_branch(new_branch, true);
    let _ = BranchMetadata::delete(repo.inner(), new_branch);
}

fn rollback_create_and_restore(
    repo: &GitRepo,
    original_branch: &str,
    new_branch: &str,
    restore_original_meta: Option<&BranchMetadata>,
) {
    if let Some(meta) = restore_original_meta {
        let _ = meta.write(repo.inner(), original_branch);
    }
    rollback_create(repo, original_branch, new_branch);
}

const CREATE_BELOW_AUTO_STASH_MESSAGE: &str = "stax create --below auto-stash";

/// Holds the temporary stash used when `--below` needs to move dirty work from
/// the current branch onto the new lower branch.
struct CreateBelowAutoStash {
    active: bool,
    restore_index: bool,
}

impl CreateBelowAutoStash {
    fn inactive() -> Self {
        Self {
            active: false,
            restore_index: false,
        }
    }

    fn push_if_dirty(workdir: &Path, restore_index: bool) -> Result<Self> {
        if !staging::has_uncommitted_changes(workdir) {
            return Ok(Self::inactive());
        }

        let output = run_git_output(
            workdir,
            &["stash", "push", "-u", "-m", CREATE_BELOW_AUTO_STASH_MESSAGE],
            "git stash push",
        )?;

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stdout.contains("No local changes") || stderr.contains("No local changes") {
            return Ok(Self::inactive());
        }

        println!("{}", "✓ Stashed working tree changes for --below.".green());
        Ok(Self {
            active: true,
            restore_index,
        })
    }

    fn is_active(&self) -> bool {
        self.active
    }

    fn apply_to_worktree(&self, workdir: &Path) -> Result<()> {
        if !self.active {
            return Ok(());
        }

        run_git_output(workdir, &["stash", "apply"], "git stash apply")?;

        if self.restore_index {
            restore_auto_stash_index(workdir)?;
        }

        Ok(())
    }

    fn restore_on_original_branch(
        &mut self,
        repo: &GitRepo,
        workdir: &Path,
        original_branch: &str,
    ) -> Result<()> {
        if !self.active {
            return Ok(());
        }

        reset_hard_and_clean(workdir)?;
        repo.checkout(original_branch)
            .with_context(|| format!("Failed to checkout original branch '{}'", original_branch))?;
        self.apply_to_worktree(workdir)
            .with_context(|| format!("Failed to restore auto-stash on '{}'", original_branch))?;
        self.drop_stash(workdir)?;
        println!(
            "{}",
            "✓ Restored stashed changes on original branch.".green()
        );
        Ok(())
    }

    fn drop_stash(&mut self, workdir: &Path) -> Result<()> {
        if !self.active {
            return Ok(());
        }

        run_git_output(workdir, &["stash", "drop"], "git stash drop")?;

        self.active = false;
        Ok(())
    }
}

fn restore_auto_stash_index(workdir: &Path) -> Result<()> {
    let diff = run_git_output(
        workdir,
        &["diff", "--binary", "stash@{0}^1", "stash@{0}^2"],
        "git diff for auto-stash index",
    )?;
    if diff.stdout.is_empty() {
        return Ok(());
    }

    let mut apply = Command::new("git")
        .args(["apply", "--cached", "--3way"])
        .current_dir(workdir)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .context("Failed to run git apply for auto-stash index")?;

    let Some(mut stdin) = apply.stdin.take() else {
        bail!("Failed to open git apply stdin for auto-stash index");
    };
    stdin
        .write_all(&diff.stdout)
        .context("Failed to write auto-stash index diff to git apply")?;
    drop(stdin);

    let output = apply
        .wait_with_output()
        .context("Failed to wait for git apply for auto-stash index")?;
    if !output.status.success() {
        bail!(
            "git apply for auto-stash index failed: {}",
            format_git_output(&output)
        );
    }

    Ok(())
}

fn reset_hard_and_clean(workdir: &Path) -> Result<()> {
    run_git_output(workdir, &["reset", "--hard"], "git reset --hard")?;
    run_git_output(workdir, &["clean", "-fd"], "git clean -fd")?;

    Ok(())
}

fn run_git_output(workdir: &Path, args: &[&str], action: &str) -> Result<Output> {
    let output = Command::new("git")
        .args(args)
        .current_dir(workdir)
        .output()
        .with_context(|| format!("Failed to run {}", action))?;

    if !output.status.success() {
        bail!("{} failed: {}", action, format_git_output(&output));
    }

    Ok(output)
}

fn format_git_output(output: &Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    match (stderr.is_empty(), stdout.is_empty()) {
        (false, false) => format!("{}\n{}", stderr, stdout),
        (false, true) => stderr,
        (true, false) => stdout,
        (true, true) => output.status.to_string(),
    }
}

/// Graphite-style commit-first flow: commit before creating the destination
/// branch, then split the new commit off to a new branch.
///
/// The key property: nothing observable changes until `git commit` returns
/// successfully. If pre-commit hooks reject the commit, or the user hits
/// Ctrl+C during the commit, no destination branch is created and no metadata
/// is written — so retrying the exact same command is a clean operation that
/// does not drift into `mybranch-2`, `mybranch-3`, etc.
///
/// When `parent_branch != current` (`--from` or `--below`), we check out the
/// parent detached before committing. That makes the resulting commit's parent
/// correct without advancing the requested parent branch.
///
/// For `--below` with prepared local changes, the dirty worktree is
/// auto-stashed before the detached checkout and the stash is kept until the
/// command succeeds, so any failure can restore the original branch and index.
#[allow(clippy::too_many_arguments)]
fn run_commit_first(
    repo: &GitRepo,
    config: &Config,
    current: &str,
    parent_branch: &str,
    branch_name: &str,
    message: &str,
    stage_mode: StageMode,
    needs_stage_all: bool,
    insert: bool,
    below_current_meta: Option<&BranchMetadata>,
    no_verify: bool,
) -> Result<()> {
    let workdir = repo.workdir()?;
    let committing_on_current = parent_branch == current;
    let parent_sha = repo.branch_commit(parent_branch)?;
    let mut auto_stash = if !committing_on_current && below_current_meta.is_some() {
        CreateBelowAutoStash::push_if_dirty(workdir, !staging::is_staging_area_empty(workdir)?)?
    } else {
        CreateBelowAutoStash::inactive()
    };

    if !committing_on_current {
        if let Err(e) = checkout_detached_for_commit(workdir, parent_branch) {
            auto_stash.restore_on_original_branch(repo, workdir, current)?;
            return Err(e);
        }
        if let Err(e) = auto_stash.apply_to_worktree(workdir) {
            let apply_error = e.to_string();
            if let Err(restore_error) =
                auto_stash.restore_on_original_branch(repo, workdir, current)
            {
                bail!(
                    "Could not apply stashed changes to '{}' for `st create --below`: {}. \
                     Auto-stash was kept; run `git stash list` before retrying. \
                     Restore attempt failed: {}",
                    parent_branch,
                    apply_error,
                    restore_error
                );
            }
            bail!(
                "Could not apply stashed changes to '{}' for `st create --below`: {}. \
                 Restored changes on '{}'.",
                parent_branch,
                apply_error,
                current
            );
        }
        if auto_stash.is_active() {
            println!(
                "{}",
                "✓ Applied stashed changes on lower branch base.".green()
            );
        }
    }

    // Stage (if requested) BEFORE the commit so hooks see the final tree.
    if stage_mode == StageMode::All || needs_stage_all {
        if let Err(e) = staging::stage_all(workdir) {
            restore_after_failed_pre_branch_commit(
                repo,
                workdir,
                current,
                committing_on_current,
                &mut auto_stash,
            );
            return Err(e);
        }
    }

    // If nothing is staged by the time we reach here, there is no commit to
    // make. Fall back to creating an empty branch — same shape as the
    // branch-first path without the trailing commit.
    let staging_area_empty = match staging::is_staging_area_empty(workdir) {
        Ok(empty) => empty,
        Err(e) => {
            restore_after_failed_pre_branch_commit(
                repo,
                workdir,
                current,
                committing_on_current,
                &mut auto_stash,
            );
            return Err(e);
        }
    };

    if staging_area_empty {
        create_branch_with_banner(
            repo,
            config,
            current,
            parent_branch,
            branch_name,
            insert,
            below_current_meta,
            false,
        )?;
        println!("{}", "No changes to commit".dimmed());
        print_tips(config);
        auto_stash.drop_stash(workdir)?;
        return Ok(());
    }

    // Run the commit before the destination branch exists. `--quiet`
    // suppresses git's "[<branch> <sha>] <msg>" summary that would otherwise
    // mention the temporary commit location; we print our own summary after
    // the commit is split off. Pre-commit hook output is not suppressed by -q.
    let commit = match run_git_commit(workdir, message, true, no_verify) {
        Ok(commit) => commit,
        Err(e) => {
            restore_after_failed_pre_branch_commit(
                repo,
                workdir,
                current,
                committing_on_current,
                &mut auto_stash,
            );
            return Err(e);
        }
    };

    if !commit.status.success() {
        restore_after_failed_pre_branch_commit(
            repo,
            workdir,
            current,
            committing_on_current,
            &mut auto_stash,
        );
        if commit.interrupted {
            bail!(
                "Commit interrupted. \
                 No branch was created — fix the issue and retry with the same command."
            );
        } else {
            bail!(
                "Commit failed (pre-commit hook or other error). \
                 No branch was created — fix the issue and retry with the same command."
            );
        }
    }

    if commit.interrupted {
        rollback_after_commit(
            workdir,
            current,
            &parent_sha,
            None,
            repo,
            committing_on_current,
            below_current_meta,
            &mut auto_stash,
        );
        bail!(
            "Commit interrupted. \
             No branch was created — fix the issue and retry with the same command."
        );
    }

    // From here on the commit exists either on the current branch or on a
    // detached HEAD at `parent_branch`. Any failure must preserve the user's
    // staged work and avoid leaving a destination branch behind.
    let new_sha = match repo.rev_parse("HEAD") {
        Ok(sha) => sha,
        Err(e) => {
            rollback_after_commit(
                workdir,
                current,
                &parent_sha,
                None,
                repo,
                committing_on_current,
                below_current_meta,
                &mut auto_stash,
            );
            return Err(e);
        }
    };

    if let Err(e) = repo.create_branch_at_commit(branch_name, &new_sha) {
        rollback_after_commit(
            workdir,
            current,
            &parent_sha,
            None,
            repo,
            committing_on_current,
            below_current_meta,
            &mut auto_stash,
        );
        return Err(e);
    }

    let meta = BranchMetadata::new(parent_branch, &parent_sha);
    if let Err(e) = meta.write(repo.inner(), branch_name) {
        rollback_after_commit(
            workdir,
            current,
            &parent_sha,
            Some(branch_name),
            repo,
            committing_on_current,
            below_current_meta,
            &mut auto_stash,
        );
        return Err(e);
    }

    if insert {
        if let Err(e) = apply_insert_reparenting(repo, parent_branch, branch_name) {
            rollback_after_commit(
                workdir,
                current,
                &parent_sha,
                Some(branch_name),
                repo,
                committing_on_current,
                below_current_meta,
                &mut auto_stash,
            );
            return Err(e);
        }
    }

    if let Some(current_meta) = below_current_meta {
        if let Err(e) = apply_below_reparenting(repo, current, branch_name, current_meta) {
            rollback_after_commit(
                workdir,
                current,
                &parent_sha,
                Some(branch_name),
                repo,
                committing_on_current,
                below_current_meta,
                &mut auto_stash,
            );
            return Err(e);
        }
    }

    if committing_on_current {
        // Move the current branch ref back to the pre-commit SHA. The new commit
        // now lives only on `branch_name`.
        let current_ref = format!("refs/heads/{}", current);
        if let Err(e) = repo.update_ref(&current_ref, &parent_sha) {
            rollback_after_commit(
                workdir,
                current,
                &parent_sha,
                Some(branch_name),
                repo,
                committing_on_current,
                below_current_meta,
                &mut auto_stash,
            );
            return Err(e);
        }
    }

    // Switch to the new branch. In the current-parent case HEAD still points at
    // `current` (now at the old SHA) while the working tree matches the new
    // commit; in the detached-parent case HEAD already points at the new commit.
    // `git checkout` only moves HEAD in both cases.
    if let Err(e) = repo.checkout(branch_name) {
        rollback_after_commit(
            workdir,
            current,
            &parent_sha,
            Some(branch_name),
            repo,
            committing_on_current,
            below_current_meta,
            &mut auto_stash,
        );
        return Err(e);
    }
    auto_stash.drop_stash(workdir)?;

    print_remote_parent_warning(repo, config, parent_branch);
    println!(
        "Created and switched to branch '{}' (stacked on {})",
        branch_name.green(),
        parent_branch.blue()
    );
    println!("Committed: {}", message.cyan());
    print_tips(config);

    Ok(())
}

struct GitCommitResult {
    status: ExitStatus,
    interrupted: bool,
}

struct CommitSignalGuard {
    interrupted: Arc<AtomicBool>,
    registrations: Vec<signal_hook::SigId>,
}

impl CommitSignalGuard {
    fn install() -> Result<Self> {
        let interrupted = Arc::new(AtomicBool::new(false));
        let sigint = signal_hook::flag::register(
            signal_hook::consts::signal::SIGINT,
            Arc::clone(&interrupted),
        )
        .context("Failed to install SIGINT handler")?;
        let sigterm = match signal_hook::flag::register(
            signal_hook::consts::signal::SIGTERM,
            Arc::clone(&interrupted),
        ) {
            Ok(registration) => registration,
            Err(e) => {
                let _ = signal_hook::low_level::unregister(sigint);
                return Err(anyhow::Error::from(e).context("Failed to install SIGTERM handler"));
            }
        };

        Ok(Self {
            interrupted,
            registrations: vec![sigint, sigterm],
        })
    }

    fn interrupted(&self) -> bool {
        self.interrupted.load(Ordering::SeqCst)
    }
}

impl Drop for CommitSignalGuard {
    fn drop(&mut self) {
        for registration in self.registrations.drain(..) {
            let _ = signal_hook::low_level::unregister(registration);
        }
    }
}

fn run_git_commit(
    workdir: &Path,
    message: &str,
    quiet: bool,
    no_verify: bool,
) -> Result<GitCommitResult> {
    let guard = CommitSignalGuard::install()?;
    let mut args = vec!["commit"];
    if quiet {
        args.push("--quiet");
    }
    if no_verify {
        args.push("--no-verify");
    }
    args.extend(["-m", message]);

    let status = Command::new("git")
        .args(args)
        .current_dir(workdir)
        .status()
        .context("Failed to run git commit")?;
    let interrupted = guard.interrupted();

    Ok(GitCommitResult {
        status,
        interrupted,
    })
}

fn checkout_detached_for_commit(workdir: &Path, parent_branch: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["checkout", "--detach", parent_branch])
        .current_dir(workdir)
        .output()
        .context("Failed to run git checkout --detach")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        bail!(
            "Failed to prepare commit on '{}': {}",
            parent_branch,
            stderr
        );
    }

    Ok(())
}

fn restore_after_failed_pre_branch_commit(
    repo: &GitRepo,
    workdir: &Path,
    original_branch: &str,
    committing_on_current: bool,
    auto_stash: &mut CreateBelowAutoStash,
) {
    if auto_stash.is_active() {
        let _ = auto_stash.restore_on_original_branch(repo, workdir, original_branch);
        return;
    }

    if committing_on_current {
        return;
    }

    let _ = Command::new("git")
        .args(["reset"])
        .current_dir(workdir)
        .status();
    let _ = repo.checkout(original_branch);
}

/// Undo the partial state left by `run_commit_first` when a step after
/// `git commit` (branch creation, metadata write, ref update) fails.
///
/// Without an active auto-stash, `--soft` keeps the working tree and index
/// exactly as git left them after the successful commit, so the user can retry
/// without re-staging. With an active `--below` auto-stash, restore the original
/// stash instead because the post-commit tree may be based on a different parent.
fn rollback_after_commit(
    workdir: &Path,
    original_branch: &str,
    old_sha: &str,
    new_branch: Option<&str>,
    repo: &GitRepo,
    committing_on_current: bool,
    restore_original_meta: Option<&BranchMetadata>,
    auto_stash: &mut CreateBelowAutoStash,
) {
    if let Some(meta) = restore_original_meta {
        let _ = meta.write(repo.inner(), original_branch);
    }
    if let Some(name) = new_branch {
        let _ = BranchMetadata::delete(repo.inner(), name);
        let _ = repo.delete_branch(name, true);
    }

    if auto_stash.is_active() {
        let _ = auto_stash.restore_on_original_branch(repo, workdir, original_branch);
        return;
    }

    let _ = Command::new("git")
        .args(["reset", "--soft", old_sha])
        .current_dir(workdir)
        .status();

    if !committing_on_current {
        let _ = repo.checkout(original_branch);
    }
}

/// Create `branch_name` stacked on `parent_branch`, write stax metadata,
/// apply `--insert`/`--below` reparenting, check out the new branch, and print the
/// "Created and switched…" banner. On any failure, undo all of it with
/// `rollback_create` so the caller sees a clean failure.
///
/// `original` is the branch the user was on when `st create` was invoked; it's
/// where `rollback_create` checks out on failure. For the commit-first
/// no-changes fallback `original == parent_branch == current`; for the
/// branch-first flow `original == current`, and `parent_branch` may or may not
/// equal it (the `--from` and `--below` cases).
///
/// The caller owns whatever comes next — the trailing "No changes to commit"
/// note, the stage/commit block, or the tips line.
fn create_branch_with_banner(
    repo: &GitRepo,
    config: &Config,
    original: &str,
    parent_branch: &str,
    branch_name: &str,
    insert: bool,
    below_current_meta: Option<&BranchMetadata>,
    restore_stash_index: bool,
) -> Result<()> {
    let workdir = repo.workdir()?;
    let mut auto_stash = if below_current_meta.is_some() {
        CreateBelowAutoStash::push_if_dirty(workdir, restore_stash_index)?
    } else {
        CreateBelowAutoStash::inactive()
    };

    if let Err(e) = if parent_branch == original {
        repo.create_branch(branch_name)
    } else {
        repo.create_branch_at(branch_name, parent_branch)
    } {
        auto_stash.restore_on_original_branch(repo, workdir, original)?;
        return Err(e);
    };

    let parent_rev = repo.branch_commit(parent_branch)?;
    let meta = BranchMetadata::new(parent_branch, &parent_rev);
    if let Err(e) = meta.write(repo.inner(), branch_name) {
        rollback_create(repo, original, branch_name);
        auto_stash.restore_on_original_branch(repo, workdir, original)?;
        return Err(e);
    }

    if insert {
        if let Err(e) = apply_insert_reparenting(repo, parent_branch, branch_name) {
            rollback_create(repo, original, branch_name);
            auto_stash.restore_on_original_branch(repo, workdir, original)?;
            return Err(e);
        }
    }

    if let Some(current_meta) = below_current_meta {
        if let Err(e) = apply_below_reparenting(repo, original, branch_name, current_meta) {
            rollback_create_and_restore(repo, original, branch_name, below_current_meta);
            auto_stash.restore_on_original_branch(repo, workdir, original)?;
            return Err(e);
        }
    }

    if let Err(e) = repo.checkout(branch_name) {
        rollback_create_and_restore(repo, original, branch_name, below_current_meta);
        auto_stash.restore_on_original_branch(repo, workdir, original)?;
        return Err(e);
    }
    if let Err(e) = auto_stash.apply_to_worktree(workdir) {
        bail!(
            "Created and switched to '{}', but could not apply stashed changes: {}. \
             Auto-stash was kept; resolve the working tree or run `git stash apply` manually.",
            branch_name,
            e
        );
    }
    if auto_stash.is_active() {
        auto_stash.drop_stash(workdir)?;
        println!("{}", "✓ Restored stashed changes on new branch.".green());
    }

    print_remote_parent_warning(repo, config, parent_branch);
    println!(
        "Created and switched to branch '{}' (stacked on {})",
        branch_name.green(),
        parent_branch.blue()
    );

    Ok(())
}

fn resolve_create_placement(
    repo: &GitRepo,
    current: &str,
    from: Option<String>,
    insert: bool,
    below: bool,
) -> Result<CreatePlacement> {
    if insert && below {
        bail!("`--insert` and `--below` cannot be used together");
    }
    if below && from.is_some() {
        bail!("`--below` cannot be used with `--from`");
    }

    if below {
        let meta = resolve_below_current_metadata(repo, current)?;
        return Ok(CreatePlacement {
            parent_branch: meta.parent_branch_name.clone(),
            below_current_meta: Some(meta),
        });
    }

    Ok(CreatePlacement {
        parent_branch: from.unwrap_or_else(|| current.to_string()),
        below_current_meta: None,
    })
}

fn resolve_below_current_metadata(repo: &GitRepo, current: &str) -> Result<BranchMetadata> {
    let trunk = repo.trunk_branch()?;
    if current == trunk {
        bail!("Cannot create a branch below trunk. Checkout a stacked branch first.");
    }

    let meta = BranchMetadata::read(repo.inner(), current)?.ok_or_else(|| {
        anyhow::anyhow!(
            "Branch '{}' is not tracked by stax. Run `st branch track` first.",
            current
        )
    })?;

    if meta.parent_branch_name == current {
        bail!(
            "Cannot create a branch below '{}': branch metadata points to itself as parent.",
            current
        );
    }

    Ok(meta)
}

/// Reparent children of `parent_branch` onto `new_branch` and print the usual
/// `--insert` summary. Extracted from the branch-first path so both flows
/// share the same behaviour.
fn apply_insert_reparenting(repo: &GitRepo, parent_branch: &str, new_branch: &str) -> Result<()> {
    let stack = Stack::load(repo)?;
    let Some(parent_info) = stack.branches.get(parent_branch) else {
        return Ok(());
    };
    let children: Vec<String> = parent_info
        .children
        .iter()
        .filter(|c| c.as_str() != new_branch)
        .cloned()
        .collect();

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

    let new_parent_rev = repo.branch_commit(new_branch)?;
    for child in &children {
        if let Some(child_meta) = BranchMetadata::read(repo.inner(), child)? {
            let updated = BranchMetadata {
                parent_branch_name: new_branch.to_string(),
                parent_branch_revision: new_parent_rev.clone(),
                ..child_meta
            };
            updated.write(repo.inner(), child)?;
        }
    }

    println!(
        "Reparented {} child branch(es) to '{}'",
        children.len(),
        new_branch.green()
    );
    for child in &children {
        println!("  {} -> {}", child.cyan(), new_branch.green());
    }
    println!(
        "{}",
        "Run `stax restack --all` to rebase the reparented branches.".yellow()
    );

    Ok(())
}

/// Insert `new_branch` between `current_branch` and its current parent.
/// Descendant metadata stays untouched: moving the subtree root makes all
/// descendants follow it while preserving their relative structure.
fn apply_below_reparenting(
    repo: &GitRepo,
    current_branch: &str,
    new_branch: &str,
    current_meta: &BranchMetadata,
) -> Result<()> {
    let new_parent_rev = repo.branch_commit(new_branch)?;
    let parent_revision = repo
        .merge_base(new_branch, current_branch)
        .unwrap_or(new_parent_rev);
    let updated = BranchMetadata {
        parent_branch_name: new_branch.to_string(),
        parent_branch_revision: parent_revision,
        ..current_meta.clone()
    };
    updated.write(repo.inner(), current_branch)?;

    let descendants = Stack::load(repo)?.descendants(current_branch);

    println!(
        "Reparented '{}' onto '{}'",
        current_branch.green(),
        new_branch.green()
    );
    if !descendants.is_empty() {
        println!(
            "  {} descendant branch(es) moved with it:",
            descendants.len().to_string().cyan()
        );
        for descendant in &descendants {
            println!("    {}", descendant.dimmed());
        }
    }
    println!(
        "{}",
        "Run `stax restack` to rebase the moved branches onto their new parent.".yellow()
    );

    Ok(())
}

fn print_remote_parent_warning(repo: &GitRepo, config: &Config, parent_branch: &str) {
    let Ok(workdir) = repo.workdir() else {
        return;
    };
    if let Ok(remote_branches) = remote::get_remote_branches(workdir, config.remote_name()) {
        if !remote_branches.contains(&parent_branch.to_string()) {
            println!(
                "{}",
                format!(
                    "Warning: parent '{}' is not on remote '{}'.",
                    parent_branch,
                    config.remote_name()
                )
                .yellow()
            );
        }
    }
}

fn print_tips(config: &Config) {
    if config.ui.tips {
        println!(
            "{}",
            "Hint: Run `st ss` to submit, or add changes with `st modify -a -m \"message\"`"
                .dimmed()
        );
    }
}

#[derive(Clone, Copy)]
enum BranchNameConflict<'a> {
    Exact(&'a str),
    ExistingIsAncestor(&'a str),
    ExistingIsDescendant(&'a str),
}

fn resolve_branch_name_conflicts(
    branch_name: &str,
    existing_branches: &[String],
    generated_branch_name: bool,
) -> Result<String> {
    match detect_branch_name_conflict(branch_name, existing_branches) {
        None => Ok(branch_name.to_string()),
        Some(conflict) if generated_branch_name => bail!(
            "{}\n\
             Generated branch names are not auto-suffixed.\n\
             Checkout/reparent the existing branch or pass an explicit different branch name.",
            branch_name_conflict_message(branch_name, conflict)
        ),
        Some(conflict) => bail!("{}", branch_name_conflict_message(branch_name, conflict)),
    }
}

fn detect_branch_name_conflict<'a>(
    branch_name: &str,
    existing_branches: &'a [String],
) -> Option<BranchNameConflict<'a>> {
    for existing in existing_branches {
        if branch_name == existing {
            return Some(BranchNameConflict::Exact(existing));
        }

        if branch_name.starts_with(&format!("{}/", existing)) {
            return Some(BranchNameConflict::ExistingIsAncestor(existing));
        }

        if existing.starts_with(&format!("{}/", branch_name)) {
            return Some(BranchNameConflict::ExistingIsDescendant(existing));
        }
    }

    None
}

fn branch_name_conflict_message(branch_name: &str, conflict: BranchNameConflict<'_>) -> String {
    match conflict {
        BranchNameConflict::Exact(existing) => format!(
            "Cannot create '{}': branch '{}' already exists.\n\
             Use `st checkout {}` or choose a different name.",
            branch_name, existing, existing
        ),
        BranchNameConflict::ExistingIsAncestor(existing) => format!(
            "Cannot create '{}': branch '{}' already exists.\n\
             Git doesn't allow a branch and its sub-path to coexist.\n\
             Either delete '{}' first, or use a different name like '{}-ui'.",
            branch_name, existing, existing, existing
        ),
        BranchNameConflict::ExistingIsDescendant(existing) => format!(
            "Cannot create '{}': branch '{}' already exists.\n\
             Git doesn't allow a branch and its sub-path to coexist.\n\
             Either delete '{}' first, or use a different name.",
            branch_name, existing, existing
        ),
    }
}

/// Interactive wizard for branch creation when no arguments provided.
///
/// Returns `(branch_name, commit_message, stage_mode)`. When the wizard
/// routes to the staging menu and the user picks `--patch`, we run
/// `git add -p` inline so the caller sees the "staged manually" shape
/// (`StageMode::ExistingOnly`, no auto-stage-all).
fn run_wizard(workdir: &Path, parent_branch: &str) -> Result<(String, Option<String>, StageMode)> {
    println!();
    println!("╭─ Create Stacked Branch ─────────────────────────────╮");
    println!(
        "│ Parent: {:<43} │",
        format!("{} (current branch)", parent_branch.cyan())
    );
    println!("╰─────────────────────────────────────────────────────╯");
    println!();

    let name: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Branch name")
        .interact_text()?;

    if name.trim().is_empty() {
        bail!("Branch name cannot be empty");
    }

    let has_changes = staging::has_uncommitted_changes(workdir);
    let change_count = staging::count_uncommitted_changes(workdir);

    if !has_changes {
        println!();
        return Ok((name, None, StageMode::None));
    }

    println!();

    let stage_label = if change_count > 0 {
        format!("Stage all changes ({} files modified)", change_count)
    } else {
        "Stage all changes".to_string()
    };
    let options = vec![
        stage_label.as_str(),
        "Select changes to commit (--patch)",
        "Empty branch (no changes)",
    ];

    let choice = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("What to include")
        .items(&options)
        .default(0)
        .interact()?;

    let stage_mode = match choice {
        0 => StageMode::All,
        1 => {
            staging::stage_patch(workdir)?;
            if staging::is_staging_area_empty(workdir)? {
                staging::print_patch_empty_notice();
                // Fall through to creating the branch with no commit —
                // matches the "empty branch" outcome.
                StageMode::None
            } else {
                StageMode::ExistingOnly
            }
        }
        _ => StageMode::None,
    };

    // Commit message only when we have something staged.
    let msg = if stage_mode != StageMode::None {
        println!();
        let m: String = Input::with_theme(&ColorfulTheme::default())
            .with_prompt("Commit message (Enter to skip)")
            .allow_empty(true)
            .interact_text()?;
        if m.is_empty() { None } else { Some(m) }
    } else {
        None
    };

    println!();
    Ok((name, msg, stage_mode))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn targets(branch: bool, message: bool) -> AiCreateTargets {
        AiCreateTargets { branch, message }
    }

    #[test]
    fn ai_create_targets_plain_ai_generates_branch_and_message_for_all_changes() {
        let resolved =
            resolve_ai_create_targets(true, None, None, true, false, true, false).unwrap();

        assert_eq!(resolved, Some(targets(true, true)));
    }

    #[test]
    fn ai_create_targets_named_branch_generates_commit_message_only() {
        let resolved =
            resolve_ai_create_targets(true, Some("manual-branch"), None, false, true, true, false)
                .unwrap();

        assert_eq!(resolved, Some(targets(false, true)));
    }

    #[test]
    fn ai_create_targets_manual_message_generates_branch_only() {
        let resolved = resolve_ai_create_targets(
            true,
            None,
            Some("Manual commit message"),
            true,
            false,
            true,
            false,
        )
        .unwrap();

        assert_eq!(resolved, Some(targets(true, false)));
    }

    #[test]
    fn ai_create_targets_skips_ai_when_no_field_needs_generation() {
        let resolved = resolve_ai_create_targets(
            true,
            Some("manual-branch"),
            None,
            false,
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(resolved, None);
    }

    #[test]
    fn ai_create_targets_do_not_generate_message_without_commit_path() {
        let resolved =
            resolve_ai_create_targets(true, None, None, false, false, true, false).unwrap();

        assert_eq!(resolved, Some(targets(true, false)));
    }

    #[test]
    fn parse_ai_create_details_accepts_fenced_json() {
        let parsed = parse_ai_create_details(
            "```json\n{\"branch\":\"add-ai-create\",\"message\":\"Add AI create\"}\n```",
            targets(true, true),
        )
        .unwrap();

        assert_eq!(parsed.branch.as_deref(), Some("add-ai-create"));
        assert_eq!(parsed.message.as_deref(), Some("Add AI create"));
    }

    #[test]
    fn parse_ai_create_details_requires_requested_fields() {
        let err = parse_ai_create_details(r#"{"message":"Only a message"}"#, targets(true, false))
            .unwrap_err();
        assert!(err.to_string().contains("non-empty branch"));

        let err = parse_ai_create_details(r#"{"branch":"only-branch"}"#, targets(false, true))
            .unwrap_err();
        assert!(err.to_string().contains("non-empty commit message"));
    }

    #[test]
    fn build_ai_create_prompt_mentions_only_requested_fields() {
        let prompt = build_ai_create_details_prompt(
            " M src/lib.rs",
            "diff --git a/src/lib.rs b/src/lib.rs",
            "",
            targets(false, true),
            true,
        );

        assert!(prompt.contains("\"message\""));
        assert!(!prompt.contains("\"branch\" and \"message\""));
        assert!(prompt.contains("The command will stage all changes before committing."));
        assert!(prompt.contains("diff --git"));
    }
}