worktree-setup 0.3.0

CLI tool for setting up git worktrees with project-specific configurations
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
//! Interactive prompts using dialoguer.

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::Duration;

use colored::Colorize;
use console::{Key, Term};
use dialoguer::{Confirm, Input, MultiSelect, Select};
use worktree_setup_config::{CreationMethod, LoadedConfig};
use worktree_setup_git::{
    Repository, WorktreeCreateOptions, WorktreeInfo, fetch_remote, get_remote_branches, get_remotes,
};

use crate::output;

/// Select which configs to apply from a list.
///
/// # Errors
///
/// * If the user cancels the selection
pub fn select_configs(configs: &[LoadedConfig]) -> io::Result<Vec<usize>> {
    if configs.len() == 1 {
        // If there's only one config, auto-select it
        return Ok(vec![0]);
    }

    let items: Vec<String> = configs
        .iter()
        .map(|c| format!("{} - {}", c.relative_path, c.config.description))
        .collect();

    let selections = MultiSelect::new()
        .with_prompt("Select configurations to apply")
        .items(&items)
        .defaults(&vec![true; items.len()])
        .interact()?;

    Ok(selections)
}

/// Format a worktree as a display label for selection prompts.
///
/// Shows: `branch (path)` with `[main]` suffix for the main worktree,
/// or `detached@commit (path)` for detached HEAD.
#[must_use]
fn format_worktree_label(wt: &WorktreeInfo) -> String {
    let suffix = if wt.is_main { " [main]" } else { "" };

    wt.branch.as_ref().map_or_else(
        || {
            wt.commit.as_ref().map_or_else(
                || format!("({}){suffix}", wt.path.display()),
                |commit| format!("detached@{commit} ({}){suffix}", wt.path.display()),
            )
        },
        |branch| format!("{branch} ({}){suffix}", wt.path.display()),
    )
}

/// Resolved clean data for a single worktree, produced by a background thread.
pub struct WorktreeResolution {
    /// Index of the worktree in the original list.
    pub index: usize,
    /// Resolved absolute paths paired with their display strings.
    pub resolved: Vec<(PathBuf, String)>,
    /// Preview items with type and size info.
    pub items: Vec<output::CleanItem>,
    /// Human-readable summary (e.g. "3 items, 150.2 MiB").
    pub summary: String,
}

/// Resolved warning for a single worktree, produced by a background thread.
pub struct WarningResolution {
    /// Index of the worktree in the original list.
    pub index: usize,
    /// Warning text, or `None` if the worktree is clean.
    pub warning: Option<String>,
}

/// Tri-state status for a worktree warning check.
#[derive(Clone)]
enum WarningStatus {
    /// Background thread has not yet reported for this worktree.
    Pending,
    /// Check completed — worktree is clean (no warning).
    Clean,
    /// Check completed — worktree has a warning to display.
    Warning(String),
}

/// Result type for [`select_worktrees_for_removal`]:
/// `(selected_indices_or_none, per_worktree_warnings)`.
pub type RemovalPickerResult = (Option<Vec<usize>>, Vec<Option<String>>);

/// Spinner frames (braille dots).
const SPINNER_FRAMES: &[char] = &['', '', '', '', '', '', '', '', '', ''];

/// Tick interval for the spinner animation (milliseconds).
const SPINNER_TICK_MS: u64 = 80;

/// Custom multi-select widget that shows live-updating size info per worktree.
///
/// Displays all worktrees immediately with animated spinners. As background
/// threads resolve clean paths and compute sizes, spinners are replaced with
/// summary text (e.g., "3 items, 150.2 MiB" or "nothing to clean").
///
/// Key bindings match `dialoguer::MultiSelect`:
/// * `↑`/`k` — move cursor up
/// * `↓`/`j`/`Tab` — move cursor down
/// * `Space` — toggle selection
/// * `a` — toggle all
/// * `Enter` — confirm
/// * `Escape`/`q` — cancel
///
/// # Arguments
///
/// * `worktrees` - The worktrees to display
/// * `result_rx` - Channel receiving `WorktreeResolution`s from background threads
/// * `done` - Atomic flag signaling background work is complete
///
/// # Returns
///
/// `Ok((Some(indices), resolutions))` on confirm, `Ok((None, resolutions))` on cancel.
/// The `resolutions` vector contains all `WorktreeResolution`s received from
/// background threads during the session.
///
/// # Errors
///
/// * If terminal I/O fails
#[allow(clippy::too_many_lines)]
pub fn select_worktrees_with_sizes(
    worktrees: &[WorktreeInfo],
    result_rx: &mpsc::Receiver<WorktreeResolution>,
    done: &AtomicBool,
) -> io::Result<(Option<Vec<usize>>, Vec<WorktreeResolution>)> {
    let count = worktrees.len();
    if count == 0 {
        return Ok((Some(Vec::new()), Vec::new()));
    }

    let term = Term::stderr();
    let labels: Vec<String> = worktrees.iter().map(format_worktree_label).collect();

    let mut state = SelectState {
        checked: vec![false; count],
        statuses: vec![None; count],
        resolutions: Vec::new(),
        cursor: 0,
        spinner_frame: 0,
    };

    // Spawn a thread that reads keys and sends them over a channel.
    // This lets us poll for keys without blocking the render loop.
    let (key_tx, key_rx) = mpsc::channel::<Key>();
    let input_done = std::sync::Arc::new(AtomicBool::new(false));
    let input_done_clone = input_done.clone();

    let input_term = term.clone();
    let input_handle = std::thread::spawn(move || {
        loop {
            if input_done_clone.load(Ordering::Relaxed) {
                break;
            }
            if let Ok(key) = input_term.read_key()
                && key_tx.send(key).is_err()
            {
                break;
            }
        }
    });

    term.hide_cursor()?;

    // Initial render — print the prompt header + all items
    let prompt_line = format!(
        "{} {}",
        "?".green().bold(),
        "Select worktrees to clean (space to toggle, enter to confirm):".bold()
    );
    term.write_line(&prompt_line)?;
    render_items(
        &term,
        &labels,
        &state.checked,
        &state.statuses,
        state.cursor,
        state.spinner_frame,
    )?;

    let result = run_select_loop(&term, &labels, &mut state, &key_rx, result_rx, done);

    // Cleanup: show cursor, clear the rendered lines, signal input thread to stop
    term.show_cursor()?;
    // +1 for the prompt line
    term.clear_last_lines(count + 1)?;
    input_done.store(true, Ordering::Relaxed);

    // We can't join the input thread (it's blocked on read_key), so detach it.
    drop(input_handle);

    // Return (selection, resolutions) — map the inner result
    result.map(|sel| (sel, state.resolutions))
}

/// Mutable state for the custom multi-select widget.
struct SelectState {
    checked: Vec<bool>,
    statuses: Vec<Option<String>>,
    resolutions: Vec<WorktreeResolution>,
    cursor: usize,
    spinner_frame: usize,
}

/// Main loop for the custom multi-select widget.
///
/// Polls for key events and background results, re-renders on changes.
#[allow(clippy::too_many_arguments)]
fn run_select_loop(
    term: &Term,
    labels: &[String],
    state: &mut SelectState,
    key_rx: &mpsc::Receiver<Key>,
    result_rx: &mpsc::Receiver<WorktreeResolution>,
    done: &AtomicBool,
) -> io::Result<Option<Vec<usize>>> {
    let count = labels.len();

    loop {
        // Drain all available background results
        let mut needs_redraw = false;
        while let Ok(res) = result_rx.try_recv() {
            if res.index < count {
                state.statuses[res.index] = Some(res.summary.clone());
                needs_redraw = true;
            }
            state.resolutions.push(res);
        }

        // Process all available key events
        while let Ok(key) = key_rx.try_recv() {
            needs_redraw = true;
            match key {
                // Move down
                Key::ArrowDown | Key::Tab | Key::Char('j') => {
                    state.cursor = (state.cursor + 1) % count;
                }
                // Move up
                Key::ArrowUp | Key::BackTab | Key::Char('k') => {
                    state.cursor = (state.cursor + count - 1) % count;
                }
                // Toggle current
                Key::Char(' ') => {
                    state.checked[state.cursor] = !state.checked[state.cursor];
                }
                // Toggle all
                Key::Char('a') => {
                    let all_checked = state.checked.iter().all(|&c| c);
                    for c in &mut state.checked {
                        *c = !all_checked;
                    }
                }
                // Confirm
                Key::Enter => {
                    let selected: Vec<usize> = state
                        .checked
                        .iter()
                        .enumerate()
                        .filter(|(_, c)| **c)
                        .map(|(i, _)| i)
                        .collect();
                    return Ok(Some(selected));
                }
                // Cancel
                Key::Escape | Key::Char('q') => {
                    return Ok(None);
                }
                _ => {
                    needs_redraw = false;
                }
            }
        }

        // Advance spinner if there are still unresolved items
        let has_pending =
            state.statuses.iter().any(Option::is_none) && !done.load(Ordering::Relaxed);
        if has_pending {
            state.spinner_frame = (state.spinner_frame + 1) % SPINNER_FRAMES.len();
            needs_redraw = true;
        }

        if needs_redraw {
            // Clear previous render and redraw
            term.clear_last_lines(count)?;
            render_items(
                term,
                labels,
                &state.checked,
                &state.statuses,
                state.cursor,
                state.spinner_frame,
            )?;
        }

        // Sleep to avoid busy-waiting (also controls spinner speed)
        std::thread::sleep(Duration::from_millis(SPINNER_TICK_MS));
    }
}

/// Render all items for the custom multi-select widget.
///
/// Matches dialoguer's plain theme styling:
/// - `>` arrow for active item, 2-space indent for inactive
/// - `[x]` / `[ ]` ASCII checkboxes
/// - No color on checkbox text; size summary in dim
fn render_items(
    term: &Term,
    labels: &[String],
    checked: &[bool],
    statuses: &[Option<String>],
    cursor: usize,
    spinner_frame: usize,
) -> io::Result<()> {
    for (i, label) in labels.iter().enumerate() {
        let is_active = i == cursor;

        let prefix = if is_active { ">" } else { " " };
        let checkbox = if checked[i] { "[x]" } else { "[ ]" };

        let status = statuses[i].as_ref().map_or_else(
            || {
                let frame = SPINNER_FRAMES[spinner_frame];
                format!("  {frame} resolving...").yellow().to_string()
            },
            |s| format!("  {s}").dimmed().to_string(),
        );

        term.write_line(&format!("{prefix} {checkbox} {label}{status}"))?;
    }

    term.flush()?;
    Ok(())
}

/// Custom multi-select widget for choosing worktrees to remove.
///
/// Displays all worktrees immediately with animated spinners while background
/// threads check each worktree for uncommitted changes. As checks complete,
/// spinners are replaced with warning text or disappear.
///
/// The main worktree is shown but **disabled**: it cannot be toggled and is
/// skipped by "toggle all".
///
/// Key bindings match `dialoguer::MultiSelect`:
/// * `↑`/`k` — move cursor up
/// * `↓`/`j`/`Tab` — move cursor down
/// * `Space` — toggle selection (no-op on disabled items)
/// * `a` — toggle all (excludes disabled items)
/// * `Enter` — confirm
/// * `Escape`/`q` — cancel
///
/// All items start **unchecked**.
///
/// # Arguments
///
/// * `worktrees` - The worktrees to display
/// * `warning_rx` - Channel receiving [`WarningResolution`]s from background threads
/// * `done` - Atomic flag signaling all background checks are complete
///
/// # Returns
///
/// `Ok((Some(indices), warnings))` on confirm, `Ok((None, warnings))` on cancel.
/// The `warnings` vector has the same length as `worktrees`, with resolved
/// warning text for each entry (`None` = clean or main worktree).
///
/// # Errors
///
/// * If terminal I/O fails
pub fn select_worktrees_for_removal(
    worktrees: &[WorktreeInfo],
    warning_rx: &mpsc::Receiver<WarningResolution>,
    done: &AtomicBool,
) -> io::Result<RemovalPickerResult> {
    let count = worktrees.len();
    if count == 0 {
        return Ok((Some(Vec::new()), Vec::new()));
    }

    let labels: Vec<String> = worktrees.iter().map(format_worktree_label).collect();
    let disabled: Vec<bool> = worktrees.iter().map(|wt| wt.is_main).collect();

    let mut state = RemovalSelectState {
        checked: vec![false; count],
        // Main worktrees start resolved (clean); linked start as pending.
        warnings: worktrees
            .iter()
            .map(|wt| {
                if wt.is_main {
                    WarningStatus::Clean
                } else {
                    WarningStatus::Pending
                }
            })
            .collect(),
        cursor: 0,
        spinner_frame: 0,
    };

    let term = Term::stderr();

    // Spawn a thread that reads keys and sends them over a channel.
    let (key_tx, key_rx) = mpsc::channel::<Key>();
    let input_done = std::sync::Arc::new(AtomicBool::new(false));
    let input_done_clone = input_done.clone();

    let input_term = term.clone();
    let input_handle = std::thread::spawn(move || {
        loop {
            if input_done_clone.load(Ordering::Relaxed) {
                break;
            }
            if let Ok(key) = input_term.read_key()
                && key_tx.send(key).is_err()
            {
                break;
            }
        }
    });

    term.hide_cursor()?;

    // Prompt header
    let prompt_line = format!(
        "{} {}",
        "?".green().bold(),
        "Select worktrees to remove (space to toggle, enter to confirm):".bold()
    );
    term.write_line(&prompt_line)?;
    render_removal_items(
        &term,
        &labels,
        &state.checked,
        &disabled,
        &state.warnings,
        state.cursor,
        state.spinner_frame,
    )?;

    let result = run_removal_select_loop(
        &term, &labels, &mut state, &disabled, &key_rx, warning_rx, done,
    );

    // Cleanup
    term.show_cursor()?;
    term.clear_last_lines(count + 1)?; // +1 for prompt line
    input_done.store(true, Ordering::Relaxed);
    drop(input_handle);

    // Flatten the tri-state warnings into final resolved warnings
    let final_warnings: Vec<Option<String>> = state
        .warnings
        .into_iter()
        .map(|w| match w {
            WarningStatus::Warning(text) => Some(text),
            WarningStatus::Pending | WarningStatus::Clean => None,
        })
        .collect();

    result.map(|sel| (sel, final_warnings))
}

/// Mutable state for the removal multi-select widget.
struct RemovalSelectState {
    checked: Vec<bool>,
    /// Per-worktree warning check status.
    warnings: Vec<WarningStatus>,
    cursor: usize,
    spinner_frame: usize,
}

/// Main loop for the removal multi-select widget.
///
/// Polls for key events and background warning results, re-renders on changes.
#[allow(clippy::too_many_arguments)]
fn run_removal_select_loop(
    term: &Term,
    labels: &[String],
    state: &mut RemovalSelectState,
    disabled: &[bool],
    key_rx: &mpsc::Receiver<Key>,
    warning_rx: &mpsc::Receiver<WarningResolution>,
    done: &AtomicBool,
) -> io::Result<Option<Vec<usize>>> {
    let count = labels.len();

    loop {
        // Drain all available background results
        let mut needs_redraw = false;
        while let Ok(res) = warning_rx.try_recv() {
            if res.index < count {
                state.warnings[res.index] = res
                    .warning
                    .map_or(WarningStatus::Clean, WarningStatus::Warning);
                needs_redraw = true;
            }
        }

        // Process all available key events
        while let Ok(key) = key_rx.try_recv() {
            needs_redraw = true;
            match key {
                // Move down
                Key::ArrowDown | Key::Tab | Key::Char('j') => {
                    state.cursor = (state.cursor + 1) % count;
                }
                // Move up
                Key::ArrowUp | Key::BackTab | Key::Char('k') => {
                    state.cursor = (state.cursor + count - 1) % count;
                }
                // Toggle current (only if not disabled)
                Key::Char(' ') => {
                    if !disabled[state.cursor] {
                        state.checked[state.cursor] = !state.checked[state.cursor];
                    }
                }
                // Toggle all (excludes disabled items)
                Key::Char('a') => {
                    let all_enabled_checked = state
                        .checked
                        .iter()
                        .enumerate()
                        .filter(|(i, _)| !disabled[*i])
                        .all(|(_, &c)| c);
                    for (i, c) in state.checked.iter_mut().enumerate() {
                        if !disabled[i] {
                            *c = !all_enabled_checked;
                        }
                    }
                }
                // Confirm
                Key::Enter => {
                    let selected: Vec<usize> = state
                        .checked
                        .iter()
                        .enumerate()
                        .filter(|(_, c)| **c)
                        .map(|(i, _)| i)
                        .collect();
                    return Ok(Some(selected));
                }
                // Cancel
                Key::Escape | Key::Char('q') => {
                    return Ok(None);
                }
                _ => {
                    needs_redraw = false;
                }
            }
        }

        // Advance spinner if there are still unresolved items
        let has_pending = state
            .warnings
            .iter()
            .any(|w| matches!(w, WarningStatus::Pending))
            && !done.load(Ordering::Relaxed);
        if has_pending {
            state.spinner_frame = (state.spinner_frame + 1) % SPINNER_FRAMES.len();
            needs_redraw = true;
        }

        if needs_redraw {
            // Clear previous render and redraw
            term.clear_last_lines(count)?;
            render_removal_items(
                term,
                labels,
                &state.checked,
                disabled,
                &state.warnings,
                state.cursor,
                state.spinner_frame,
            )?;
        }

        // Sleep to avoid busy-waiting (also controls spinner speed)
        std::thread::sleep(Duration::from_millis(SPINNER_TICK_MS));
    }
}

/// Render all items for the removal multi-select widget.
///
/// Matches dialoguer's plain theme styling:
/// - `>` arrow for active item, 2-space indent for inactive
/// - `[x]` / `[ ]` ASCII checkboxes
/// - Disabled items (main worktree) shown with dim text and `[-]` checkbox
/// - Pending checks shown with animated spinner
/// - Warning text (e.g., "has uncommitted changes") shown in yellow after the label
fn render_removal_items(
    term: &Term,
    labels: &[String],
    checked: &[bool],
    disabled: &[bool],
    warnings: &[WarningStatus],
    cursor: usize,
    spinner_frame: usize,
) -> io::Result<()> {
    for (i, label) in labels.iter().enumerate() {
        let is_active = i == cursor;
        let prefix = if is_active { ">" } else { " " };

        if disabled[i] {
            let line = format!("{prefix} [-] {label}").dimmed();
            term.write_line(&line.to_string())?;
        } else {
            let checkbox = if checked[i] { "[x]" } else { "[ ]" };
            let suffix = match warnings.get(i) {
                // Still checking — show spinner
                Some(WarningStatus::Pending) | None => {
                    let frame = SPINNER_FRAMES[spinner_frame];
                    format!("  {frame} checking...").yellow().to_string()
                }
                // Resolved with warning
                Some(WarningStatus::Warning(w)) => {
                    format!(" {}", format!("({w})").yellow())
                }
                // Resolved clean — no suffix
                Some(WarningStatus::Clean) => String::new(),
            };
            term.write_line(&format!("{prefix} {checkbox} {label}{suffix}"))?;
        }
    }

    term.flush()?;
    Ok(())
}

/// Prompt for the target worktree path.
///
/// # Errors
///
/// * If the user cancels the input
pub fn prompt_worktree_path() -> io::Result<PathBuf> {
    let path: String = Input::new()
        .with_prompt("Enter the path for the new worktree")
        .interact_text()?;

    Ok(PathBuf::from(path))
}

/// Prompt for which branch to base a new branch off.
///
/// # Arguments
///
/// * `default_branch` - The detected default branch (e.g., "master" or "main")
/// * `recent_branches` - Recently checked-out branches from reflog
/// * `profile_base` - If set by a profile, this branch is preselected as the default
///
/// # Returns
///
/// `None` for current HEAD, `Some(branch)` for a specific branch/ref
///
/// # Errors
///
/// * If the user cancels the prompts
fn prompt_base_branch(
    default_branch: Option<&str>,
    recent_branches: &[String],
    profile_base: Option<&str>,
) -> io::Result<Option<String>> {
    use std::collections::BTreeSet;

    let mut options = vec!["Current HEAD".to_string()];
    let mut seen = BTreeSet::new();

    // Add default branch first
    if let Some(branch) = default_branch {
        options.push(branch.to_string());
        seen.insert(branch.to_string());
    }

    // Add recent branches (excluding duplicates)
    for branch in recent_branches {
        if !seen.contains(branch) {
            options.push(branch.clone());
            seen.insert(branch.clone());
        }
    }

    // Add the profile base branch if it's not already in the list
    if let Some(base) = profile_base
        && !seen.contains(base)
    {
        options.push(base.to_string());
        seen.insert(base.to_string());
    }

    options.push("Enter custom branch/ref...".to_string());

    // Determine default selection: profile base branch if set, otherwise Current HEAD
    let default_idx = profile_base
        .and_then(|base| options.iter().position(|o| o == base))
        .unwrap_or(0);

    let choice = Select::new()
        .with_prompt("Base the new branch off")
        .items(&options)
        .default(default_idx)
        .interact()?;

    let last_idx = options.len() - 1;

    if choice == 0 {
        Ok(None) // Current HEAD
    } else if choice == last_idx {
        // Custom input
        let custom: String = Input::new()
            .with_prompt("Enter branch name or ref")
            .interact_text()?;
        Ok(Some(custom))
    } else {
        // Selected a branch from the list
        Ok(Some(options[choice].clone()))
    }
}

/// Resolve which remote to use.
///
/// If `override_name` is provided, uses that directly. Otherwise auto-detects:
/// * Single remote: uses it automatically
/// * Multiple remotes: prompts the user to pick one
/// * No remotes: returns an error
///
/// # Errors
///
/// * If listing remotes fails
/// * If the user cancels the prompt
/// * If the repository has no remotes configured
fn resolve_remote(repo: &Repository, override_name: Option<&str>) -> io::Result<String> {
    if let Some(name) = override_name {
        return Ok(name.to_string());
    }

    let remotes =
        get_remotes(repo).map_err(|e| io::Error::other(format!("Failed to list remotes: {e}")))?;

    match remotes.len() {
        0 => Err(io::Error::other("No remotes configured in this repository")),
        1 => Ok(remotes.into_iter().next().unwrap_or_default()),
        _ => {
            let idx = Select::new()
                .with_prompt("Select remote")
                .items(&remotes)
                .default(0)
                .interact()?;
            Ok(remotes[idx].clone())
        }
    }
}

/// Prompt for tracking a remote branch.
///
/// Resolves the remote (auto-detect or prompt), optionally fetches, then
/// presents a picker of remote branches. Falls back to default options
/// if no remote branches are found.
///
/// When `inferred_branch` is provided and a matching remote branch exists,
/// a confirm prompt is shown instead of the full branch picker.
///
/// # Arguments
///
/// * `repo` - The repository (needed for fetching and listing remote branches)
/// * `remote_override` - If set, use this remote name instead of auto-detecting
/// * `inferred_branch` - Branch name inferred from worktree directory (for auto-selection)
///
/// # Errors
///
/// * If the user cancels the prompts
/// * If fetching or listing remote branches fails
fn prompt_remote_branch(
    repo: &Repository,
    remote_override: Option<&str>,
    inferred_branch: Option<&str>,
) -> io::Result<WorktreeCreateOptions> {
    let remote = resolve_remote(repo, remote_override)?;

    let should_fetch = Confirm::new()
        .with_prompt(format!("Fetch latest from {remote}?"))
        .default(true)
        .interact()?;

    if should_fetch {
        println!("Fetching from {remote}...");
        fetch_remote(repo, &remote)
            .map_err(|e| io::Error::other(format!("Failed to fetch: {e}")))?;
    }

    let remote_branches = get_remote_branches(repo, &remote)
        .map_err(|e| io::Error::other(format!("Failed to list remote branches: {e}")))?;

    if remote_branches.is_empty() {
        println!("No remote branches found. Using auto-named branch instead.");
        return Ok(WorktreeCreateOptions::default());
    }

    let remote_prefix = format!("{remote}/");

    // Try to auto-select from inferred branch name
    if let Some(inferred) = inferred_branch {
        let inferred_remote = format!("{remote_prefix}{inferred}");
        if remote_branches.iter().any(|b| b == &inferred_remote) {
            let use_inferred = Confirm::new()
                .with_prompt(format!("Use inferred remote branch '{inferred_remote}'?"))
                .default(true)
                .interact()?;

            if use_inferred {
                return Ok(WorktreeCreateOptions {
                    branch: Some(inferred.to_string()),
                    ..Default::default()
                });
            }
            // User declined — fall through to the full picker
        } else {
            println!("No remote branch matching '{inferred_remote}' found. Showing all branches.");
        }
    }

    let branch_idx = Select::new()
        .with_prompt("Select remote branch")
        .items(&remote_branches)
        .interact()?;

    // Strip the known remote prefix (e.g., "origin/feature/auth/login" -> "feature/auth/login").
    // We use strip_prefix with the exact remote name rather than splitting on '/'
    // to correctly handle branch names that contain slashes.
    let selected = &remote_branches[branch_idx];
    let local_name = selected
        .strip_prefix(&remote_prefix)
        .unwrap_or(selected.as_str());

    Ok(WorktreeCreateOptions {
        branch: Some(local_name.to_string()),
        ..Default::default()
    })
}

/// Profile-derived hints that control worktree creation prompts.
#[derive(Debug, Clone, Default)]
pub struct CreationProfileHints<'a> {
    /// Skip the "Create worktree?" confirmation.
    pub auto_create: bool,
    /// Skip the creation method picker and use this method directly.
    pub creation_method: Option<&'a CreationMethod>,
    /// Preselect this base branch for new branch creation.
    pub base_branch: Option<&'a str>,
    /// When `true` with `creation_method = Auto`, use `base_branch` without prompting.
    pub new_branch: bool,
    /// Override the remote name for remote branch operations.
    pub remote_override: Option<&'a str>,
    /// Branch name inferred from worktree directory (for remote tracking).
    pub inferred_branch: Option<&'a str>,
}

/// Build the creation method options list and determine the default choice.
///
/// Returns `(display_labels, value_keys, default_index)`.
fn build_creation_options(
    worktree_name: &str,
    current_branch: Option<&str>,
    creation_method: Option<&CreationMethod>,
) -> (Vec<String>, Vec<&'static str>, usize) {
    let mut options: Vec<String> = Vec::new();
    let mut option_values: Vec<&str> = Vec::new();

    options.push(format!("New branch (auto-named '{worktree_name}')"));
    option_values.push("auto");

    options.push("New branch (custom name)...".to_string());
    option_values.push("new");

    if let Some(branch) = current_branch {
        options.push(format!("Use current branch ({branch})"));
        option_values.push("current");
    }

    options.push("Use existing branch...".to_string());
    option_values.push("existing");

    options.push("Track remote branch...".to_string());
    option_values.push("remote");

    options.push("Detached HEAD (current commit)".to_string());
    option_values.push("detach");

    let default_key = match creation_method {
        Some(CreationMethod::Remote) => "remote",
        Some(CreationMethod::Current) => "current",
        Some(CreationMethod::Detach) => "detach",
        _ => "auto",
    };

    let default_choice = option_values
        .iter()
        .position(|v| *v == default_key)
        .unwrap_or(0);

    (options, option_values, default_choice)
}

/// Dispatch a creation method directly, without showing the picker.
fn dispatch_creation_method(
    method: &CreationMethod,
    repo: &Repository,
    worktree_name: &str,
    current_branch: Option<&str>,
    hints: &CreationProfileHints<'_>,
) -> io::Result<WorktreeCreateOptions> {
    match method {
        CreationMethod::Auto => {
            let base_branch = hints.base_branch.map(String::from);
            if base_branch.is_some() {
                Ok(WorktreeCreateOptions {
                    new_branch: Some(worktree_name.to_string()),
                    branch: base_branch,
                    ..Default::default()
                })
            } else {
                // Current HEAD — let git handle auto-naming
                Ok(WorktreeCreateOptions::default())
            }
        }
        CreationMethod::Current => Ok(WorktreeCreateOptions {
            branch: current_branch.map(String::from),
            ..Default::default()
        }),
        CreationMethod::Remote => {
            prompt_remote_branch(repo, hints.remote_override, hints.inferred_branch)
        }
        CreationMethod::Detach => Ok(WorktreeCreateOptions {
            detach: true,
            ..Default::default()
        }),
    }
}

/// Prompt for worktree creation options.
///
/// Returns `None` if the user doesn't want to create a worktree.
///
/// Profile hints control which prompts are skipped:
/// * `auto_create` — skip the "Create it?" confirmation
/// * `creation_method` — skip the creation method picker
/// * `base_branch` / `new_branch` — skip the base branch prompt
/// * `inferred_branch` — auto-select a remote branch by name
///
/// # Errors
///
/// * If the user cancels the prompts
/// * If fetching remote branches fails
#[allow(clippy::too_many_arguments)]
pub fn prompt_worktree_create(
    repo: &Repository,
    target_path: &Path,
    current_branch: Option<&str>,
    branches: &[String],
    default_branch: Option<&str>,
    recent_branches: &[String],
    hints: &CreationProfileHints<'_>,
) -> io::Result<Option<WorktreeCreateOptions>> {
    // Step 1: Confirm creation (skip if auto_create)
    if !hints.auto_create {
        let should_create = Confirm::new()
            .with_prompt(format!(
                "Worktree does not exist at {}. Create it?",
                target_path.display()
            ))
            .default(true)
            .interact()?;

        if !should_create {
            return Ok(None);
        }
    }

    let worktree_name = target_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("worktree");

    // Step 2: If creation_method is fully determined, dispatch directly
    if let Some(method) = hints.creation_method {
        let options = dispatch_creation_method(method, repo, worktree_name, current_branch, hints)?;
        return Ok(Some(options));
    }

    // Step 3: Show creation method picker
    let (options, option_values, default_choice) =
        build_creation_options(worktree_name, current_branch, hints.creation_method);

    let choice = Select::new()
        .with_prompt("How should the worktree be created?")
        .items(&options)
        .default(default_choice)
        .interact()?;

    let selected_value = option_values[choice];

    let result = match selected_value {
        "auto" => {
            let base_branch = if hints.new_branch && hints.base_branch.is_some() {
                hints.base_branch.map(String::from)
            } else {
                prompt_base_branch(default_branch, recent_branches, hints.base_branch)?
            };

            if base_branch.is_some() {
                WorktreeCreateOptions {
                    new_branch: Some(worktree_name.to_string()),
                    branch: base_branch,
                    ..Default::default()
                }
            } else {
                WorktreeCreateOptions::default()
            }
        }
        "new" => {
            let branch_name: String = Input::new()
                .with_prompt("Enter new branch name")
                .interact_text()?;

            let base_branch =
                prompt_base_branch(default_branch, recent_branches, hints.base_branch)?;

            WorktreeCreateOptions {
                new_branch: Some(branch_name),
                branch: base_branch,
                ..Default::default()
            }
        }
        "current" => WorktreeCreateOptions {
            branch: current_branch.map(String::from),
            ..Default::default()
        },
        "existing" => {
            if branches.is_empty() {
                println!("No local branches found. Using auto-named branch instead.");
                WorktreeCreateOptions::default()
            } else {
                let branch_idx = Select::new()
                    .with_prompt("Select branch")
                    .items(branches)
                    .interact()?;

                WorktreeCreateOptions {
                    branch: Some(branches[branch_idx].clone()),
                    ..Default::default()
                }
            }
        }
        "remote" => prompt_remote_branch(repo, hints.remote_override, hints.inferred_branch)?,
        "detach" => WorktreeCreateOptions {
            detach: true,
            ..Default::default()
        },
        _ => unreachable!(),
    };

    Ok(Some(result))
}

/// Prompt whether to run post-setup commands.
///
/// # Errors
///
/// * If the user cancels the prompt
pub fn prompt_run_install(default: bool) -> io::Result<bool> {
    Ok(Confirm::new()
        .with_prompt("Run post-setup commands (e.g., bun install)?")
        .default(default)
        .interact()?)
}

/// Recovery action for a stale worktree registration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaleWorktreeAction {
    /// Run `git worktree prune` and retry.
    Prune,
    /// Retry with `--force`.
    Force,
    /// Cancel and return the original error.
    Cancel,
}

/// Prompt the user for how to handle a stale worktree registration.
///
/// Shown when `git worktree add` fails because the path is already
/// registered but missing from disk.
///
/// # Errors
///
/// * If the user cancels the prompt
#[must_use = "caller must act on the chosen recovery action"]
pub fn prompt_stale_worktree_recovery() -> io::Result<StaleWorktreeAction> {
    let options = [
        "Prune stale worktrees and retry",
        "Force create (overwrite registration)",
        "Cancel",
    ];

    let choice = Select::new()
        .with_prompt("This path is registered as a stale worktree. How would you like to proceed?")
        .items(options)
        .default(0)
        .interact()?;

    Ok(match choice {
        0 => StaleWorktreeAction::Prune,
        1 => StaleWorktreeAction::Force,
        _ => StaleWorktreeAction::Cancel,
    })
}

/// Result of the setup operations prompt.
#[derive(Debug, Clone)]
pub struct SetupOperationChoices {
    /// Whether to run file operations (symlinks, copies, templates).
    pub run_files: bool,
    /// Whether to overwrite existing files during file operations.
    pub overwrite_existing: bool,
    /// Whether to run post-setup commands.
    pub run_post_setup: bool,
}

/// Input for each setup operation: pre-determined by profile or needs prompting.
#[derive(Debug, Clone)]
pub struct SetupOperationInputs {
    /// Whether the target is a secondary worktree (controls file ops visibility).
    pub is_secondary_worktree: bool,
    /// File operations: `Some(value)` = determined, `None` = prompt.
    pub files: Option<bool>,
    /// Overwrite existing: `Some(value)` = determined, `None` = prompt.
    pub overwrite: Option<bool>,
    /// Post-setup commands: `Some(value)` = determined, `None` = prompt.
    pub post_setup: Option<bool>,
}

/// Determine setup operations, prompting only for undetermined values.
///
/// If all values are pre-determined (by profile + CLI flags), no prompt
/// is shown. Otherwise, only undetermined items appear in the checklist.
///
/// # Arguments
///
/// * `inputs` - Which operations are determined vs need prompting
/// * `post_setup_commands` - Post-setup commands (shown inline for context)
///
/// # Errors
///
/// * If the user cancels the prompt
pub fn prompt_setup_operations(
    inputs: &SetupOperationInputs,
    post_setup_commands: &[&str],
) -> io::Result<SetupOperationChoices> {
    // Start with pre-determined values
    let mut result = SetupOperationChoices {
        run_files: inputs.files.unwrap_or(inputs.is_secondary_worktree),
        overwrite_existing: inputs.overwrite.unwrap_or(false),
        run_post_setup: inputs.post_setup.unwrap_or(!post_setup_commands.is_empty()),
    };

    // Build checklist of only undetermined items
    let mut items: Vec<String> = Vec::new();
    let mut checked: Vec<bool> = Vec::new();

    // Track which checklist index maps to which operation
    let mut file_ops_index: Option<usize> = None;
    let mut overwrite_index: Option<usize> = None;
    let mut post_setup_index: Option<usize> = None;

    if inputs.is_secondary_worktree && inputs.files.is_none() {
        file_ops_index = Some(items.len());
        items.push("Apply file operations (symlinks, copies, templates)".to_string());
        checked.push(result.run_files);
    }

    if inputs.is_secondary_worktree && inputs.overwrite.is_none() {
        overwrite_index = Some(items.len());
        items.push("Overwrite existing files".to_string());
        checked.push(result.overwrite_existing);
    }

    if !post_setup_commands.is_empty() && inputs.post_setup.is_none() {
        post_setup_index = Some(items.len());
        let cmds_display = post_setup_commands.join(", ");
        items.push(format!("Run post-setup commands ({cmds_display})"));
        checked.push(result.run_post_setup);
    }

    // If nothing needs prompting, return the pre-determined values
    if items.is_empty() {
        return Ok(result);
    }

    let selections = MultiSelect::new()
        .with_prompt("Select what to run")
        .items(&items)
        .defaults(&checked)
        .interact()?;

    // Update only the prompted items
    if let Some(i) = file_ops_index {
        result.run_files = selections.contains(&i);
    }
    if let Some(i) = overwrite_index {
        result.overwrite_existing = result.run_files && selections.contains(&i);
    }
    if let Some(i) = post_setup_index {
        result.run_post_setup = selections.contains(&i);
    }

    Ok(result)
}